How to use tapText method in fMBT

Best Python code snippet using fMBT_python

TappingWithTrTiming_Movie_d3.py

Source:TappingWithTrTiming_Movie_d3.py Github

copy

Full Screen

1#!/usr/bin/env python22"""Display multi-page text with a quiz at the end."""3# TappingWithTrTiming_Movie_d3.py4# Created 11/09/15 by DJ based on DistractionTask_practice_d3.py5# Updated 12/4/15 by DJ - made movie version6# Updated 12/7/15 by DJ - updated prompts, general cleanup7# Updated 1/12/16 by DJ - moved from movie to frame-by-frame display, single repeated condition8from psychopy import core, gui, data, event, sound, logging 9# from psychopy import visual # visual causes a bug in the guis, so it's declared after all GUIs run.10from psychopy.tools.filetools import fromFile, toFile # saving and loading parameter files11import time as ts, numpy as np # for timing and array operations12import AppKit, os, glob # for monitor size detection, files13import BasicPromptTools # for loading/presenting prompts and questions14import random # for randomization of trials15# ====================== #16# ===== PARAMETERS ===== #17# ====================== #18# Save the parameters declared below?19saveParams = True;20newParamsFilename = 'TappingParams.pickle'21# Declare primary task parameters.22params = {23# Declare stimulus and response parameters24 'nBlocks': 5, # number of blocks in this session25 'condition': 'TapRight',26 'movieFolder': 'Images/', # relative path to tapping videos27 'blockDur_TRs': 3, # duration of each tapping block (in TRs)28 'restDur_TRs': 3, # duration of each rest block (in TRs)29 'tStartup_TRs': 0, # pause time before starting first stimulus (in TRs)30 'triggerKey': 't', # key from scanner that says scan is starting31# declare prompt and question files32 'skipPrompts': False, # go right to the scanner-wait page33 'promptDir': 'Text/', # directory containing prompts and questions files34# declare display parameters35 'fullScreen': True, # run in full screen mode?36 'screenToShow': 1, # display on primary screen (0) or secondary (1)?37 'fixCrossSize': 100, # size of cross, in pixels38 'movieSize': (400,250), # size of image in pixels 39 'fixCrossPos': [0,0], # (x,y) pos of fixation cross displayed before each stimulus (for gaze drift correction)40 'screenColor':(128,128,128), # in rgb255 space: (r,g,b) all between 0 and 25541 'textHeight': 40 #(in pixels)42}43stimList = {44 'conditionList':['TapRight','TapFast','TapLeft','AlmostRight','ImagineRight'],45 'moviePromptList': ['Tap (Right Hand) \nAlong with the video.','Tap (Right Hand) \nAlong with the video.','Tap (Left Hand) \nAlong with the video.','Move (Right Hand) but do NOT touch fingers \nAlong with the video.','Imagine Tapping (Right Hand).'],46 'moviePrefixList': ['right','right','left','right_almost','right_imagine'], # filenames of movies47 'movieFrameRateList': [10, 40, 10, 10, 1], # frame rate of each movie (s)48 'movieNFrameList':[10, 10, 10, 10, 1], # nFrames in each movie (numbered from 0 to nFrames-149 'promptFileList': ['TappingPrompts_Movie.txt','TappingPrompts_Movie.txt','TappingPrompts_Movie.txt','AlmostPrompts_Movie.txt','ImaginePrompts_Movie.txt'] # Name of text file containing prompts 50}51# save parameters52if saveParams:53 dlgResult = gui.fileSaveDlg(prompt='Save Params...',initFilePath = os.getcwd() + '/Params', initFileName = newParamsFilename,54 allowed="PICKLE files (.pickle)|.pickle|All files (.*)|")55 newParamsFilename = dlgResult56 if newParamsFilename is None: # keep going, but don't save57 saveParams = False58 else:59 toFile(newParamsFilename, params) # save it!60# ========================== #61# ===== SET UP LOGGING ===== #62# ========================== #63scriptName = os.path.basename(__file__)64try: # try to get a previous parameters file65 lastInfo = fromFile('%s-lastExpInfo.pickle'%scriptName)66 expInfo = {67 'subject': lastInfo['subject'], 68 'session': lastInfo['session']+1, 69 'condition': stimList['conditionList'],70 'skipPrompts':lastInfo['skipPrompts'], 71 'paramsFile':[lastInfo['paramsFile'],'Load...']}72except: # if not there then use a default set73 expInfo = {74 'subject':'1', 75 'session': 1, 76 'condition': stimList['conditionList'],77 'skipPrompts':False, 78 'paramsFile':['DEFAULT','Load...']}79# overwrite params struct if you just saved a new parameter set80if saveParams:81 expInfo['paramsFile'] = [newParamsFilename,'Load...']82#present a dialogue to change select params83dlg = gui.DlgFromDict(expInfo, title=scriptName, order=['subject','session','condition','skipPrompts','paramsFile'])84if not dlg.OK:85 core.quit() # the user hit cancel, so exit86# find parameter file87if expInfo['paramsFile'] == 'Load...':88 dlgResult = gui.fileOpenDlg(prompt='Select parameters file',tryFilePath=os.getcwd(),89 allowed="PICKLE files (.pickle)|.pickle|All files (.*)|")90 expInfo['paramsFile'] = dlgResult[0]91# load parameter file92if expInfo['paramsFile'] not in ['DEFAULT', None]: # otherwise, just use defaults.93 # load params file94 params = fromFile(expInfo['paramsFile'])95# transfer skipPrompts from expInfo (gui input) to params (logged parameters)96params['skipPrompts'] = expInfo['skipPrompts']97params['condition'] = expInfo['condition']98iCondition = stimList['conditionList'].index(params['condition'])99print('iCondition = %d'%iCondition)100# print params to Output101print 'params = {'102for key in sorted(params.keys()):103 print " '%s': %s"%(key,params[key]) # print each value as-is (no quotes)104print '}'105 106# save experimental info107toFile('%s-lastExpInfo.pickle'%scriptName, expInfo)#save params to file for next time108#make a log file to save parameter/event data109dateStr = ts.strftime("%b_%d_%H%M", ts.localtime()) # add the current time110filename = '%s-%s-%d-%s'%(scriptName,expInfo['subject'], expInfo['session'], dateStr) # log filename111logging.LogFile((filename+'.log'), level=logging.INFO)#, mode='w') # w=overwrite112logging.log(level=logging.INFO, msg='---START PARAMETERS---')113logging.log(level=logging.INFO, msg='filename: %s'%filename)114logging.log(level=logging.INFO, msg='subject: %s'%expInfo['subject'])115logging.log(level=logging.INFO, msg='session: %s'%expInfo['session'])116logging.log(level=logging.INFO, msg='date: %s'%dateStr)117# log everything in the params struct118for key in sorted(params.keys()): # in alphabetical order119 logging.log(level=logging.INFO, msg='%s: %s'%(key,params[key])) # log each parameter120logging.log(level=logging.INFO, msg='---END PARAMETERS---')121# ========================== #122# ===== GET SCREEN RES ===== #123# ========================== #124# kluge for secondary monitor125if params['fullScreen']: 126 screens = AppKit.NSScreen.screens()127 screenRes = (int(screens[params['screenToShow']].frame().size.width), int(screens[params['screenToShow']].frame().size.height))128# screenRes = [1920, 1200]129 if params['screenToShow']>0:130 params['fullScreen'] = False131else:132 screenRes = [800,600]133print "screenRes = [%d,%d]"%screenRes134# ========================== #135# ===== SET UP STIMULI ===== #136# ========================== #137from psychopy import visual138# Initialize deadline for displaying next frame139tNextFlip = [0.0] # put in a list to make it mutable (weird quirk of python variables) 140#create clocks and window141globalClock = core.Clock()#to keep track of time142trialClock = core.Clock()#to keep track of time143win = visual.Window(screenRes, fullscr=params['fullScreen'], allowGUI=False, monitor='testMonitor', screen=params['screenToShow'], units='deg', name='win',color=params['screenColor'],colorSpace='rgb255')144# create fixation cross145fCS = params['fixCrossSize'] # size (for brevity)146fCP = params['fixCrossPos'] # position (for brevity)147fixation = visual.ShapeStim(win,lineColor='#000000',lineWidth=3.0,vertices=((fCP[0]-fCS/2,fCP[1]),(fCP[0]+fCS/2,fCP[1]),(fCP[0],fCP[1]),(fCP[0],fCP[1]+fCS/2),(fCP[0],fCP[1]-fCS/2)),units='pix',closeShape=False,name='fixCross');148# create text stimuli149message1 = visual.TextStim(win, pos=[0,+.5], wrapWidth=1.5, color='#000000', alignHoriz='center', name='topMsg', text="aaa",units='norm')150message2 = visual.TextStim(win, pos=[0,-.5], wrapWidth=1.5, color='#000000', alignHoriz='center', name='bottomMsg', text="bbb",units='norm')151# Load new image stimuli152tapImages = []153for i in range(0,stimList['movieNFrameList'][iCondition]):154 tapImages.append(visual.ImageStim(win, pos=[0,0], name='Movie Frame %d'%i,image='%s%s_%d.png'%(params['movieFolder'],stimList['moviePrefixList'][iCondition],i), units='pix', size=params['movieSize']))155# Create bottom text stim156tapText = visual.TextStim(win, stimList['moviePromptList'][iCondition], wrapWidth=params['movieSize'][0], color='#000000', pos=(0, params['movieSize'][1]/2+params['textHeight']*2), height = params['textHeight'], units = 'pix')157# read prompts from text files158[topPrompts,bottomPrompts] = BasicPromptTools.ParsePromptFile(params['promptDir']+stimList['promptFileList'][iCondition])159print('%d prompts loaded from %s'%(len(topPrompts),stimList['promptFileList'][iCondition]))160# ============================ #161# ======= SUBFUNCTIONS ======= #162# ============================ #163# increment time of next window flip164def AddToFlipTime(tIncrement=1.0):165 tNextFlip[0] += tIncrement166# flip window as soon as possible167def SetFlipTimeToNow():168 tNextFlip[0] = globalClock.getTime()169def CheckForTriggers():170 # get new keys171 newKeys = event.getKeys(keyList=[params['triggerKey'], 'q','escape'],timeStamped=globalClock)172 # check each keypress for escape or trigger keys173 nTriggers = 0174 if len(newKeys)>0:175 for thisKey in newKeys: 176 if thisKey[0] in ['q','escape']: # escape keys177 CoolDown() # exit gracefully178 elif thisKey[0] == params['triggerKey']:179 nTriggers = nTriggers + 1180 181 return nTriggers182def PlayTappingMovie(tapImages, tapText, dt, blockDur_TRs):183 184 # Wait for escape key press or 'blockDur_TRs' triggers185 nTriggers = 0186 SetFlipTimeToNow()187 tBlockStart = globalClock.getTime() # record time when window flipped188 iFrame = 0189 SetFlipTimeToNow()190 while (nTriggers < blockDur_TRs): # until it's time for the next frame # while mov.status != visual.FINISHED:191 # ---tapping movie192 # check for loop or movie end193 if iFrame >= len(tapImages):194 iFrame=0 # rewind to beginning195 196 # Only flip when a new frame should be displayed.197 if globalClock.getTime()>=tNextFlip[0]:198 # draw movie frame, draw text stim, and flip199 tapImages[iFrame].draw()200 tapText.draw()201 win.logOnFlip(level=logging.EXP, msg='Display Frame %d'%iFrame)202 win.flip()203 # increment iFrame204 iFrame = iFrame+1205 # Add to flip time206 AddToFlipTime(dt)207 else:208 # Give the OS a break if a flip is not needed209 ts.sleep(0.001)210 211 212 # Check for triggers and increment trigger count213 nNew = CheckForTriggers()214 nTriggers = nTriggers + nNew215 # check for final trigger216 if nTriggers >= blockDur_TRs:217 break218 219 # allow screen update220 SetFlipTimeToNow()221 222 # Get block time223 tBlock = globalClock.getTime()-tBlockStart224 print('Block time: %.3f seconds'%(tBlock))225 226 return (tBlock)227# Pause until a given number of TRs is received.228def WaitForTrs(tWait_TRs):229 # do IBI230 nTriggers = 0231 while (nTriggers < tWait_TRs):232 # Check for triggers and increment trigger count233 nNew = CheckForTriggers()234 nTriggers = nTriggers + nNew235 if nTriggers >= tWait_TRs:236 break237# Handle end of a session238def CoolDown():239 240 # display cool-down message241 message1.setText("That's the end! ")242 message2.setText("Press 'q' or 'escape' to end the session.")243 win.logOnFlip(level=logging.EXP, msg='Display TheEnd')244 win.clearBuffer() # clear the screen245 message1.draw()246 message2.draw()247 win.flip()248 thisKey = event.waitKeys(keyList=['q','escape'])249 250 # exit251 core.quit()252# =========================== #253# ======= RUN PROMPTS ======= #254# =========================== #255# display prompts256if not params['skipPrompts']:257 BasicPromptTools.RunPrompts(topPrompts,bottomPrompts,win,message1,message2)258# wait for scanner259message1.setText("Please don't move...")260message2.setText("") #("(Press '%c' to override.)"%params['triggerKey'].upper())261message1.draw()262message2.draw()263win.logOnFlip(level=logging.EXP, msg='PleaseDontMove') #'Display WaitingForScanner')264win.flip()265event.waitKeys(keyList=params['triggerKey'])266tStartSession = globalClock.getTime()267AddToFlipTime(tStartSession)268# wait before first stimulus269fixation.draw()270win.logOnFlip(level=logging.EXP, msg='Display Fixation')271win.flip()272WaitForTrs(params['tStartup_TRs']) # wait for the given # of TRs273# =========================== #274# ===== MAIN EXPERIMENT ===== #275# =========================== #276# log experiment start and set up277logging.log(level=logging.EXP, msg='---START EXPERIMENT---')278# run main experiment loop279for iBlock in range(0,params['nBlocks']):280 281 # Run rest period282 print('Resting Block %d: duration=%.2f'%(iBlock, params['restDur_TRs']) )283 # Display fixation cross284 win.clearBuffer() # clear the screen285 fixation.draw() # draw the cross286 win.logOnFlip(level=logging.EXP, msg='Display Fixation')287 win.flip() # flip the window ASAP288 # do rest period289 WaitForTrs(params['restDur_TRs'])290 291 # display info to experimenter292 print('Tapping Block %d: movie=%s, framerate=%.2f'%(iBlock, stimList['moviePrefixList'][iCondition], stimList['movieFrameRateList'][iCondition]) )293 # display tapping movie294 tBlock = PlayTappingMovie(tapImages=tapImages, tapText=tapText, dt=1.0/stimList['movieFrameRateList'][iCondition], blockDur_TRs=params['blockDur_TRs'])295# Log end of experiment296logging.log(level=logging.EXP, msg='--- END EXPERIMENT ---')297# exit experiment...

