def prepare(self): """The preparation phase of the plug-in goes here.""" item.prepare(self) if self.var.event == u'Saccade start': self.wait_func = self.experiment.pygaze_eyetracker. \ wait_for_saccade_start elif self.var.event == u'Saccade end': self.wait_func = self.experiment.pygaze_eyetracker. \ wait_for_saccade_end elif self.var.event == u'Fixation start': self.wait_func = self.experiment.pygaze_eyetracker. \ wait_for_fixation_start elif self.var.event == u'Fixation end': self.wait_func = self.experiment.pygaze_eyetracker. \ wait_for_fixation_end elif self.var.event == u'Blink start': self.wait_func = self.experiment.pygaze_eyetracker. \ wait_for_blink_start elif self.var.event == u'Blink end': self.wait_func = self.experiment.pygaze_eyetracker. \ wait_for_blink_start else: raise osexception(u'Unknown event: %s' % self.var.event)
def prepare(self): """The preparation phase of the plug-in goes here.""" item.prepare(self) self.prepare_drift_correction_canvas() self.experiment.pygaze_eyetracker.set_draw_drift_correction_target_func( self.draw_drift_correction_canvas)
def prepare(self): """Preparation phase""" # Call the parent constructor. item.prepare(self) self.close() self.init_var() if self.dummy_mode == u'no': try: from rusocsci import buttonbox except ImportError: self.show_message( u'The RuSocSci package could not be imported. Please install package.' ) try: self.experiment.radboudbox = buttonbox.Buttonbox( id=self.id, port=self.port) self.clock.sleep(4000) self.experiment.cleanup_functions.append(self.close) self.python_workspace[ u'radboudbox'] = self.experiment.radboudbox except OSError: debug.msg(u'Could not access the Radboud Buttonbox') elif self.dummy_mode == u'yes': self.show_message(u'Dummy mode enabled, prepare phase') else: self.show_message(u'Error with dummy mode, dummy mode: %s' % self.dummy_mode)
def prepare(self): """Preparation phase""" # Call the parent constructor. item.prepare(self) self.close() self.init_var() if self.dummy_mode == u'no': try: from rusocsci import buttonbox except ImportError: self.show_message(u'The RuSocSci package could not be imported. Please install package.') try: self.experiment.radboudbox = buttonbox.Buttonbox(id=self.id, port=self.port) self.clock.sleep(4000) self.experiment.cleanup_functions.append(self.close) self.python_workspace[u'radboudbox'] = self.experiment.radboudbox except OSError: debug.msg(u'Could not access the Radboud Buttonbox') elif self.dummy_mode == u'yes': self.show_message(u'Dummy mode enabled, prepare phase') else: self.show_message(u'Error with dummy mode, dummy mode: %s' % self.dummy_mode)
def prepare(self): """Preparation phase""" # Call the parent constructor. item.prepare(self) self.init_var()
def prepare(self): """Prepare a canvas with a fixation dot.""" # Call parent functions. item.prepare(self) generic_response.prepare(self) # Create a canvas. self.c = canvas(self.experiment, self.get(u'background'), \ self.get(u'foreground')) # Set the coordinates. self._x = self.get(u'x') + self.c.xcenter() self._y = self.get(u'y') + self.c.ycenter() # Draw the fixation dot. self.c.set_penwidth(self.get(u'penwidth')) if self.style == u'default': self.c.fixdot(self._x, self._y) elif self.style == u'filled': self.c.ellipse(self._x - 10, self._y - 10, 20, 20, True) elif self.style == u'filled-small': self.c.ellipse(self._x - 5, self._y - 5, 10, 10, True) elif self.style == u'empty': self.c.ellipse(self._x - 10, self._y - 10, 20, 20, False) elif self.style == u'empty-small': self.c.ellipse(self._x - 5, self._y - 5, 10, 10, False) elif self.style == u'cross': self.c.line(self._x - 10, self._y, self._x + 10, self._y) self.c.line(self._x, self._y - 10, self._x, self._y + 10) elif self.style == u'cross-small': self.c.line(self._x - 5, self._y, self._x + 5, self._y) self.c.line(self._x, self._y - 5, self._x, self._y + 5)
def prepare(self): # Call parent functions. item.prepare(self) # Prepare your plug-in here. generic_response.prepare(self) path = self.experiment.pool[self.var.media_src] self.c = canvas(self.experiment, background_color=self.var.background, color=self.var.foreground) if not os.path.isfile(path): raise osexception(u"Media file '%s' was not found." % (os.path.basename(path), self.name)) if self.var.HMDtype == u"Oculus DK1 (1280x800px)" and self.var.stereoscopic == u"No (No 3D depth)" and self.var.isVideo == u"No": self.c.image(path, x=-252, y=0.0) self.c.image(path, x=252, y=0.0) elif self.var.HMDtype == u"Oculus DK1 (1280x800px)" and self.var.stereoscopic == u"Yes" and self.var.isVideo == u"No": self.c.image(path, x=0, y=0.0) elif self.var.HMDtype == u"Oculus DK2 (1920x1080px)" and self.var.stereoscopic == u"No" and self.var.isVideo == u"No": self.c.image(path, x=-378, y=0.0) self.c.image(path, x=378, y=0.0) elif self.var.HMDtype == u"Oculus DK2 (1920x1080px)" and self.var.stereoscopic == u"Yes" and self.var.isVideo == u"No": self.c.image(path, x=0, y=0.0) elif self.var.HMDtype == u"Oculus Rift 2016 (2160x1200px)" and self.var.stereoscopic == u"No" and self.var.isVideo == u"No": self.c.image(path, x=-415.8, y=0.0) self.c.image(path, x=415.8, y=0.0) elif self.var.HMDtype == u"Oculus Rift 2016 (2160x1200px)" and self.var.stereoscopic == u"Yes" and self.var.isVideo == u"No": self.c.image(path, x=0, y=0.0) elif self.var.HMDtype == u"HTC Vive (2160x1200px)" and self.var.stereoscopic == u"No" and self.var.isVideo == u"No": self.c.image(path, x=-415.8, y=0.0) self.c.image(path, x=415.8, y=0.0) elif self.var.HMDtype == u"HTC Vive (2160x1200px)" and self.var.stereoscopic == u"Yes" and self.var.isVideo == u"No": self.c.image(path, x=0, y=0.0)
def prepare(self): """Prepares the text display canvas.""" # Pass the word on to the parent item.prepare(self) # Create an offline canvas self.c = openexp.canvas.canvas(self.experiment, self.get( \ u"background"), self.get(u"foreground")) self.c.set_font(self.get(u"font_family"), self.get(u"font_size")) # Make sure that the content is a unicode string that is evaluated # for variables and then split into separated lines, using either the # os-specific or the Unix-style line separator. content = self.unistr(self.get(u'content')) content = content.replace(os.linesep, u'\n') content = self.eval_text(content).split(u"\n") # Do line wrapping _content = [] for line in content: while len(line) > self.get(u"maxchar"): i = line.rfind(" ", 0, self.get(u"maxchar")) if i < 0: raise osexception( \ u"Failed to do line wrapping in text_display '%s'. Perhaps one of the words is longer than the maximum number of characters per line?" \ % self.name) _content.append(line[:i]) line = line[i+1:] _content.append(line) content = _content if self.get(u"align") != u"center": try: max_width = 0 max_height = 0 for line in content: size = self.c.text_size(line) max_width = max(max_width, size[0]) max_height = max(max_height, size[1]) except: raise osexception( \ u"Failed to use alignment '%s' in text_display '%s'. Perhaps this alignment is not supported by the back-end. Please use 'center' alignment." \ % (self.get(u"align"), self.name)) line_nr = -len(content) / 2 for line in content: if self.get(u"align") == u"center": self.c.textline(line, line_nr) elif self.get(u"align") == u"left": self.c.text(line, False, self.c.xcenter()-0.5*max_width, \ self.c.ycenter()+1.5*line_nr*max_height) else: width = self.c.text_size(line)[0] self.c.text(line, False, self.c.xcenter()+0.5*max_width-width, \ self.c.ycenter()+1.5*line_nr*max_height) line_nr += 1 generic_response.prepare(self)
def prepare(self): """Preparation phase""" # Call the parent constructor. item.prepare(self) self.pptrigger_port = self.var.pptrigger_port self.pptrigger_dummy = self.var.pptrigger_dummy self.experiment.pptrigger_dummy = self.var.pptrigger_dummy self.experiment.pptrigger_port = self.pptrigger_port if self.pptrigger_dummy == u'no': if os.name == 'posix': # import the local modified version of pyparallel # that allows for non-exclusive connections to the parport path_to_file = os.path.join(os.path.dirname(__file__), 'parallelppdev.py') parallel = imp.load_source('parallel', path_to_file) try: import parallelppdev as parallel except ImportError as e: raise osexception( u'The local modified version of pyparallel could not be loaded. Check if the file is present and if the file permissions are correct.', exception=e) elif os.name == 'nt': try: from ctypes import windll except ImportError as e: raise osexception( u'The ctypes module can not be loaded. Check if ctypes is installed correctly.', exception=e) else: try: import parallel except ImportError as e: raise osexception( 'The pyparallel module could not be loaded, please make sure pyparallel is installed correctly.', exception=e) if not hasattr(self.experiment, "pptrigger"): try: if os.name == 'nt': self.experiment.pptrigger = windll.dlportio else: self.experiment.pptrigger = parallel.Parallel( port=self.pptrigger_port.encode('ascii'), exclusive=True) pass except Exception as e: raise osexception(u'Could not access the Parallel Port', exception=e) self.experiment.cleanup_functions.append(self.close) self.python_workspace[u'pptrigger'] = self.experiment.pptrigger elif self.pptrigger_dummy == u'yes': debug.msg(u'Dummy mode enabled, prepare phase') else: debug.msg(u'Error with dummy mode, mode is: %s' % self.pptrigger_dummy)
def prepare(self): """The preparation phase of the plug-in goes here.""" # Call the parent constructor. item.prepare(self) # Here simply prepare a canvas with a fixatio dot. self.c = canvas(self.experiment) self.c.fixdot()
def prepare(self): """See item.""" item.prepare(self) self._timeout = self._prepare_timeout() self._allowed_responses = self._prepare_allowed_responses() self._collect_response = self.prepare_response_func() self._t0 = None
def prepare(self): """Preparation phase""" # Call the parent constructor. item.prepare(self) self.pptrigger_port = self.var.pptrigger_port self.pptrigger_dummy = self.var.pptrigger_dummy self.experiment.pptrigger_dummy = self.var.pptrigger_dummy self.experiment.pptrigger_port = self.pptrigger_port if self.pptrigger_dummy == u'no': if os.name == 'posix': # import the local modified version of pyparallel # that allows for non-exclusive connections to the parport path_to_file = os.path.join(os.path.dirname(__file__), 'parallelppdev.py') parallel = imp.load_source('parallel', path_to_file) try: import parallelppdev as parallel except ImportError as e: raise osexception(u'The local modified version of pyparallel could not be loaded. Check if the file is present and if the file permissions are correct.', exception=e) elif os.name == 'nt': try: from ctypes import windll except ImportError as e: raise osexception(u'The ctypes module can not be loaded. Check if ctypes is installed correctly.', exception=e) else: try: import parallel except ImportError as e: raise osexception('The pyparallel module could not be loaded, please make sure pyparallel is installed correctly.', exception=e) if not hasattr(self.experiment, "pptrigger"): try: if os.name == 'nt': self.experiment.pptrigger = windll.dlportio else: #print(self.pptrigger_port.encode('ascii')) if isinstance(self.pptrigger_port,str): pptrigger_port = self.pptrigger_port.encode('ascii') elif isinstance(self.pptrigger_port,int): pptrigger_port = self.pptrigger_port else: raise osexception('Port value is not an integer or string') self.experiment.pptrigger = parallel.Parallel(port=pptrigger_port) #self.experiment.pptrigger = parallel.Parallel() pass except Exception as e: raise osexception( u'Could not access the Parallel Port', exception=e) self.experiment.cleanup_functions.append(self.close) self.python_workspace[u'pptrigger'] = self.experiment.pptrigger elif self.pptrigger_dummy == u'yes': debug.msg(u'Dummy mode enabled, prepare phase') else: debug.msg(u'Error with dummy mode, mode is: %s' % self.pptrigger_dummy)
def prepare(self): """Prepares the text display canvas.""" # Pass the word on to the parent item.prepare(self) # Create an offline canvas self.c = openexp.canvas.canvas(self.experiment, self.get( \ u"background"), self.get(u"foreground")) self.c.set_font(self.get(u"font_family"), self.get(u"font_size")) # Make sure that the content is a unicode string that is evaluated # for variables and then split into separated lines, using either the # os-specific or the Unix-style line separator. content = self.unistr(self.get(u'content')) content = content.replace(os.linesep, u'\n') content = self.eval_text(content).split(u"\n") # Do line wrapping _content = [] for line in content: while len(line) > self.get(u"maxchar"): i = line.rfind(" ", 0, self.get(u"maxchar")) if i < 0: raise osexception( \ u"Failed to do line wrapping in text_display '%s'. Perhaps one of the words is longer than the maximum number of characters per line?" \ % self.name) _content.append(line[:i]) line = line[i + 1:] _content.append(line) content = _content if self.get(u"align") != u"center": try: max_width = 0 max_height = 0 for line in content: size = self.c.text_size(line) max_width = max(max_width, size[0]) max_height = max(max_height, size[1]) except: raise osexception( \ u"Failed to use alignment '%s' in text_display '%s'. Perhaps this alignment is not supported by the back-end. Please use 'center' alignment." \ % (self.get(u"align"), self.name)) line_nr = -len(content) / 2 for line in content: if self.get(u"align") == u"center": self.c.textline(line, line_nr) elif self.get(u"align") == u"left": self.c.text(line, False, self.c.xcenter()-0.5*max_width, \ self.c.ycenter()+1.5*line_nr*max_height) else: width = self.c.text_size(line)[0] self.c.text(line, False, self.c.xcenter()+0.5*max_width-width, \ self.c.ycenter()+1.5*line_nr*max_height) line_nr += 1 generic_response.prepare(self)
def prepare(self): """Preparation phase""" # Call the parent constructor. item.prepare(self) self.init_var() # create keyboard object self.kb = keyboard(self.experiment, timeout=1)
def prepare(self): """The preparation phase of the plug-in goes here.""" # Call the parent constructor. item.prepare(self) # Here simply prepare a canvas with a fixatio dot. self.c = canvas(self.experiment) self.c.text('Hello world') debug.msg('Prepared')
def prepare(self): """Preparation phase""" # Call the parent constructor. item.prepare(self) # create keyboard object self.kb = keyboard(self.experiment,timeout=1) self.init_var()
def prepare(self): """The preparation phase of the plug-in goes here.""" item.prepare(self) # Checking the excistence of the VAS elements is only possible in the runphase # as only then the full canvas is availeable self.c = Canvas(self.experiment) self.slmouse = Mouse(self.experiment, timeout=20, visible=True) self.slmouse.show_cursor(True) self.slmouse.set_pos(pos=(0, 0)) my_canvas = self.experiment.items[self.var.VAS_CANVAS_NAME].canvas try: if my_canvas[self.var.VAS_BODY_NAME] == None or my_canvas[ self.var.VAS_EXITBUTTON_NAME] == None: oslogger.info("Should not occur") except Exception as e: raise osexception( u"Prepare: READ the VAS manual:\n\rNo VAS elements found on the named canvas" ) self.useLabels = True try: if my_canvas[self.var.VAS_MAXLABEL_NAME] == None or my_canvas[ self.var.VAS_MAXLABEL_NAME] == None: oslogger.info("Should not occur") except Exception as e: self.uselabels = False self.c = self.experiment.items[self.var.VAS_CANVAS_NAME].canvas self.ypos = -1 # is the vasbody a line or a rect? if hasattr(self.c[self.var.VAS_BODY_NAME], 'ex') and hasattr( self.c[self.var.VAS_BODY_NAME], 'sx'): self.VASLENGTH = self.c[self.var.VAS_BODY_NAME].ex - self.c[ self.var.VAS_BODY_NAME].sx self.ypos = (self.c[self.var.VAS_BODY_NAME].sy + self.c[self.var.VAS_BODY_NAME].ey) / 2 self.sx = self.c[self.var.VAS_BODY_NAME].sx if hasattr(self.c[self.var.VAS_BODY_NAME], 'w') and hasattr( self.c[self.var.VAS_BODY_NAME], 'y') and hasattr( self.c[self.var.VAS_BODY_NAME], 'h'): self.VASLENGTH = self.c[self.var.VAS_BODY_NAME].w self.ypos = self.c[self.var.VAS_BODY_NAME].y + ( self.c[self.var.VAS_BODY_NAME].h / 2) self.sx = self.c[self.var.VAS_BODY_NAME].x if self.ypos == -1: raise TypeError("VasBody should be a line or a Rect")
def prepare(self): """The preparation phase of the plug-in goes here.""" # Call the parent constructor. item.prepare(self) # User input self.responses = [self._yes, self._no] self.rows = [2] + [1]*len(self.responses) self.m = mouse(self.experiment) self.c = canvas(self.experiment)
def prepare(self): """Preparation phase""" # Call the parent constructor. item.prepare(self) # create keyboard object self.kb = keyboard(self.experiment, timeout=1) if hasattr(self.experiment, "pptrigger_dummy"): self.pptrigger_dummy = self.experiment.pptrigger_dummy else: raise osexception(u'Parallel Port init is missing')
def prepare(self): """The preparation phase of the plug-in goes here.""" item.prepare(self) self.EE = EvtExchanger() Devices = self.EE.Select(self.var.VAS_ENCODER_ID) try: self.EE.RENC_SetUp(1024, 0, int(1024*(self.var.VAS_CURSOR_STARTPOSITION/100.0)), 1, 1) if Devices[0] is None: raise except: self.var.VAS_ENCODER_ID = u"MOUSE" oslogger.info("Cannot find encoder input device: Using mouse") # Checking the excistence of the VAS elements is only possible in the runphase # as only then the full canvas is availeable self.c = Canvas(self.experiment) self._Keyboard = Keyboard(self.experiment, timeout = 0); self._Mouse = Mouse(self.experiment) my_canvas = self.experiment.items[self.var.VAS_CANVAS_NAME].canvas try: if my_canvas[self.var.VAS_CURSOR_NAME] == None or my_canvas[self.var.VAS_BODY_NAME] == None: oslogger.info("Should not occur") except Exception as e: raise osexception(u"Prepare: READ the VAS manual:\n\rNo VAS elements found on the named canvas") self.c = self.experiment.items[self.var.VAS_CANVAS_NAME].canvas self.c[self.var.VAS_CURSOR_NAME].sx = (self.c[self.var.VAS_BODY_NAME].sx+self.c[self.var.VAS_BODY_NAME].ex) / 2.0 self.c[self.var.VAS_CURSOR_NAME].ex = self.c[self.var.VAS_CURSOR_NAME].sx self.VASLENGTH = self.c[self.var.VAS_BODY_NAME].ex - self.c[self.var.VAS_BODY_NAME].sx self.SHOWTIMER = False if self.var.VAS_EXIT_METHOD == 'TIME': if my_canvas[self.var.VAS_CURSOR_NAME] != None: self.SHOWTIMER = True self.w = self.c[self.var.VAS_TIMER_NAME].ex - self.c[self.var.VAS_TIMER_NAME].sx self.h = self.c[self.var.VAS_TIMER_NAME].ey - self.c[self.var.VAS_TIMER_NAME].sy self.TIMER_DIR = 'vert' self.TIMERSIZE = self.h if (abs(self.w) > abs(self.h)): self.TIMER_DIR = 'horiz' self.TIMERSIZE = self.w
def prepare(self): """Preparation phase""" # Call the parent constructor. item.prepare(self) # create keyboard object self.kb = keyboard(self.experiment, timeout=1) self.init_var() if self.pause_resume != u'': # Prepare the pause resume responses self._allowed_responses_pause_resume = [] for r in safe_decode(self.pause_resume).split(u';'): if r.strip() != u'': self._allowed_responses_pause_resume.append(r) if not self._allowed_responses_pause_resume: self._allowed_responses_pause_resume = None self.show_message(u"allowed pause/resume keys set to %s" % self._allowed_responses_pause_resume) if self.stop != u'': # Prepare the pause resume responses self._allowed_responses_stop = [] for r in safe_decode(self.stop).split(u';'): if r.strip() != u'': self._allowed_responses_stop.append(r) if not self._allowed_responses_stop: self._allowed_responses_stop = None self.show_message(u"allowed stop keys set to %s" % self._allowed_responses_stop) if self.dummy_mode == u'no': try: self.show_message(u'\n') self.show_message(u'Creating wave file: ' + self.filename + ' ...') self.wav_file = wave.open(self.filename, 'wb') self.show_message(u'Succesfully created wave file...') except Exception as e: raise osexception(u'Could not create wave file', exception=e) self.wav_file.setsampwidth(self.samplewidth) self.wav_file.setframerate(self.samplerate) self.wav_file.setnchannels(self.channels) self.show_message(u'Period size: %d frames' % (self.period_size)) self.show_message(u'Period duration: %s ms' % (str(self.period_size_time)))
def prepare(self): """ desc: Prepare the item. """ item.prepare(self) #self.prepare_timeout() # create keyboard object #self.kb = keyboard(self.experiment,timeout=1) self.init_var()
def prepare(self): """Preparation phase""" # Call the parent constructor. item.prepare(self) # create keyboard object self.kb = keyboard(self.experiment,timeout=1) if hasattr(self.experiment, "pptrigger_dummy"): self.pptrigger_dummy = self.experiment.pptrigger_dummy else: raise osexception( u'Parallel Port init is missing')
def prepare(self): """ desc: Prepares the item. """ item.prepare(self) if self.module is None: path = self.experiment.pool[self.var.file] self.experiment.python_workspace.run_file(path) self.prepare_bytecode = self.experiment.python_workspace._compile( u'%s()' % self.var.prepare_func) self.run_bytecode = self.experiment.python_workspace._compile( u'%s()' % self.var.run_func) self.experiment.python_workspace._exec(self.prepare_bytecode)
def prepare(self): """See item.""" item.prepare(self) self._schedule = [] for item_name, start_time, end_time, cond in self.schedule: if not self.python_workspace._eval(self.syntax.compile_cond(cond)): continue t = item_task( self.experiment.items[item_name], self.syntax.auto_type(self.syntax.eval_text(start_time)), self.syntax.auto_type(self.syntax.eval_text(end_time))) self._schedule.append(t) if self.var.function_name != u"": t = inline_task(self.var.function_name, self.python_workspace, 0, self.var.duration) self._schedule.append(t)
def prepare(self): """Preparation phase""" # Call the parent constructor. item.prepare(self) self.pptrigger_value = self.var.pptrigger_value self.pptrigger_duration_check = self.var.pptrigger_duration_check self.pptrigger_duration = self.var.pptrigger_duration if hasattr(self.experiment, "pptrigger_dummy"): self.pptrigger_dummy = self.experiment.pptrigger_dummy else: raise osexception( u'Parallel Port init is missing')
def prepare(self): # Call parent functions. item.prepare(self) # Get the path of the file, named "libkinect.py", which contain the Kinect library path = os.path.join(os.path.dirname(__file__), u'libkinect.py') # Load the Kinect library libkinect = imp.load_source(u'libkinect', path) # Debugging output is only visible when OpenSesame is started with the # --debug argument. debug.msg(u'Loading the Kinect library from : %s' % path) # Create an instance of a Kinect by calling the init function of the library self.experiment.kinect = libkinect.libkinect(self.experiment) # Call the function close when the experiment is finished self.experiment.cleanup_functions.append(self.close)
def prepare(self): """See item.""" item.prepare(self) self.event('prepare coroutines') self._schedule = [] for item_name, start_time, end_time, cond in self.schedule: if not self.python_workspace._eval(self.syntax.compile_cond(cond)): continue t = item_task(self, self.experiment.items[item_name], self.syntax.auto_type(self.syntax.eval_text(start_time)), self.syntax.auto_type(self.syntax.eval_text(end_time)) ) self._schedule.append(t) if self.var.function_name != u"": t = inline_task(self, self.var.function_name, self.python_workspace, 0, self.var.duration) self._schedule.append(t)
def prepare(self): """ desc: Prepare a canvas with a fixation dot. """ # Call parent functions. item.prepare(self) generic_response.prepare(self) # Create a canvas. self.c = canvas(self.experiment, background_color=self.var.background, color=self.var.foreground, penwidth=self.var.penwidth) self.c.color = self.var.foreground self.c.background_color = self.var.background # Set the coordinates. self._x = self.var.x self._y = self.var.y if self.var.uniform_coordinates != u'yes': self._x += self.c.width/2 self._y += self.c.height/2 # For backwards compatibility, we support a few special fixdot styles if self.var.style == u'filled': self.c.ellipse(self._x - 10, self._y - 10, 20, 20, fill=True) elif self.var.style == u'filled-small': self.c.ellipse(self._x - 5, self._y - 5, 10, 10, fill=True) elif self.var.style == u'empty': self.c.ellipse(self._x - 10, self._y - 10, 20, 20, fill=False) elif self.var.style == u'empty-small': self.c.ellipse(self._x - 5, self._y - 5, 10, 10, fill=False) elif self.var.style == u'cross': self.c.line(self._x - 10, self._y, self._x + 10, self._y) self.c.line(self._x, self._y - 10, self._x, self._y + 10) elif self.var.style == u'cross-small': self.c.line(self._x - 5, self._y, self._x + 5, self._y) self.c.line(self._x, self._y - 5, self._x, self._y + 5) # But the new way is to use the style keyword else: self.c.fixdot(self._x, self._y, style=self.var.style)
def prepare(self): """ desc: Prepare the item. """ item.prepare(self) self.prepare_timeout() self.init_var() # Prepare the allowed responses self._allowed_responses = None if u'allowed_responses' in self.var: self._allowed_responses = [] for r in safe_decode(self.allowed_responses).split(u';'): if r.strip() != u'': self._allowed_responses.append(r) if not self._allowed_responses: self._allowed_responses = None self.show_message(u"allowed responses set to %s" % self._allowed_responses) # Prepare keyboard for dummy-mode and flushing self._keyboard = openexp.keyboard.keyboard(self.experiment) if self.dummy_mode == u'yes': self._resp_func = self._keyboard.get_key return else: if self.timeout == u'infinite' or self.timeout == None: self._timeout = float("inf") else: self._timeout = float(self.timeout) / 1000 # Prepare auto response if self.experiment.auto_response: self._resp_func = self.auto_responder else: self._resp_func = self.experiment.radboudbox.waitButtons
def prepare(self): """The preparation phase of the plug-in goes here.""" # Call the parent constructor. item.prepare(self) # get the global pp instance and initialize it if # necessary#-*- coding:utf-8 -*- if os.name == 'nt': global _winpp if _winpp is None: try: _winpp = windll.dlportio print('Successfully accessed the parallel port on address: %s' % self.get("_port")) except OSError: print('Could not access the parallel port on address: %s' % self.get("_port")) self.winpp = _winpp else: global _pp if _pp is None: try: _pp = parallel.Parallel() print('Successfully accessed the parallel port (/dev/parport0).') except OSError: print('Could not access /dev/parport0.') self.pp = _pp # create keyboard object self.kb = keyboard(self.experiment, keylist=['escape']) # Report success return True
def prepare(self): """The preparation phase of the plug-in goes here.""" item.prepare(self) if self.var.event == 'Saccade start': self.wait_func = self.experiment.pygaze_eyetracker. \ wait_for_saccade_start elif self.var.event == 'Saccade end': self.wait_func = self.experiment.pygaze_eyetracker. \ wait_for_saccade_end elif self.var.event == 'Fixation start': self.wait_func = self.experiment.pygaze_eyetracker. \ wait_for_fixation_start elif self.var.event == 'Fixation end': self.wait_func = self.experiment.pygaze_eyetracker. \ wait_for_fixation_end elif self.var.event == 'Blink start': self.wait_func = self.experiment.pygaze_eyetracker. \ wait_for_blink_start elif self.var.event == 'Blink end': self.wait_func = self.experiment.pygaze_eyetracker. \ wait_for_blink_start else: raise osexception('Unknown event: %s' % self.var.event)
def prepare(self): """The preparation phase of the plug-in goes here.""" item.prepare(self)
def prepare(self): """ desc: Opens the video file for playback and compiles the event handler code. returns: desc: True on success, False on failure. type: bool """ # Call parent functions. item.prepare(self) # Byte-compile the event handling code (if any) event_handler = self.var.get('event_handler', _eval=False) if event_handler: custom_event_handler = self.python_workspace._compile( event_handler ) else: custom_event_handler = None if self.var.playaudio == u"yes": playaudio = True else: playaudio = False # Initialize player object self.player = mediadecoder.Decoder(play_audio=playaudio) self.player.loop = (self.var.loop == "yes") # Load video file to play if self.var.video_src == u"": raise osexception(u"No video file was set") else: # Find the full path to the video file. This will point to some # temporary folder where the file pool has been placed path = self.experiment.get_file(self.var.video_src) if not os.path.exists(path): raise osexception(u"Invalid path to video file: {0} (file not " "found)".format(path)) # Load the video file. Returns false if this failed elif not self.player.load_media(path): raise osexception(u"Video file could not be loaded") # Set audiorenderer if self.var.playaudio == u"yes" and self.player.audioformat: if self.var.soundrenderer == u"pygame": from mediadecoder.soundrenderers import SoundrendererPygame self.audio_handler = SoundrendererPygame(self.player.audioformat) elif self.var.soundrenderer == u"pyaudio": from mediadecoder.soundrenderers import SoundrendererPyAudio self.audio_handler = SoundrendererPyAudio(self.player.audioformat) elif self.var.soundrenderer == u"sounddevice": from mediadecoder.soundrenderers import SoundrendererSounddevice self.audio_handler = SoundrendererSounddevice(self.player.audioformat) self.player.set_audiorenderer(self.audio_handler) self.vid_size = self.player.clip.size self.windowsize = self.experiment.resolution() if self.var.resizeVideo == u"yes": self.dest_size = self.calculate_scaled_resolution(self.windowsize, self.vid_size) else: self.dest_size = self.vid_size self.vid_pos = ((self.windowsize[0] - self.dest_size[0]) / 2, (self.windowsize[1] - self.dest_size[1]) / 2) # Set handler of frames and user input if isinstance(self.var.canvas_backend, basestring): if self.var.canvas_backend == u"legacy" or self.var.canvas_backend \ == u"droid": from handlers import LegacyHandler self.handler = LegacyHandler(self, self.experiment.surface, custom_event_handler) if self.var.canvas_backend == u"psycho": from handlers import PsychopyHandler self.handler = PsychopyHandler(self, self.experiment.window, custom_event_handler) if self.var.canvas_backend == u"xpyriment": # Expyriment uses OpenGL in fullscreen mode, but just pygame # (legacy) display mode otherwise if self.var.fullscreen: from handlers import ExpyrimentHandler self.handler = ExpyrimentHandler(self, self.experiment.window, custom_event_handler) else: from handlers import LegacyHandler self.handler = LegacyHandler(self, self.experiment.window, custom_event_handler) else: # Give a sensible error message if the proper back-end has not been # selected raise osexception(u"The media_player plug-in could not determine " "which backend was used!") self.player.set_videoframerender_callback(self.__update_videoframe) # Init texture lock to False self.texture_locked = False # Report success return True
def prepare(self): # Call parent functions. item.prepare(self)
def prepare(self): """The preparation phase of the plug-in goes here.""" # Check if vuamsconnected is 'debug' so all vu_ams actions and warnings are skipped. This will work for all # vu_ams items that follow the vu_ams item where "Use without VU-AMS device" is checked # NOTE: the behaviour might be a bit strange when vu_ams is used in a loop item: http://osdoc.cogsci.nl/3.1/manual/prepare-run/ try: if(self.experiment.get(u'vuamsconnected') == u'debug'): return # Check if "Use without VU-AMS device" is checked. Then set vuamsconnected to 'debug' so all vu_ams actions and warnings are skipped elif(self.var._use_without_vu_ams == u'yes'): self.experiment.set(u'vuamsconnected',u'debug') self.warn() print u'Item "%s": Debug mode: "Use without VU-AMS device" checked!' % self.name return except: # Check if "Use without VU-AMS device" is checked. Then set vuamsconnected to 'debug' so all vu_ams actions and warnings are skipped if(self.var._use_without_vu_ams == u'yes'): self.experiment.set(u'vuamsconnected',u'debug') self.warn() print u'Item "%s": Debug mode: "Use without VU-AMS device" checked!' % self.name return # Call the parent constructor. item.prepare(self) # Several parts of the preparations only have to happen ones (i.e. not for every vu_ams item in the exp): # 1) Loading the dll # 2) Connecting to the device # 3) Checking if device is recording # 4) Appending Close to cleanup_functions # Because the item.py get and set functions can only handle simple variable types (unicode, float, int); # we can not store the <class 'ctypes.WinDLL'> returned by windll.amsserial globally. # Therefore we load the dll (1) in every prepare. Luckily it seems to return the same handle every time. # To track if the device is already connected (so 2, 3 and 4 can be skipped) we use the global variable # vuamsconnected. # Load dll to communicate with VU-AMS device try: from ctypes import windll self.var.AMS = windll.amsserial # requires AmsSerial.dll !!! debug.msg(u'Loaded AmsSerial.dll') except: raise osexception( \ u'AmsSerial.dll not found. Download (and install) from www.vu-ams.nl > support > downloads > extra > Download AMS serial DLL setup version 1.3.5 ') try: self.experiment.get(u'vuamsconnected') except: ####################### # Only ones: ####################### # If a device has been specified, use it if self.var._device_name not in (None, '', u'autodetect'): self.var._vuams = self.var._device_name try: self.var.AMS.Connect(self.var._vuams.encode('utf-8'), 'AMS5fs') #NOTE: port AND device type can't be u'unicode' debug.msg(u'Trying to connect to VU-AMS device') except Exception as e: raise osexception( u'Failed to open device port "%s" : "%s"' % (self.var._vuams, e)) # Try to get VU-AMS Serial to check is a VU-AMS device is connected if(self.var.AMS.GetSerial()<=0): raise osexception( u'Failed to connect to device on port "%s"' % (self.var._vuams)) else: # Else determine the common name of the serial devices on the # platform and find the first accessible device. On Windows, # devices are labeled COM[X], on Linux there are labeled /dev/tty[X] debug.msg(u'Trying to connect to VU-AMS device using autodetect') if os.name == u'nt': for i in range(255): try: dev = 'COM%d' % (i+1) #as COM ports start from 1 on Windows self.var.AMS.Connect(dev, 'AMS5fs') #NOTE: device type AND [dev] can't be u'unicode' # Try to get VU-AMS Serial to check is a VU-AMS device is connected if(self.var.AMS.GetSerial()>0): self.var._vuams = dev break self.var.AMS.Disconnect() except Exception as e: self.var._vuams = 'None' elif os.name == u'posix': raise osexception( \ u'Sorry: the vu-ams plug-in is Windows only.') else: raise osexception( \ u'vu-ams plug-in does not know how to auto-detect the VU-AMS on your platform. Please specify a device.') if self.var._vuams == 'None': raise osexception( \ u'vu-ams plug-in failed to auto-detect a VU-AMS. Please specify a device.') else: self.experiment.set(u'vuamsconnected',u'yes') self.experiment.set(u'AMS', self.var.AMS) print u'Connected to VU-AMS' # Check if VU-AMS device is recording if(self.var.AMS.IsRecording()!=1): raise osexception(u'VU-AMS is not recording!') # Appending Close to cleanup_functions self.experiment.cleanup_functions.append(self.close) ####################### # END: Only ones ### ####################### # If "Use number from title" is enabled get number from item title if(self.var._use_title_checkbox == u'yes'): number = ''.join(x for x in self.name if x.isdigit()) try: int(number) except Exception as e: raise osexception(u'Item "%s": No number in vu_ams item title "%s" to send as marker' % (self.name, self.name)) self.set((u'_send_marker'), number) # Check that title doesn't start with number. # Technically this should be a problem but it's not advisable and might be evoked by "Use number from title" functionality. if(self.name[0].isdigit()): print u'It is not advisable to start an item title with a number. (Good: "vu_ams33", "vu2_ams" and "R2-D2" Bad: "33vu_ams")' # Check if marker is numerical try: int(self.get(u'_send_marker')) except Exception as e: raise osexception(u'Item "%s": Markers must be a number' % self.name) # Check if marker is bigger then 65535 if(self.get(u'_send_marker')>65535): raise osexception(u'Item "%s": Markers can not be bigger then 65535' % self.name)
def prepare(self): """ desc: Opens the video file for playback and compiles the event handler code. returns: desc: True on success, False on failure. type: bool """ # Call parent functions. item.prepare(self) # Byte-compile the event handling code (if any) if self.var.event_handler.strip() != u"": custom_event_handler = compile(self.var.event_handler, u"<string>", u"exec") else: custom_event_handler = None if self.var.playaudio == u"yes": playaudio = True else: playaudio = False # Initialize player object self.player = player.Player(play_audio=playaudio) # Load video file to play if self.var.video_src == u"": raise osexception(u"No video file was set") else: # Find the full path to the video file. This will point to some # temporary folder where the file pool has been placed path = self.experiment.get_file(self.var.video_src) if not os.path.exists(path): raise osexception( u"Invalid path to video file: {0} (file not found)".format( path)) # Load the video file. Returns false if this failed elif not self.player.load_video(path): raise osexception(u"Video file could not be loaded") # Set audiorenderer if self.var.playaudio == u"yes" and self.player.audioformat: if self.var.soundrenderer == u"pygame": self.audio_handler = SoundrendererPygame( self.player.audioformat) elif self.var.soundrenderer == u"pyaudio": self.audio_handler = SoundrendererPyAudio( self.player.audioformat) self.vidsize = self.player.clip.size self.windowsize = self.experiment.resolution() if self.var.resizeVideo == u"yes": self.destsize = self.calculate_scaled_resolution( self.windowsize, self.vidsize) else: self.destsize = self.vidsize self.vidPos = ((self.windowsize[0] - self.destsize[0]) / 2, (self.windowsize[1] - self.destsize[1]) / 2) # Set handler of frames and user input if type(self.var.canvas_backend) in [unicode, str]: if self.var.canvas_backend == u"legacy" or self.var.canvas_backend == u"droid": self.handler = legacy_handler(self, self.experiment.surface, custom_event_handler) if self.var.canvas_backend == u"psycho": self.handler = psychopy_handler(self, self.experiment.window, custom_event_handler) if self.var.canvas_backend == u"xpyriment": # Expyriment uses OpenGL in fullscreen mode, but just pygame # (legacy) display mode otherwise if self.experiment.fullscreen: self.handler = expyriment_handler(self, self.experiment.window, custom_event_handler) else: self.handler = legacy_handler(self, self.experiment.window, custom_event_handler) else: # Give a sensible error message if the proper back-end has not been selected raise osexception( u"The media_player plug-in could not determine which backend was used!" ) self.player.set_videoframerender_callback(self.__update_videoframe) self.player.set_audioframerender_callback(self.__render_audioframe) # Report success return True
def prepare(self): """ desc: Opens the video file for playback and compiles the event handler code. returns: desc: True on success, False on failure. type: bool """ item.prepare(self) # Byte-compile the event handling code (if any) if self.var.event_handler.strip(): self._event_handler = self.python_workspace._compile( self.var.event_handler) self._event_handler_always = \ self.var.event_handler_trigger == u'after every frame' else: self._event_handler = None self._event_handler_always = False # Find the full path to the video file in the file pool, and check if it # can be found. path = self.var.video_src # Commented as this is not a file but a youtube path # debug.msg(u"loading '%s'" % path) # if not os.path.isfile(path): # raise osexception( # u"Video file '%s' was not found by video_player '%s' (or no video file was specified)." # % (os.path.basename(path), self.name)) # Read the framerate from the video file, and fall back to a default # framerate if this fails if self.hasMediaInfo: debug.msg(u"Reading file media parameters") mi = MediaInfo.parse(path) try: mi = MediaInfo.parse(path) for track in mi.tracks: if track.track_type == u"Video": self.framerate = float(track.frame_rate) except: raise osexception( u"Error parsing media file. Possibly the video file is corrupt") else: self.framerate = 30. self.frame_duration = 1000/self.framerate self.vlcInstance = vlc.Instance(u"--no-video-title-show") self.player = self.vlcInstance.media_player_new() try: # Trick on how to reproduce youtube from python-vlc http://stackoverflow.com/a/29430900 self.media = self.vlcInstance.media_new(path) self.media_list = self.vlcInstance.media_list_new([path]) self.player.set_media(self.media) self.list_player = self.vlcInstance.media_list_player_new() self.list_player.set_media_player(self.player) self.list_player.set_media_list(self.media_list) self.media.parse() self.file_loaded = True # Determines if cleanup is necessary later # If vlc memory is freed, set to True. self.released = False except: raise osexception( u"Error loading media file. Unsupported format?") # If playaudio is set to no, tell vlc to mute the movie if self.var.playaudio == u"no": self.player.audio_set_mute(True) else: self.player.audio_set_mute(False) # Solves bug in vlc bindings: unmute sets sound status to unmuted # but sets volume to 0 self.player.audio_set_volume(75) # create reference to vlc event handler and set up event handling self.vlc_event_handler = self.player.event_manager() # Pass thru vlc output to experiment window self._set_display_window() # Indicate function for clean up that is run after the experiment # finishes self.experiment.cleanup_functions.append(self.closePlayer) if self.var.resizeVideo == u"no": self.player.video_set_scale(1.0) # Set response objects self.keyboard = keyboard(self.experiment, timeout=0)
def prepare(self): """Preparation phase""" # Call the parent constructor. item.prepare(self) self.close() self.init_var() if self.dummy_mode == u'no': if os.name == 'posix': # import the local modified version of pyparallel # that allows for non-exclusive connections to the parport path_to_file = os.path.join(os.path.dirname(__file__), 'parallelppdev.py') parallel = imp.load_source('parallel', path_to_file) try: import parallelppdev as parallel except ImportError as e: raise osexception(u'The local modified version of pyparallel could not be loaded. Check if the file is present and if the file permissions are correct.', exception=e) elif os.name == 'nt': try: from ctypes import windll except ImportError as e: raise osexception(u'The ctypes module can not be loaded. Check if ctypes is installed correctly.', exception=e) else: try: import parallel except ImportError as e: raise osexception('The pyparallel module could not be loaded, please make sure pyparallel is installed correctly.', exception=e) if not hasattr(self.experiment, "pptrigger"): try: if os.name == 'nt': path_to_dll_file = os.path.join(os.path.dirname(__file__), 'inpout32.dll') self.show_message(path_to_dll_file) self.experiment.pptrigger = windll.LoadLibrary(path_to_dll_file) if isinstance(self.var.port,str): #port = self.port.encode('ascii') self.port = self.var.port.encode('ascii') else: raise osexception('Port value should be a string on Windows') else: self.show_message(u'Using parallel port on address: %s' % self.var.port) if isinstance(self.var.port,int): self.port = self.var.port elif isinstance(self.var.port,str): #port = self.port.encode('ascii') self.port = self.var.port.encode('ascii') else: raise osexception('Port value should be a integer or string on Linux') self.experiment.pptrigger = parallel.Parallel(port=self.port) except Exception as e: raise osexception( u'Could not access the Parallel Port', exception=e) self.experiment.cleanup_functions.append(self.close) self.python_workspace[u'pp'] = self.experiment.pptrigger ## reset trigger try: if os.name == 'nt': self.set_item_onset(self.experiment.pptrigger.DlPortWritePortUchar(int(self.port,0), 0)) else: self.set_item_onset(self.experiment.pptrigger.setData(0)) self.show_message(u'Resetting the parallel port on address: %s' % (self.port)) except Exception as e: raise osexception( u'Wrong port address, could not access the Parallel Port', exception=e) elif self.dummy_mode == u'yes': self.show_message(u'Dummy mode enabled for the Parallel Port Trigger Plug-in') else: self.show_message(u'Error with dummy mode, mode is: %s' % self.dummy_mode)
def prepare(self): item.prepare(self)
def prepare(self): """ desc: Opens the video file for playback and compiles the event handler code. returns: desc: True on success, False on failure. type: bool """ item.prepare(self) # Byte-compile the event handling code (if any) if self.var.event_handler.strip(): self._event_handler = self.python_workspace._compile(self.var.event_handler) self._event_handler_always = self.var.event_handler_trigger == u"after every frame" else: self._event_handler = None self._event_handler_always = False # Find the full path to the video file in the file pool, and check if it # can be found. path = self.experiment.pool[self.var.video_src] debug.msg(u"loading '%s'" % path) if not os.path.isfile(path): raise osexception( u"Video file '%s' was not found by video_player '%s' (or no video file was specified)." % (os.path.basename(path), self.name) ) # Read the framerate from the video file, and fall back to a default # framerate if this fails if self.hasMediaInfo: debug.msg(u"Reading file media parameters") mi = MediaInfo.parse(path) try: mi = MediaInfo.parse(path) for track in mi.tracks: if track.track_type == u"Video": self.framerate = float(track.frame_rate) except: raise osexception(u"Error parsing media file. Possibly the video file is corrupt") else: self.framerate = 30.0 self.frame_duration = 1000 / self.framerate self.vlcInstance = vlc.Instance(u"--no-video-title-show") self.player = self.vlcInstance.media_player_new() try: self.media = self.vlcInstance.media_new(path) self.player.set_media(self.media) self.media.parse() self.file_loaded = True # Determines if cleanup is necessary later # If vlc memory is freed, set to True. self.released = False except: raise osexception(u"Error loading media file. Unsupported format?") # If playaudio is set to no, tell vlc to mute the movie if self.var.playaudio == u"no": self.player.audio_set_mute(True) else: self.player.audio_set_mute(False) # Solves bug in vlc bindings: unmute sets sound status to unmuted # but sets volume to 0 self.player.audio_set_volume(75) # create reference to vlc event handler and set up event handling self.vlc_event_handler = self.player.event_manager() # Pass thru vlc output to experiment window self._set_display_window() # Indicate function for clean up that is run after the experiment # finishes self.experiment.cleanup_functions.append(self.closePlayer) if self.var.resizeVideo == u"no": self.player.video_set_scale(1.0) # Set response objects self.keyboard = keyboard(self.experiment, timeout=0)
def prepare(self): """The preparation phase of the plug-in goes here.""" # Call the parent constructor. item.prepare(self)
def prepare(self): """ desc: Opens the video file for playback and compiles the event handler code. returns: desc: True on success, False on failure. type: bool """ # Call parent functions. item.prepare(self) # Byte-compile the event handling code (if any) if self.var.event_handler.strip() != u"": # custom_event_handler = compile(self.var.event_handler, u"<string>", # u"exec") custom_event_handler = self.python_workspace._compile(self.var.event_handler) else: custom_event_handler = None if self.var.playaudio == u"yes": playaudio = True else: playaudio = False # Initialize player object self.player = mediadecoder.Decoder(play_audio=playaudio) self.player.loop = (self.var.loop == "yes") # Load video file to play if self.var.video_src == u"": raise osexception(u"No video file was set") else: # Find the full path to the video file. This will point to some # temporary folder where the file pool has been placed path = self.experiment.get_file(self.var.video_src) if not os.path.exists(path): raise osexception(u"Invalid path to video file: {0} (file not " "found)".format(path)) # Load the video file. Returns false if this failed elif not self.player.load_media(path): raise osexception(u"Video file could not be loaded") # Set audiorenderer if self.var.playaudio == u"yes" and self.player.audioformat: if self.var.soundrenderer == u"pygame": from mediadecoder.soundrenderers import SoundrendererPygame self.audio_handler = SoundrendererPygame(self.player.audioformat) elif self.var.soundrenderer == u"pyaudio": from mediadecoder.soundrenderers import SoundrendererPyAudio self.audio_handler = SoundrendererPyAudio(self.player.audioformat) elif self.var.soundrenderer == u"sounddevice": from mediadecoder.soundrenderers import SoundrendererSounddevice self.audio_handler = SoundrendererSounddevice(self.player.audioformat) self.player.set_audiorenderer(self.audio_handler) self.vid_size = self.player.clip.size self.windowsize = self.experiment.resolution() if self.var.resizeVideo == u"yes": self.dest_size = self.calculate_scaled_resolution(self.windowsize, self.vid_size) else: self.dest_size = self.vid_size self.vid_pos = ((self.windowsize[0] - self.dest_size[0]) / 2, (self.windowsize[1] - self.dest_size[1]) / 2) # Set handler of frames and user input if type(self.var.canvas_backend) in [unicode,str]: if self.var.canvas_backend == u"legacy" or self.var.canvas_backend \ == u"droid": from handlers import LegacyHandler self.handler = LegacyHandler(self, self.experiment.surface, custom_event_handler) if self.var.canvas_backend == u"psycho": from handlers import PsychopyHandler self.handler = PsychopyHandler(self, self.experiment.window, custom_event_handler) if self.var.canvas_backend == u"xpyriment": # Expyriment uses OpenGL in fullscreen mode, but just pygame # (legacy) display mode otherwise if self.var.fullscreen: from handlers import ExpyrimentHandler self.handler = ExpyrimentHandler(self, self.experiment.window, custom_event_handler) else: from handlers import LegacyHandler self.handler = LegacyHandler(self, self.experiment.window, custom_event_handler) else: # Give a sensible error message if the proper back-end has not been # selected raise osexception(u"The media_player plug-in could not determine " "which backend was used!") self.player.set_videoframerender_callback(self.__update_videoframe) # Init texture lock to False self.texture_locked = False # Report success return True
def prepare(self): """Preparation phase""" # Call the parent constructor. item.prepare(self) # create keyboard object self.kb = keyboard(self.experiment,timeout=1) self.init_var() if self.pause_resume != u'': # Prepare the pause resume responses self._allowed_responses_pause_resume = [] for r in safe_decode(self.pause_resume).split(u';'): if r.strip() != u'': self._allowed_responses_pause_resume.append(r) if not self._allowed_responses_pause_resume: self._allowed_responses_pause_resume = None self.show_message(u"allowed pause/resume keys set to %s" % self._allowed_responses_pause_resume) if self.stop != u'': # Prepare the pause resume responses self._allowed_responses_stop = [] for r in safe_decode(self.stop).split(u';'): if r.strip() != u'': self._allowed_responses_stop.append(r) if not self._allowed_responses_stop: self._allowed_responses_stop = None self.show_message(u"allowed stop keys set to %s" % self._allowed_responses_stop) if self.dummy_mode == u'no': try: self.show_message(u'\n') self.show_message(u'Loading sound file: '+self.filename+' ...') self.wav_file = wave.open(self.filename, 'rb') self.show_message(u'Succesfully loaded sound file...') except Exception as e: raise osexception( u'Could not load audio file', exception=e) self.wav_duration = int(round(float(self.wav_file.getnframes()) / float(self.wav_file.getframerate()) * 1000, 1)) self.show_message(u'Audio file duration: %d ms' % (self.wav_duration)) self.show_message(u'Period size: %d frames' % (self.period_size)) self.show_message(u'Period duration: %s ms' % (str(self.period_size_time))) error_msg_list = [] if self.wav_file.getsampwidth() * 8 != self.bitdepth: error_msg_list.append(u'- bitdepth incorrect, file is %dbit but experiment is set to %dbit\n' % (self.wav_file.getsampwidth()*8,self.bitdepth)) #raise osexception(u'wave file has incorrect bitdepth') if self.wav_file.getframerate() != self.samplerate: error_msg_list.append(u'- samplerate incorrect, file is %dHz but experiment is set to %dHz\n' % (self.wav_file.getframerate(),self.samplerate)) #raise osexception(u'wave file has incorrect samplerate') if self.wav_file.getnchannels() != self.channels: error_msg_list.append(u'- number of channels incorrect, file has %d channel(s) but experiment is set to %d channel(s)\n' % (self.wav_file.getnchannels(), self.channels)) #raise osexception(u'wave file has incorrect number of channels') if self.wav_file.getnframes() < self.period_size: error_msg_list.append(u'- Period size is larger than total number of frames in wave file, use a period size smaller than %d frames\n' % (self.wav_file.getnframes())) if error_msg_list: raise osexception(u'Error with audio file %s\n%s' % (self.filename, ''.join(error_msg_list))) if self.ram_cache == u'yes': wav_file_nframes = self.wav_file.getnframes() self.wav_file_data = self.wav_file.readframes(wav_file_nframes) self.wav_file.close()
def prepare(self): item.prepare(self) self._coroutine = self.coroutine() next(self._coroutine)
def prepare(self): """The preparation phase of the plug-in goes here.""" # Call the parent constructor. item.prepare(self) # Specific code # Use this to define global functions def send_data(data, delete): self.c.clear() self.c.text("Connecting to server...") self.c.show() # Try to open the connection address = "http://cogsci.nl/etravers/androidsql.php" try: page = urllib.urlopen(address, "position=openingconnection") page.close() # Connection works. Send data. print "Connected" t = 0 for trial in data: progress = int(float(t) / len(data) * 680) # print t, len(data), progress self.c.clear() self.c.text("Sending...") self.c.rect(300, 600, 680, 72, False, "white") # Update progress bar self.c.rect(303, 601, progress, 70, True, "red") self.c.show() encode_data = urllib.urlencode(trial) print encode_data for i in range(5): try: page = urllib.urlopen(address, encode_data) page.close() print "Sent!", t except IOError as e: print str(e) else: break t += 1 result = "Data sent!" # Delete sent datafile if delete: if os.path.isfile(data_path): os.remove(data_path) except IOError as e: result = "Unable to connect.\nPlease try again when connected to the internet." save_data() print str(e) self.c.clear() self.c.text(result) self.c.show() my_mouse.get_click() def save_data(): sdcard_folders = ["/sdcard/", "/mnt/sdcard/"] for path in sdcard_folders: if os.path.isdir(path): break try: f = open(os.path.join(path, "datafile.txt"), "w") except: print "Failed to create %s" % path f = open("datafile.txt", "w") f.truncate() f.write("data_log = " + repr(data_log) + "\n" + "global data_log") f.close() global send_data, save_data