Full Screen

Full Screen

TappingWithTrTiming_Movie_d2.py

Source:TappingWithTrTiming_Movie_d2.py Github

copy

Full Screen

1#!/usr/bin/env python22"""Display multi-page text with a quiz at the end."""3# TappingWithTrTiming_Movie_d1.py4# Created 11/09/15 by DJ based on DistractionTask_practice_d3.py5# Updated 12/4/15 by DJ - made movie version6# Updated 12/7/15 by DJ - updated prompts, general cleanup7# Updated 1/12/16 by DJ - moved from movie to frame-by-frame display8from psychopy import core, gui, data, event, sound, logging 9# from psychopy import visual # visual causes a bug in the guis, so it's declared after all GUIs run.10from psychopy.tools.filetools import fromFile, toFile # saving and loading parameter files11import time as ts, numpy as np # for timing and array operations12import AppKit, os, glob # for monitor size detection, files13import BasicPromptTools # for loading/presenting prompts and questions14import random # for randomization of trials15# ====================== #16# ===== PARAMETERS ===== #17# ====================== #18# Save the parameters declared below?19saveParams = True;20newParamsFilename = 'TappingParams.pickle'21# Declare primary task parameters.22params = {23# Declare stimulus and response parameters24 'nBlocks': 5, # number of trials in this session25 'movieFolder': 'Images/', # relative path to tapping videos26 'moviePromptList': ['Tap (Right Hand) \nAlong with the video.','Tap (Right Hand) \nAlong with the video.','Tap (Left Hand) \nAlong with the video.','Move (Right Hand) but do NOT touch fingers \nAlong with the video.','Imagine Tapping (Right Hand).'],27 'moviePrefixList': ['right','right','left','right_almost','right_imagine'], # filenames of movies28 'movieFrameRateList': [10, 20, 10, 10, 1], # frame rate of each movie (s)29 'movieNFrameList':[10, 10, 10, 10, 1], # nFrames in each movie (numbered from 0 to nFrames-130 'blockDur_TRs': 3, # duration of each tapping block (in TRs)31 'restDur_TRs': 3, # duration of each rest block (in TRs)32 'tStartup_TRs': 0, # pause time before starting first stimulus (in TRs)33 'triggerKey': 't', # key from scanner that says scan is starting34# declare prompt and question files35 'skipPrompts': False, # go right to the scanner-wait page36 'promptDir': 'Text/', # directory containing prompts and questions files37 'promptFile': 'TappingPrompts_Movie.txt', # Name of text file containing prompts 38# declare display parameters39 'fullScreen': True, # run in full screen mode?40 'screenToShow': 1, # display on primary screen (0) or secondary (1)?41 'fixCrossSize': 100, # size of cross, in pixels42 'movieSize': (400,250), # size of image in pixels 43 'fixCrossPos': [0,0], # (x,y) pos of fixation cross displayed before each stimulus (for gaze drift correction)44 'screenColor':(128,128,128) # in rgb255 space: (r,g,b) all between 0 and 25545}46# save parameters47if saveParams:48 dlgResult = gui.fileSaveDlg(prompt='Save Params...',initFilePath = os.getcwd() + '/Params', initFileName = newParamsFilename,49 allowed="PICKLE files (.pickle)|.pickle|All files (.*)|")50 newParamsFilename = dlgResult51 if newParamsFilename is None: # keep going, but don't save52 saveParams = False53 else:54 toFile(newParamsFilename, params) # save it!55# ========================== #56# ===== SET UP LOGGING ===== #57# ========================== #58scriptName = os.path.basename(__file__)59try: # try to get a previous parameters file60 expInfo = fromFile('%s-lastExpInfo.pickle'%scriptName)61 expInfo['session'] +=1 # automatically increment session number62 expInfo['paramsFile'] = [expInfo['paramsFile'],'Load...']63except: # if not there then use a default set64 expInfo = {65 'subject':'1', 66 'session': 1, 67 'skipPrompts':False, 68 'paramsFile':['DEFAULT','Load...']}69# overwrite params struct if you just saved a new parameter set70if saveParams:71 expInfo['paramsFile'] = [newParamsFilename,'Load...']72#present a dialogue to change select params73dlg = gui.DlgFromDict(expInfo, title=scriptName, order=['subject','session','skipPrompts','paramsFile'])74if not dlg.OK:75 core.quit() # the user hit cancel, so exit76# find parameter file77if expInfo['paramsFile'] == 'Load...':78 dlgResult = gui.fileOpenDlg(prompt='Select parameters file',tryFilePath=os.getcwd(),79 allowed="PICKLE files (.pickle)|.pickle|All files (.*)|")80 expInfo['paramsFile'] = dlgResult[0]81# load parameter file82if expInfo['paramsFile'] not in ['DEFAULT', None]: # otherwise, just use defaults.83 # load params file84 params = fromFile(expInfo['paramsFile'])85# transfer skipPrompts from expInfo (gui input) to params (logged parameters)86params['skipPrompts'] = expInfo['skipPrompts']87# print params to Output88print 'params = {'89for key in sorted(params.keys()):90 print " '%s': %s"%(key,params[key]) # print each value as-is (no quotes)91print '}'92 93# save experimental info94toFile('%s-lastExpInfo.pickle'%scriptName, expInfo)#save params to file for next time95#make a log file to save parameter/event data96dateStr = ts.strftime("%b_%d_%H%M", ts.localtime()) # add the current time97filename = '%s-%s-%d-%s'%(scriptName,expInfo['subject'], expInfo['session'], dateStr) # log filename98logging.LogFile((filename+'.log'), level=logging.INFO)#, mode='w') # w=overwrite99logging.log(level=logging.INFO, msg='---START PARAMETERS---')100logging.log(level=logging.INFO, msg='filename: %s'%filename)101logging.log(level=logging.INFO, msg='subject: %s'%expInfo['subject'])102logging.log(level=logging.INFO, msg='session: %s'%expInfo['session'])103logging.log(level=logging.INFO, msg='date: %s'%dateStr)104# log everything in the params struct105for key in sorted(params.keys()): # in alphabetical order106 logging.log(level=logging.INFO, msg='%s: %s'%(key,params[key])) # log each parameter107logging.log(level=logging.INFO, msg='---END PARAMETERS---')108# ========================== #109# ===== GET SCREEN RES ===== #110# ========================== #111# kluge for secondary monitor112if params['fullScreen']: 113 screens = AppKit.NSScreen.screens()114 screenRes = (int(screens[params['screenToShow']].frame().size.width), int(screens[params['screenToShow']].frame().size.height))115# screenRes = [1920, 1200]116 if params['screenToShow']>0:117 params['fullScreen'] = False118else:119 screenRes = [800,600]120print "screenRes = [%d,%d]"%screenRes121# ========================== #122# ===== SET UP STIMULI ===== #123# ========================== #124from psychopy import visual125# Initialize deadline for displaying next frame126tNextFlip = [0.0] # put in a list to make it mutable (weird quirk of python variables) 127#create clocks and window128globalClock = core.Clock()#to keep track of time129trialClock = core.Clock()#to keep track of time130win = visual.Window(screenRes, fullscr=params['fullScreen'], allowGUI=False, monitor='testMonitor', screen=params['screenToShow'], units='deg', name='win',color=params['screenColor'],colorSpace='rgb255')131# create fixation cross132fCS = params['fixCrossSize'] # size (for brevity)133fCP = params['fixCrossPos'] # position (for brevity)134fixation = visual.ShapeStim(win,lineColor='#000000',lineWidth=3.0,vertices=((fCP[0]-fCS/2,fCP[1]),(fCP[0]+fCS/2,fCP[1]),(fCP[0],fCP[1]),(fCP[0],fCP[1]+fCS/2),(fCP[0],fCP[1]-fCS/2)),units='pix',closeShape=False,name='fixCross');135# create text stimuli136message1 = visual.TextStim(win, pos=[0,+.5], wrapWidth=1.5, color='#000000', alignHoriz='center', name='topMsg', text="aaa",units='norm')137message2 = visual.TextStim(win, pos=[0,-.5], wrapWidth=1.5, color='#000000', alignHoriz='center', name='bottomMsg', text="bbb",units='norm')138# read prompts from text files139[topPrompts,bottomPrompts] = BasicPromptTools.ParsePromptFile(params['promptDir']+params['promptFile'])140print('%d prompts loaded from %s'%(len(topPrompts),params['promptFile']))141# ============================ #142# ======= SUBFUNCTIONS ======= #143# ============================ #144# increment time of next window flip145def AddToFlipTime(tIncrement=1.0):146 tNextFlip[0] += tIncrement147# flip window as soon as possible148def SetFlipTimeToNow():149 tNextFlip[0] = globalClock.getTime()150def CheckForTriggers():151 # get new keys152 newKeys = event.getKeys(keyList=[params['triggerKey'], 'q','escape'],timeStamped=globalClock)153 # check each keypress for escape or trigger keys154 nTriggers = 0155 if len(newKeys)>0:156 for thisKey in newKeys: 157 if thisKey[0] in ['q','escape']: # escape keys158 CoolDown() # exit gracefully159 elif thisKey[0] == params['triggerKey']:160 nTriggers = nTriggers + 1161 162 return nTriggers163def PlayTappingMovie(tapImages, tapText, dt, blockDur_TRs):164 165 # Wait for escape key press or 'blockDur_TRs' triggers166 nTriggers = 0167 SetFlipTimeToNow()168 tBlockStart = globalClock.getTime() # record time when window flipped169 iFrame = 0170 SetFlipTimeToNow()171 while (nTriggers < blockDur_TRs): # until it's time for the next frame # while mov.status != visual.FINISHED:172 # ---tapping movie173 # check for loop or movie end174 if iFrame >= len(tapImages):175 iFrame=0 # rewind to beginning176 177 # Only flip when a new frame should be displayed.178 if globalClock.getTime()>=tNextFlip[0]:179 # draw movie frame, draw text stim, and flip180 tapImages[iFrame].draw()181 tapText.draw()182 win.logOnFlip(level=logging.EXP, msg='Display Frame %d'%iFrame)183 win.flip()184 # increment iFrame185 iFrame = iFrame+1186 # Add to flip time187 AddToFlipTime(dt)188 else:189 # Give the OS a break if a flip is not needed190 ts.sleep(0.001)191 192 193 # Check for triggers and increment trigger count194 nNew = CheckForTriggers()195 nTriggers = nTriggers + nNew196 # check for final trigger197 if nTriggers >= blockDur_TRs:198 break199 200 # allow screen update201 SetFlipTimeToNow()202 203 # Get block time204 tBlock = globalClock.getTime()-tBlockStart205 print('Block time: %.3f seconds'%(tBlock))206 207 return (tBlock)208# Pause until a given number of TRs is received.209def WaitForTrs(tWait_TRs):210 # do IBI211 nTriggers = 0212 while (nTriggers < tWait_TRs):213 # Check for triggers and increment trigger count214 nNew = CheckForTriggers()215 nTriggers = nTriggers + nNew216 if nTriggers >= tWait_TRs:217 break218# Handle end of a session219def CoolDown():220 221 # display cool-down message222 message1.setText("That's the end! ")223 message2.setText("Press 'q' or 'escape' to end the session.")224 win.logOnFlip(level=logging.EXP, msg='Display TheEnd')225 win.clearBuffer() # clear the screen226 message1.draw()227 message2.draw()228 win.flip()229 thisKey = event.waitKeys(keyList=['q','escape'])230 231 # exit232 core.quit()233# =========================== #234# ======= RUN PROMPTS ======= #235# =========================== #236# display prompts237if not params['skipPrompts']:238 BasicPromptTools.RunPrompts(topPrompts,bottomPrompts,win,message1,message2)239# wait for scanner240message1.setText("Please don't move...")241message2.setText("") #("(Press '%c' to override.)"%params['triggerKey'].upper())242message1.draw()243message2.draw()244win.logOnFlip(level=logging.EXP, msg='PleaseDontMove') #'Display WaitingForScanner')245win.flip()246event.waitKeys(keyList=params['triggerKey'])247tStartSession = globalClock.getTime()248AddToFlipTime(tStartSession)249# wait before first stimulus250fixation.draw()251win.logOnFlip(level=logging.EXP, msg='Display Fixation')252win.flip()253WaitForTrs(params['tStartup_TRs']) # wait for the given # of TRs254# =========================== #255# ===== MAIN EXPERIMENT ===== #256# =========================== #257# log experiment start and set up258logging.log(level=logging.EXP, msg='---START EXPERIMENT---')259# run main experiment loop260for iBlock in range(0,params['nBlocks']):261 262 # Run rest period263 print('Resting Block %d: duration=%.2f'%(iBlock, params['restDur_TRs']) )264 # Display fixation cross265 win.clearBuffer() # clear the screen266 fixation.draw() # draw the cross267 win.logOnFlip(level=logging.EXP, msg='Display Fixation')268 win.flip() # flip the window ASAP269 # do rest period270 WaitForTrs(params['restDur_TRs'])271 272 # Load new image stimuli273 tapImages = []274 for i in range(0,params['movieNFrameList'][iBlock]):275 tapImages.append(visual.ImageStim(win, pos=[0,0], name='Movie Frame %d'%i,image='%s%s_%d.png'%(params['movieFolder'],params['moviePrefixList'][iBlock],i), units='pix', size=params['movieSize']))276 # Create bottom text stim277 tapText = visual.TextStim(win, params['moviePromptList'][iBlock], pos=(0, params['movieSize'][1]/2+25), units = 'pix', color='#000000')278 279 # display info to experimenter280 print('Tapping Block %d: movie=%s, framerate=%.2f'%(iBlock, params['moviePrefixList'][iBlock], params['movieFrameRateList'][iBlock]) )281 # display tapping movie282 tBlock = PlayTappingMovie(tapImages=tapImages, tapText=tapText, dt=1.0/params['movieFrameRateList'][iBlock], blockDur_TRs=params['blockDur_TRs'])283# Log end of experiment284logging.log(level=logging.EXP, msg='--- END EXPERIMENT ---')285# exit experiment...

Full Screen

Full Screen

test_sql.py

Source:test_sql.py Github

copy

Full Screen

1# SPDX-FileCopyrightText: 2018-2020 Magenta ApS2# SPDX-License-Identifier: MPL-2.03import os4import pathlib5import unittest6import tap.parser7from oio_rest import config8from oio_rest.db import db_templating, get_connection9from tests import util10from tests.util import DBTestCase11class SQLTests(DBTestCase):12 def setUp(self):13 super().setUp()14 with get_connection() as conn, conn.cursor() as curs:15 curs.execute('CREATE EXTENSION "pgtap";')16 curs.execute(17 'CREATE SCHEMA test AUTHORIZATION "{}";'.format(18 config.get_settings().db_user,19 ),20 )21 for dbfile in pathlib.Path(util.TESTS_DIR).glob("sql/*.sql"):22 curs.execute(dbfile.read_text())23 def tearDown(self):24 super().setUp()25 with get_connection() as conn, conn.cursor() as curs:26 curs.execute("DROP SCHEMA test CASCADE")27 curs.execute('DROP EXTENSION IF EXISTS "pgtap" CASCADE;')28 def test_pgsql(self):29 with get_connection() as conn, conn.cursor() as curs:30 curs.execute("SELECT * FROM runtests ('test'::name)")31 self.assertGreater(curs.rowcount, 0)32 # tap.py doesn't support subtests yet, so strip the line33 # see https://github.com/python-tap/tappy/issues/7134 #35 # please note that the tuple unpacking below is36 # deliberate; we're iterating over over a cursor37 # containing single-item rows38 taptext = "\n".join(line.strip() for (line,) in curs)39 for result in tap.parser.Parser().parse_text(taptext):40 if result.category == "test":41 print(result)42 with self.subTest(result.description):43 if result.skip:44 raise unittest.SkipTest()45 elif not result.ok:46 self.fail(result.diagnostics or result.description)47class TextTests(unittest.TestCase):48 def test_sql_unchanged(self):49 schema_path = os.path.join(50 util.BASE_DIR, "alembic", "versions", "initial_schema.sql"51 )52 expected_path = pathlib.Path(schema_path)53 expected = expected_path.read_text()54 actual = ("\n".join(db_templating.get_sql()) + "\n")55 actual = actual.replace("OWNER TO mox", "OWNER TO {{ mox_user }}")56 self.assertEqual(57 expected,58 actual,59 "SQL changed unexpectedly! We are using Alembic to manage database "60 "changes from now on. Please don't introduce database schema "61 "changes in other ways."...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run fMBT automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful