class Teacher(Thread): def __init__(self, train_data_list, batch_size, augment_func): Thread.__init__(self) self.timer = Timer() self.batch_size = batch_size self.augment_func = augment_func self.train_data_list = copy.deepcopy(train_data_list) def run(self): while True: self.timer.tik() batch_image_data = [] batch_label_data = [] np.random.shuffle(self.train_data_list) batch_data_list = self.train_data_list[:self.batch_size] for data in batch_data_list: image, label = data image = cv2.resize(image, (224, 224)) if self.augment_func is not None: image = self.augment_func(image) batch_image_data.append(image) batch_label_data.append(label) batch_image_data = np.asarray(batch_image_data, dtype=np.float32) batch_label_data = np.asarray(batch_label_data, dtype=np.float32) print('{}ms'.format(self.timer.tok()))
def test_call_repeatedly(self): t = Timer() try: t.schedule.enter_after = Mock() myfun = Mock() myfun.__name__ = bytes_if_py2("myfun") t.call_repeatedly(0.03, myfun) self.assertEqual(t.schedule.enter_after.call_count, 1) args1, _ = t.schedule.enter_after.call_args_list[0] sec1, tref1, _ = args1 self.assertEqual(sec1, 0.03) tref1() self.assertEqual(t.schedule.enter_after.call_count, 2) args2, _ = t.schedule.enter_after.call_args_list[1] sec2, tref2, _ = args2 self.assertEqual(sec2, 0.03) tref2.canceled = True tref2() self.assertEqual(t.schedule.enter_after.call_count, 2) finally: t.stop()
def net_thread(): print 'begin loop' server = Client('localhost', 8081) # asyncore.loop() Timer.addRepeatTimer(common.FRAME_DETAL, lambda: tick()) asyncore_with_timer.loop(0) print 'after loop'
def __init__(self, window): self.teamleft = Team() self.teamright = Team() self.time = Timer(path="Output/Timer.txt", upCounting=True) self.window = window self.penalty = { } # all information about a specific penalty will be saved in this dict
def resetTimer(self): (Timer.is_repeat_timer(self.timer) and Timer.cancel_timer(self.timer)) now = time.time() self._last_check_minute = time.localtime(now)[4] secondsToMinute = (((60 - now) + Crontab.TRIGGER_OFFSET) % 60) self.timer = Timer.addTimer(secondsToMinute, self._resetMinuteTimer).timerid
def __init__(self,learningIterations = 10000,trackingFrequency = 0, learningEvalCheckpoints = np.array([10000]),N = 1000,p_spec=0.5,labelMissingData='NA',discreteAttributeLimit=10,nu=5,chi=0.8,upsilon=0.04,theta_GA=25,theta_del=20,theta_sub=20,acc_sub=0.99,beta=0.2,delta=0.1,init_fit=0.01,fitnessReduction=0.1,doSubsumption=1,selectionMethod='tournament',theta_sel=0.5): """Sets up eLCS model with given parameters """ self.learningIterations = learningIterations self.N = N self.p_spec = p_spec self.labelMissingData = labelMissingData self.discreteAttributeLimit = discreteAttributeLimit self.nu = nu self.chi = chi self.upsilon = upsilon self.theta_GA = theta_GA self.theta_del = theta_del self.theta_sub = theta_sub self.acc_sub = acc_sub self.beta = beta self.delta = delta self.init_fit = init_fit self.fitnessReduction = fitnessReduction self.doSubsumption = doSubsumption self.selectionMethod = selectionMethod self.theta_sel = theta_sel self.trackingFrequency = trackingFrequency self.learningCheckpoints = np.array([1,5,10,20,100,200,500,600,1000,2000,3000,5000,8000,10000]) self.timer = Timer() self.trackingObjs = np.array([]) self.popStatObjs = np.array([])
def test_2(db,collectionName,save): time_total=Timer() time_total.start() #**************** documents=getAllDocuments(db,collectionName,save) time_total.stop() print("Total:{}, load time:{}".format(len(documents),time_total.elapsed))
def test_3(db,collectionName,search_doc,projection={},save=0,limit=0): time_total=Timer() time_total.start() #**************** c= db[collectionName] #search_doc={} #search_doc["f1xxxxxxxx"]= search_str #cursor=c.find(search_doc,projection) if projection: cursor=c.find(search_doc,projection).limit(limit) else: cursor=c.find(search_doc).limit(limit) #cursor=c.find() documentList=[] if save: documentList=list(cursor) #documents=getAllDocuments(db,collectionName,1) time_total.stop() print("Total:{}, search time:{}".format(cursor.count(with_limit_and_skip=True), time_total.elapsed)) # if limit: # print("Total:{}, search time:{}".format(limit,time_total.elapsed)) # else: # print("Total:{}, search time:{}".format(cursor.count(),time_total.elapsed)) return documentList
def __init__(self, logger, params): self.lick_timer = Timer() self.lick_timer.start() self.ready_timer = Timer() self.ready_timer.start() self.ready = False super(DummyProbe, self).__init__(logger, params)
def __init__(self, w, h, title): self.KeyInputState = { "reset": False, "space": False, "b": False, "v": False, "g": False, "h": False, "n": False } self.cam = Camera(60., 1.0, 0.1, 1000.0) #self.cam.setPos([0,10,1], [0,0,0]) #self.cam.setPos([10,10,10], [0,0,0]) #self.cam.setPos([10,5,10], [0,0,0]) #self.cam.setPos([10,2,10], [0,0,0]) self.cam.setPos([20, 10, 10], [0, 0, 0]) self.timer = Timer() self.gridMode = False self.gridAngle = 0 self.gridAxis = [1, 0, 0] self.graphics = Graphics() self.lighting = Lighting() self.scene = Scene() self.background = Background() glutInit(sys.argv) glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH) glutInitWindowSize(w, h) glutInitWindowPosition(100, 100) glutCreateWindow(title) glClearColor(0.25, 0.25, 0.25, 1.0) glEnable(GL_DEPTH_TEST) self.lighting.LightSet()
class Paddle(Collider): def __init__(self, position, speed, size): Collider.__init__(self, position, size) self.timer = Timer() self.speed = speed self.mv_up = 0 self.mv_down = 0 self.spd_up = 1 self.spd_down = 1 def move(self): self.position.y += self.speed * ( self.mv_up + self.mv_down ) * self.spd_up * self.spd_down * self.timer.get_elapsed() if (self.get_top() < 0): self.set_top(0) elif (self.get_bot() > config.HEIGHT_SCREEN): self.set_bot(config.HEIGHT_SCREEN) def move_up(self, move): self.mv_up = -1 if move else 0 self.timer.set_timer() def move_down(self, move): self.mv_down = 1 if move else 0 self.timer.set_timer() def speed_up(self, speed): self.spd_up = config.SPEED_UP if speed else 1 def speed_down(self, speed): self.spd_down = config.SPEED_DOWN if speed else 1 def speed(self, speed): self.speed += speed
def sendAfter(self, originator, level, msgName, after, *args, **kwargs): import Timer # this is mapped from an M3 SEND statement if not Global.raw_python: args = [ arg.dupe() for arg in args ] for key in kwargs: kwargs[key] = kwargs[key].dupe() cmd = Command.ModelMsgCommand(target=self, msgName=msgName, source=Command.userSrc, level=level, args=args, kwargs=kwargs) #print "SENDING",level #import pdb; pdb.set_trace() cmdList = cmd.redirect(self) DbgStub.ping("send") # this is not right for send after's for cmd in cmdList: # calculate the link overhead if present linkCost = Processors.getLinkCost(self.M3ProcessorName,cmd.target.M3ProcessorName) if after or linkCost: # divide by performance factor if present, then add link cost speed = Processors.getSpeed(self.M3ProcessorName) Timer.insertAfter((after / speed) + linkCost, cmd) else: CommandQueue.insert(cmd)
def tryOneParameter(self, key, fitnessFunctionName, args=(), nbIndividuals=30): #only makes one parameters vary for a range of value firstValue = self.initialIndividual.inputParametersVariable[key]['value']*(1-self.initialIndividual.inputParametersVariable[key]['variation']/100) lastValue = self.initialIndividual.inputParametersVariable[key]['value']*(1+self.initialIndividual.inputParametersVariable[key]['variation']/100) step = (lastValue - firstValue)/nbIndividuals xaxis = [firstValue]*nbIndividuals yaxis = [None]*nbIndividuals newIndiv = copy.deepcopy(self.initialIndividual) newIndiv.inputParametersVariable[key]['value'] = firstValue with Timer.LoggerTimer("{} {} | Fitness : {} | Computation Time ".format(newIndiv.inputParametersVariable[key]['name'], newIndiv.inputParametersVariable[key]['value'], newIndiv.fitness)): #bug, la fitness affichée est la fitness d'avant le calcul newIndiv.calc(getattr(newIndiv, fitnessFunctionName), args) yaxis[0] = newIndiv.fitness for i in range(nbIndividuals - 1): newIndiv.inputParametersVariable[key]['value'] = newIndiv.inputParametersVariable[key]['value'] + step with Timer.LoggerTimer("{} {} | Fitness : {} | Computation Time ".format(newIndiv.inputParametersVariable[key]['name'], newIndiv.inputParametersVariable[key]['value'], newIndiv.fitness)): newIndiv.calc(getattr(newIndiv, fitnessFunctionName), args) xaxis[i+1] = newIndiv.inputParametersVariable[key]['value'] yaxis[i+1] = newIndiv.fitness if (newIndiv.fitness < self.bestIndividual.fitness): self.bestIndividual = newIndiv return (xaxis, yaxis)
def __init__(self, w, h, title): self.cam = Camera(90.0, 800/600,1, 100000.0) self.eye = [0.0, -2000.0, 3800.0] self.target = [0.0, 0.0, 2500.0] self.up = [0.0, 0.0, 1.0] self.cam.setPos(self.eye, self.target) self.timer = Timer() self.gridMode = False self.gridAngle = 0 self.gridAxis = [1,0,0] self.graphics = Graphics() self.lighting = Lighting() self.scene = Scene() self.background = Background() self.obj_basic = OBJ('island_basic_1.obj', swapyz=True) self.obj_snow = OBJ('island_basic_snow.obj', swapyz=True) self.obj_rain = OBJ('island_basic_rain.obj', swapyz=True) self.obj = self.obj_basic glutInit(sys.argv) glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH) glutInitWindowSize(w, h) glutInitWindowPosition(800, 600) glEnable(GL_DEPTH_TEST) glShadeModel(GL_SMOOTH) self.lighting.LightSet()
class Behavior: """ This class handles the behavior variables """ def __init__(self, logger, params): self.resp_int = params['response_interval'] self.resp_timer = Timer() self.resp_timer.start() self.logger = logger def is_licking(self): return False def is_ready(self): return False, 0 def water_reward(self, probe): print('Giving Water at probe:%1d' % probe) def punish_with_air(self, probe, air_dur=200): print('Punishing with Air at probe:%1d' % probe) def give_odor(self, delivery_probe, odor_idx, odor_dur, odor_dutycycle): print('Odor %1d presentation for %d' % (odor_idx, odor_dur)) def inactivity_time(self): # in minutes return 0 def cleanup(self): pass def get_in_position(self): pass def get_off_position(self): pass
def test_call_repeatedly(self): t = Timer() try: t.schedule.enter_after = Mock() myfun = Mock() myfun.__name__ = bytes_if_py2('myfun') t.call_repeatedly(0.03, myfun) assert t.schedule.enter_after.call_count == 1 args1, _ = t.schedule.enter_after.call_args_list[0] sec1, tref1, _ = args1 assert sec1 == 0.03 tref1() assert t.schedule.enter_after.call_count == 2 args2, _ = t.schedule.enter_after.call_args_list[1] sec2, tref2, _ = args2 assert sec2 == 0.03 tref2.canceled = True tref2() assert t.schedule.enter_after.call_count == 2 finally: t.stop()
class LegMotion(object): def __init__(self, startValues, endValues, time = 5.0): self.startValues = startValues self.endValues = endValues self.time = time self.motionTimer = Timer() self.start() def start(self): self.motionTimer.start() def currentValues(self, dt): return LegMotion.extrapolateBatch(self.startValues, self.endValues, self.motionTimer.elapsedTime() + dt, self.time) def isDone(self): return self.motionTimer.elapsedTime() > self.time @staticmethod def extrapolate(startValue, endValue, currentTime, totalTime): if currentTime > totalTime: return endValue return startValue + (endValue - startValue) * (currentTime / totalTime) @staticmethod def extrapolateBatch(startValues, endValues, currentTime, totalTime): if len(startValues) != len(endValues): print("Error: startValues and endValues must have the same length in LegMotion.extrapolateBatch()") res = [] for i in range(len(startValues)): res.append(LegMotion.extrapolate(startValues[i], endValues[i], currentTime, totalTime)) return res
class SimulationBillard: def __init__(self, dimTableInPixels): assert dimTableInPixels.x == 2 * dimTableInPixels.y self.root = Tk() self.root.title("Simulation billard") self.dimTableInPixels = dimTableInPixels self._initTable() self._initBalls() self.timerBetweenUpdates = Timer() def start(self): self.timerBetweenUpdates.start() self.table.after(0, self._update) self.root.mainloop() def _initTable(self): dimTableInMeters = Vec2(3.1, 3.1 / 2) self.table = Table(self.root, dimTableInMeters, self.dimTableInPixels) self.table.pack() def _initBalls(self): ballCount = 12 for i in range(0, ballCount): self.table.addBall() def _update(self): dt = self.timerBetweenUpdates.getElapsedTimeAndRestart() self.table.executeNextStepInSimulation(dt) self.table.after(1, self._update)
def reset(): tm.ldTrack() timer.reset() points.points = 0.0 player.innerce = 0.0 player.isAlive = True glv.press = 0 glv.ForceReset = False
def main(): while True: if os.path.exists('config.json'): Timer.configurator() else: print('Creating config file') with open('config.json', 'w') as f: json.dump(config, f, indent=4)
def deactive(self): self._is_deactive = True self.set_tick(None) for timerid in self._timers: Timer.cancel_timer(timerid) self._timers = {} self.add_timer = self.add_repeat_timer = self._on_timer = NonexistentSwallower( )
def init_params(self): self.last_trial = 0 self.queue = Queue() self.timer = Timer() self.trial_start = 0 self.curr_cond = [] self.task_idx = [] self.reward_amount = []
def __init__(self, position, speed, size): Collider.__init__(self, position, size) self.timer = Timer() self.speed = speed self.mv_up = 0 self.mv_down = 0 self.spd_up = 1 self.spd_down = 1
class NPC: AllNPCs = [] def __init__(self, name, pos, sprite, dialog): self.Name = name self.X = pos[0] self.Y = pos[1] self.Dialog = dialog self.width = sprite.get_width() self.deight = sprite.get_height() self.walking = False self.Timer = Timer(1) self.Timer.OnNext = lambda: MoveNPC( self ) #if we dont use lambda it will understand that the function return something self.Timer.Start() self.LastLocation = [0, 0] #GET NPC FACES self.facing = "south" self.faces = get_faces(sprite) #PUBLISH NPC.AllNPCs.append(self) ##-------------------------------------------- ##-------------------------------------------- def Render(self, surface): self.Timer.Update() if self.walking: move_speed = 0 * Globals.deltatime if self.facing == "south": self.Y += move_speed elif self.facing == "north": self.Y -= move_speed elif self.facing == "east": self.X += move_speed elif self.facing == "west": self.X -= move_speed ##-------------------------------------------- ##-------------------------------------------- # BLOCK TILE NPC IS STANDING ON location = [round(self.X / Tiles.Size), round(self.Y / Tiles.Size)] if self.LastLocation in Tiles.Blocked: Tiles.Blocked.remove(self.LastLocation) if not location in Tiles.Blocked: Tiles.Blocked.append(location) self.LastLocation = location surface.blit(self.faces[self.facing], (self.X + Globals.camera_x, self.Y + Globals.camera_y))
def test_enter_after(self): t = Timer() t._enter = Mock() fun = Mock(name='fun') time = Mock(name='time') time.return_value = 10 t.enter_after(10, fun, time=time) time.assert_called_with() t._enter.assert_called_with(20, 0, fun)
def test_supports_Timer_interface(self): x = Timer() x.stop() tref = Mock() x.cancel(tref) tref.cancel.assert_called_with() assert x.schedule is x
def __init__(self, train_data_list, batch_size, augment_func): Thread.__init__(self) self.timer = Timer() self.batch_size = batch_size self.augment_func = augment_func self.train_data_list = copy.deepcopy(train_data_list)
def toStart(message, controller): if message is not "": global TIMEVAR controller.show_frame(StartGame) global USERNAME USERNAME = message Timer.startTimer(SCORE,TIMEVAR)
def __init__(self, logger): self.logger = logger self.probe1 = False self.probe2 = False self.ready = False self.timer_probe1 = Timer() self.timer_probe2 = Timer() self.timer_ready = Timer() self.__calc_pulse_dur(logger.reward_amount) self.thread = ThreadPoolExecutor(max_workers=2)
def __init__(self, dimTableInPixels): assert dimTableInPixels.x == 2 * dimTableInPixels.y self.root = Tk() self.root.title("Simulation billard") self.dimTableInPixels = dimTableInPixels self._initTable() self._initBalls() self.timerBetweenUpdates = Timer()
def perform_action(action): if (action == 1): controls.turnLeft() if (action == 2): controls.turnRight() timer.run() player.updatePos() player.checkBounds() sm.calcTestpoints() sm.updateState()
def post_next_level(self): """Mandatory method. This is called once by the core after 'next_level' *and* after the 321 count. You should place stuff in here that run in a seperate thread like sound play.""" # placed here because it's another thread self.timer_f = Timer.Timer(self.timersleep,self.release_fish,\ lock=self.SPG.get_thread_lock(), startnow=True) self.timer_f.start() self.timer_b = Timer.Timer(self.timersleep+1,self.release_bubble,\ lock=self.SPG.get_thread_lock()) self.timer_b.start() self.screen.set_clip((0, 0, 800, self.ty+490))
def convert(file_path): try: with open("sentences.txt", 'rb') as f: sentences = pickle.load(f) except: pdf_texts = [] sentences = [] timer_convert = t.Timer() print(f'PDF conversion start: {timer_convert}.') for filename in os.listdir(file_path): if (".pdf" in filename): print("Converting " + filename + " to pdf.") print(file_path + "/" + filename) pdf_texts.append( pdf_converter.convert(file_path + "/" + filename)) if (".txt" in filename): print("Converting " + filename + " to array.") print(file_path + "/" + filename) with open(file_path + "/" + filename) as f: for line in f: sentences.append(line) return sentences print(f'PDF conversion end: {timer_convert}.') timer_spacy = t.Timer() print(f'Spacy load start: {timer_spacy}.') # python -m spacy download en_core_web_md you will need to install this on first load nlp = spacy.load('en_core_web_md') logging.getLogger( 'tensorflow' ).disabled = True #OPTIONAL - to disable outputs from Tensorflow timer_convert = t.Timer() print(f'Spacy load end: {timer_spacy}.') timer_nlp = t.Timer() text = "" for pdf_text in pdf_texts: text += pdf_text.lower().replace('\n', ' ').replace('\t', ' ').replace( '\xa0', ' ') text += "\n" text = ' '.join(text.split()) nlp.max_length = 1000000000 doc = nlp(text) for i in doc.sents: if len(i) > 1: sentences.append(i.string.strip()) with open("sentences.txt", 'wb') as f: pickle.dump(sentences, f) return sentences
def prepare(self, conditions): self.clock = pygame.time.Clock() self.stim_conditions = dict() self.timer = Timer() self.timer.start() for cond in conditions: params = (GratingCond() & dict(cond_idx=cond) & self.logger.session_key).fetch1() params['grating'] = self.__make_grating(params['spatial_period'], params['direction'], params['phase'], params['contrast'], params['square']) self.stim_conditions[cond] = params
def __mainLoop(self): while not self.done: Timer.tick() self.sprites.update() self.particles.update() while self.paused: self.__gameInput() self.__gameInput() self.collider.DetectCollisions() self.__updateGame() self.__drawScene()
def make_control(argv): 'return a Bunch' print argv parser = argparse.ArgumentParser() parser.add_argument('invocation') parser.add_argument('training_data', choices=arg_type.training_data_choices) parser.add_argument('neighborhood', type=arg_type.neighborhood) parser.add_argument('model', choices=['en', 'gb', 'rf']) parser.add_argument('n_processes', type=int) parser.add_argument('--test', action='store_true') parser.add_argument('--trace', action='store_true') parser.add_argument('--year', type=arg_type.year) arg = parser.parse_args(argv) arg.me = arg.invocation.split('.')[0] if arg.trace: pdb.set_trace() dir_working = Path.Path().dir_working() path_out_dir = (os.path.join(dir_working, arg.me + '-test') if arg.test else os.path.join(dir_working, arg.me)) dirutility.assure_exists(path_out_dir) return Bunch.Bunch( arg=arg, path_out_log=os.path.join(path_out_dir, '0log.txt'), timer=Timer.Timer(), )
def make_control(argv): print 'argv', argv parser = argparse.ArgumentParser() parser.add_argument('ticker') parser.add_argument('--test', action='store_true') parser.add_argument('--trace', action='store_true') arg = parser.parse_args(argv[1:]) # ignore invocation name arg.me = 'bds' if arg.trace: pdb.set_trace() random_seed = 123 random.seed(random_seed) # put all output in directory path_out_dir = dirutility.assure_exists('../data/working/' + arg.me + '/' + arg.ticker + '/') return Bunch.Bunch( arg=arg, path_in_dir= '../data/input/7chord_team_folder/NYU/7chord_ticker_universe_nyu_poc/', path_in_glob='*.csv', path_out_dir=path_out_dir, path_out_log=path_out_dir + '0log.txt', path_out_report_ticker_maturity_template=path_out_dir + '%s.txt', path_out_ticker_maturity_template_csv=path_out_dir + '%s.csv', path_out_report_counts=path_out_dir + '0counts.txt', path_out_report_na=path_out_dir + '0na.txt', random_seed=random_seed, test=arg.test, timer=Timer.Timer(), )
class Transition(PubSub): def __init__(self, current, next): PubSub.__init__(self) self.current = current self.next = next self.timer = Timer() self.timer.on('tick', self.on_timer) self.timer.on('finished', self.on_timer_finished) self.timer.on('started', self.on_timer_started) self.parent_temp = None def start(self, delay=0, duration='infinite', interval=0, repeats='infinite', message_type='tick'): if self.current.parent == None or self.current == self.next: return if self.current.transitioning or self.next.transitioning: print 'stopping' return self.emitter = self.current._stage self.timer.start(self.emitter, delay, duration, interval, repeats, message_type) def on_timer_started(self): self.current.transitioning = True self.next.transitioning = True self.next.transition_target = [self.current.x, self.current.y, self.next.width, self.next.height] self.on_start() self.emit('started') self.parent_temp = self.next.parent self.current.parent.add_child(self.next) if self.current.parent.on_stage: self.next.enter(self.current) def on_start(self): pass def on_timer(self): pass def on_stop(self): pass def on_timer_finished(self, event, **kwargs): self.emit('finished', event = event, args = kwargs) self.current.parent.remove_child(self.current) self.current.transitioning = False self.next.transitioning = False self.next.transition_target = None if self.parent_temp is not None: self.parent_temp.add_child(self.current) self.current.exit(self.next) self.on_stop()
def __init__(self, current, next): PubSub.__init__(self) self.current = current self.next = next self.timer = Timer() self.timer.on('tick', self.on_timer) self.timer.on('finished', self.on_timer_finished) self.timer.on('started', self.on_timer_started) self.parent_temp = None
def __init__(self,parent=None,debug=True): super(cMainFrame,self).__init__(parent) self.debug=debug # Gestion des paramêtres projet self.oProjetIMD=Projet.ProjetIMD(self) # Initialiser les différents Timer self.oTimer=Timer.cTimer(self) # Gestion des fonctions de l'IHM, module Notebook self.oNoteBook=NoteBook.NoteBook(self) # Gestion des fonctions de l'IHM, module Notebook self.oPlastProcess=PlastProcess.PlastProcess(self) #Initialisation des éléments IHM self.m_statusBar.SetStatusWidths([250,-1]) if (self.oNoteBook.RefreshOnListBox_vtk(self.oProjetIMD.projet["root"]["dir"]["plast3d"])==-1): print >>sys.stderr,"Erreur: Répertoire ""plast"" de base non présent sous le dossier IMD3D." else: self.oTimer.oRefreshListeofVTKTimer.Start(10000) #Init Visualisation 3D-vtk du cache des points et cell_data self.cache_liste_points={} self.m_choice_vtk_color.Clear() self.m_choice_vtk_color.Append("Z-Hauteur") self.m_choice_vtk_color.SetSelection(0) ##début du test pour chargé un STL et le transformer en BMP 2D#### # a=pystl.cSTL("./stl/ship.stl") # a.read(scale=500,fileformat='b') # _size,_buffer=a.raw_bitmap() # image_bmp = Common.scale_bitmap(wx.BitmapFromBuffer(_size[0],_size[1],_buffer),500,500) # self.TopLevelParent.m_bitmap_test.SetBitmap(image_bmp) ##fin du test #Init du directory PLAST3D-VTK (certaines propriétés IHM de la Class DirPicker ne sont pas settable via wxFormBuilder self.m_dirPicker_PLAST3D.SetPath(self.oProjetIMD.projet["root"]["dir"]["plast3d"]) self.m_dirPicker_PLAST3D.GetPickerCtrl().SetLabel("Répertoire de l'éxécutable PLAST.EXE") #il est impossible de modifier le control text en READ_ONLY après sa création => self.m_dirPicker_PLAST3D.GetTextCtrl().SetDefaultStyle(wx.TE_READONLY) #On opte pour attacher l'événement KILL_FOCUS et SET_FOCUS afi de vérifier si le directory entré "à la main" est juste self.m_dirPicker_PLAST3D.GetTextCtrl().Bind( wx.EVT_KILL_FOCUS, self.OnKillFocus_DIR_PLAST3D ) self.m_dirPicker_PLAST3D.GetTextCtrl().Bind( wx.EVT_SET_FOCUS, self.OnSetFocus_DIR_PLAST3D ) #Message dans la console self.m_textCtrl_console.AppendText("(c) Dynamic3D/Python4D - 01/2013 - Version %s\n"%__version__) self.m_textCtrl_console.AppendText("OpenGL, version utilisée:%s\n" % self.oVueOpenGL.OpenGlVersion.split('-')[0]) if self.debug==True: self.m_textCtrl_console.SetDefaultStyle(wx.TextAttr(wx.RED)) self.m_textCtrl_console.AppendText("(!!!Attention vous êtes en MODE Debug les chargements des fichiers et animations ne sont pas optimisés !!!)\n") self.m_textCtrl_console.SetDefaultStyle(wx.TextAttr(wx.BLACK)) self.m_textCtrl_console.AppendText("Bienvenue sur l'interface OpenGL/Python du projet IMD3D\n") if self.debug==True: sys.stdout = Common.RedirectOutput("out",self.m_textCtrl_console) sys.stderr = Common.RedirectOutput("err",self.m_textCtrl_console) self.Maximize() self.Show() wx.SplashScreen(wx.Bitmap("./images/splash.png"), wx.SPLASH_CENTRE_ON_SCREEN|wx.SPLASH_TIMEOUT,2000, None, -1,style=wx.BORDER_NONE).Show()
def run(self, timeout=None): if timeout: Timer.addTimer(timeout, self.stop) while True: try: if self.profileFlag == 0: self.asyncLoop() else: if self.profile is None: self.createProfile() self.profile.runcall(self.asyncLoop) except KeyboardInterrupt: break except: # ignore all exceptions pass if self.stoped: break asio.closeAll() asio.loop(0.05, True, self.socketMap)
def run(self, export_lim, import_lim, total_delay_time=750): print "Estimating total entries to import...", no_of_entries = self.es_conn.search(index=self.es_index, doc_type='jobTitle', body=self.es_query, size=1)['hits']['total'] print "%d entries" % no_of_entries print "Begin to import..." exported = 0 start = 0 while start <= no_of_entries and (self.hard_lim_export == 0 or start <= self.hard_lim_export): exported_entries = self.es_export_rows(start, export_lim) exported += len(exported_entries) start += export_lim sys.stdout.write("\r Exported %d entries of total %d entries..." % (exported, no_of_entries)) sys.stdout.flush() delay_timer = Timer() self.insert_sqlite(exported_entries, import_lim) delay_timer.sleep_if_not_enough(total_delay_time)
def test_handle_error(self): from datetime import datetime on_error = Mock(name='on_error') s = Timer(on_error=on_error) with patch('kombu.async.timer.to_timestamp') as tot: tot.side_effect = OverflowError() s.enter_at(Entry(lambda: None, (), {}), eta=datetime.now()) s.enter_at(Entry(lambda: None, (), {}), eta=None) s.on_error = None with pytest.raises(OverflowError): s.enter_at(Entry(lambda: None, (), {}), eta=datetime.now()) on_error.assert_called_once() exc = on_error.call_args[0][0] assert isinstance(exc, OverflowError)
def test_handle_error(self): from datetime import datetime scratch = [None] def on_error(exc_info): scratch[0] = exc_info s = Timer(on_error=on_error) with patch("kombu.async.timer.to_timestamp") as tot: tot.side_effect = OverflowError() s.enter_at(Entry(lambda: None, (), {}), eta=datetime.now()) s.enter_at(Entry(lambda: None, (), {}), eta=None) s.on_error = None with self.assertRaises(OverflowError): s.enter_at(Entry(lambda: None, (), {}), eta=datetime.now()) exc = scratch[0] self.assertIsInstance(exc, OverflowError)
def run(self): self.map.run() # Make the enemy objects and add every enemy to the enemy_list. # Every enemy takes a x and y coordinate as argument. # (Spawn point) # And the range it can walk on the x axis. # The fish takes a third argument. # You got two choices: 'Water' or 'Lava'. # According to the fish you want. self.enemy_list.append(Fly(500, 600, 100)) self.enemy_list.append(Fly(1500, 100, 100)) self.enemy_list.append(Tank(2600, 50, 380)) self.enemy_list.append(Fish(1000, 700, 200, 'Water')) # Add a collider for the enemies and the player. # It takes the player, map group(tiles), # an array with all the enemy objects, Reference to # LevelStateManager # as arguments. self.collider = Collider(self.player, self.map.get_group(), self.enemy_list, self.LevelStateManager) # Load the background music. # The pygame.mixer.music.load # method takes the file location as an argument. # It has to be .wav or .mp3. self.level_background_music = \ pygame.mixer.music.load('../Data/Music/Level4_2.mp3') # Play the background music. # This is only necessary in level1, # because we don't stop the music when creating level2. pygame.mixer.music.play() # Create a camera for this level. self.camera = Camera(self.shift_start, self.shift_end, self.map, self.player, self.enemy_list) # Create a timer for this level. self.timer = Timer() # Load the best time of level 1. self.timer.load_best_time(1)
def __drawScene(self): self.screen.fill((0, 0, 0)) for star in Stars(): self.screen.set_at(star, (200, 200, 200)) self.sprites.draw(self.screen) self.particles.draw(self.screen) render_text(self.screen, "Score: %06d" % self.score, self.font, (10, 10)) render_text(self.screen, "High: %06d" % self.highscore, self.font, (SCREEN_WIDTH/2, 10),True) render_text(self.screen, "Level: %d" % self.num_level, self.font, (SCREEN_WIDTH-140, 10)) if (self.display_fps): render_text(self.screen, "FPS: %d" % (1000/Timer.get_frame_time()), self.font, (SCREEN_WIDTH-140, 50)) for i in range(self.lives): LifeImage(self.screen, (20 + i*20, 50)) if self.state==STATE_END_GAME: render_text(self.screen, self.text_end_game[0], self.font2, (SCREEN_WIDTH/2, SCREEN_HEIGHT/2-40), True) i=1 while i<len(self.text_end_game): render_text(self.screen, self.text_end_game[i], self.font3, (SCREEN_WIDTH/2, SCREEN_HEIGHT/2+self.font3.get_height()*i), True) i+=1 if self.state==STATE_MAIN and self.timerManager.get_timer(STATE_TIMER)<1000: render_text(self.screen, "Level "+str(self.num_level+1), self.font2, (SCREEN_WIDTH/2, SCREEN_HEIGHT/3), True) pygame.display.flip()
from Timer import * from sys import argv from ES2SQLite import ES2SQLite from FindSpecChar import FindSpecChar from SuggesterCleanUp import SuggesterCleanUp if __name__ == '__main__': timer = Timer() configfile = 'config.cfg' if len(argv) > 1: if argv[1] == 'import': es2sqlite = ES2SQLite(configfile, 'SRC_ES') es2sqlite.create_sqlite_table() # es2sqlite.set_hard_lim_export(1) es2sqlite.run(export_lim=1000, import_lim=250, total_delay_time=100) elif argv[1] == 'importfile': if len(argv) < 3: print "Please enter file name" else: filename = argv[2] es2sqlite = ES2SQLite(configfile, 'DES_ES') es2sqlite.create_sqlite_table() es2sqlite.insert_from_file(filename) clean_up = SuggesterCleanUp(configfile, 'DES_ES') print "Pre clean up:" clean_up.create_tables() clean_up.import_to_unique_table()
def test_1(idList,save,projection={}): time_total=Timer() time_total.start() t = Timer() t.start() #**************** documentList=[] for id in range(len(idList)): if type(idList[id])==str: _id=ObjectId(idList[id]) else: _id=idList[id] if projection: doc=model.find_one({"_id": _id},projection) else: doc=model.find_one({"_id": _id}) # doc=model.find_one({"_id": idList[id]}) if save: documentList.append(doc) if id % 10000 == 0 or idList==0: t.stop() print(str(id)+" : "+str(t.elapsed)) t.reset() t.start() time_total.stop() print("Total:{}, load time:{}".format(len(idList),time_total.elapsed)) return documentList
class TestTimer(unittest.TestCase): def setUp(self): self.tm = Timer(OpenRTM_aist.TimeValue()) def tearDown(self): time.sleep(0.1) def test_start_stop(self): self.tm.start() self.tm.stop() def test_invoke(self): self.tm.registerListenerFunc(test().func, OpenRTM_aist.TimeValue()) self.tm.registerListenerFunc(test().func, OpenRTM_aist.TimeValue()) self.tm.invoke() def test_registerListener(self): self.tm.registerListener(test(), OpenRTM_aist.TimeValue()) self.tm.invoke() pass def test_registerListenerObj(self): self.tm.registerListenerObj(test(), test.func, OpenRTM_aist.TimeValue()) self.tm.invoke() def test_registerListenerFunc(self): self.tm.registerListenerFunc(test().func, OpenRTM_aist.TimeValue()) self.tm.invoke() def test_unregisterListener(self): obj = OpenRTM_aist.ListenerObject(test(),test.func) self.tm.registerListener(obj, OpenRTM_aist.TimeValue()) self.assertEqual(self.tm.unregisterListener(obj),True) self.assertEqual(self.tm.unregisterListener(obj),False)
def start(self): from Log import * Log.debug("Start scheduler") timer = Timer() timer.setCurrentDateAndTime() processID = os.getpid() Log.debug("Start to operate bot [" + str(processID) + "]\n") # Make a pattern self.patternDelegator.startToGetPattern(self.jobHashMap) Log.debug("=============================================") Log.debug("=================== Ready ===================") Log.debug("=============================================") while self.continued: try: start = self.checkNextHour(timer) # After generating the pattern # Send the report to the manager # and wait for the start message if self.firstStep: #Log.debug("Send the action message to the manager\n") #reportToSend = makeManagerJsonData(self.userID) #recvMsgFromManager = self.networkingWithManager(reportToSend) self.firstStep = False #if len(recvMsgFromManager) == 0: # Log.error("Fail to receive the action message from the manager") # self.continued = False # continue if start: Log.debug("=============================================") Log.debug("=================== Start ===================") Log.debug("=============================================") currentHour = timer.getCurrentHour() while start: nextJobToWork = self.jobHashMap.dequeJobValueByKey(currentHour) if nextJobToWork == 0: start = False Log.debug("Complete sending requests") break delay = random.randrange(1, 6) time.sleep(delay) Log.debug("Start to communicate with servers\n") dstName = self.getDstName(nextJobToWork) Log.debug("Start to find dstName in Hash\n") if not self.isIncludedInHash(dstName): dstIPAddress = self.startToCommunicationWithBroker(nextJobToWork) self.addInHash(dstName, dstIPAddress) if self.hash_dstIPAddress[dstName]: self.startToCommunicateWithService(nextJobToWork, dstIPAddress) if not self.continued: break Log.debug("Wait for next hour\n") wait = timer.getWaitTimeForNextHour() time.sleep(wait) timer.setCurrentDateAndTime() except Exception as e: Log.error("There is error in scheduler") Log.error(e) sys.exit(1) Log.debug("Successfully end the one day job") sys.exit(0)
result = w.torder(context.stocks[index],"Sell",buy_1,hold_volume,logonid=context.logonid) context.maxprice[index] = buy_1 context.cash[index] = context.cash[index] + (buy_1*hold_volume) #print result print 'sell '+context.stocks[index]+' '+str(hold_volume)+'@'+str(buy_1)+'\n' if buy_1 > context.maxprice[index]: context.maxprice[index] = buy_1 return() w.start() context = Context() while True: while Timer.isBegin(): context.logon() context.getPosition() context.getPrice() for index,stock in enumerate(context.stocks): Trade(context,index) fp = open('trade.data','w') fp.write(str(context.maxprice)+'\n') fp.write(str(context.cash)) fp.close() sleep(10)
def __init__(self, aKernel): self.kernel = aKernel self.pc = 0 self.pcbCurrent = None self.timer = Timer(self.kernel)
class CPU: def __init__(self, aKernel): self.kernel = aKernel self.pc = 0 self.pcbCurrent = None self.timer = Timer(self.kernel) def initializeThread(self): self.timer.initializeThread() def fetchInstruction(self,): #lo hace en modo usuario VERIFICAR if self.hayPCB(): if self.pcbCurrent.isProgramInMemory(): self.runInstruccion() else: self.kernel.mmu.saveInMemory(self.pcbCurrent)#carga el programa en memoria self.runInstruccion() else: self.kernel.manageIRQ.nilInterrupt() def hayPCB(self): return self.pcbCurrent != None def runInstruccion(self): if not self.isLastInstruccion(): nextInstruccion = self.readInstruccion() if self.nextIsIO(nextInstruccion): # Validar (si es una instruccion de I/O) para hacer una IRQ self.iOInterrupt(self.pcbCurrent, nextInstruccion) #EL PC LO INCREMENTA LUEGO DE EL HANDLER IO EJECUTE LA INSTRUCCION else: self.runCPUInstrucction(nextInstruccion) def runCPUInstrucction(self, nextInstruccion): self.pcbCurrent.changeStatus(State.RUNNING) nextInstruccion.execute() self.pcbCurrent.increasePc() self.pcbCurrent.changeStatus(State.READY) #Analizar si es necesario def readInstruccion(self): instruccion=self.kernel.mmu.read(self.pcbCurrent.nextDirInstruccion()) return instruccion def nextIsIO(self, instruccion): return instruccion.isIO() def isLastInstruccion(self): if self.pcbCurrent.isLastInstruccion(): self.killInterrupt() return True else: return False def iOInterrupt(self, aPCB , nextInstruccion): self.kernel.manageIRQ.iOInterrupt(aPCB, nextInstruccion) def killInterrupt(self): self.kernel.manageIRQ.killInterrupt() def setPCB(self , aPCB): self.pcbCurrent = aPCB def getPCB(self): return self.pcbCurrent
def setUp(self): self.tm = Timer(OpenRTM_aist.TimeValue())
def test_enter_exit(self): x = Timer() x.stop = Mock(name='timer.stop') with x: pass x.stop.assert_called_with()
def test_cancel(self): t = Timer() tref = Mock() t.cancel(tref) tref.cancel.assert_called_with()
class Level1State(LevelState.LevelState): map = None player = None level_state_manager = None collider = None level_background_music = None main_menu = None camera = None timer = None # List to hold all the enemy objects. enemy_list = [] # Spawn point of the player. player_spawn_x = 270 player_spawn_y = 100 # The X value on which the player needs # to be when starting to shift the map and stop shifting the map. shift_start = 410 shift_end = 3290 cloud_images = [] # Half the width of the surface. # This is needed for the placement of the images/sprites. half_screen_width = Artist.get_half_screen_width() def __init__(self, level_state_manager, main_menu): self.cloud_images = [] self.enemy_list = [] # The map variable is a TileGrid object. # The map contains an multidimensional array of tiles. # This creates the map self.map = TileGrid(DatabaseReceiver.get_level_data ("TXT", "Level1", "Level1")) self.main_menu = main_menu self.LevelStateManager = level_state_manager # Create a player object with the x and y # value in which the player should spawn and the # LevelStateManager. self.player = Player(self.player_spawn_x, self.player_spawn_y, level_state_manager) # Statement to set the player_x variable in the map class. # It is necessary for the camera # that the map knows the x coordinate of the spawn point. self.map.set_player_x(self.player_spawn_x) # This variable creates the background of the level. # It uses the DatabaseReceiver to get the image from, # the database. self.background = Background( DatabaseReceiver.get_level_data( "IMAGE", "Level1", "BackgroundEen")) self.cloud_images.append(img.Image( DatabaseReceiver.get_level_data( "IMAGE", "Level1", "cloud1"), 200, 300, 0.5)) self.cloud_images.append(img.Image( DatabaseReceiver.get_level_data( "IMAGE", "Level1", "cloud1"), 500, 200, 0.5)) self.cloud_images.append(img.Image( DatabaseReceiver.get_level_data( "IMAGE", "Level1", "cloud2"), 800, 250, 0.7)) self.cloud_images.append(img.Image( DatabaseReceiver.get_level_data( "IMAGE", "Level1", "cloud3"), 950, 100, 0.5)) self.cloud_images.append(img.Image( DatabaseReceiver.get_level_data( "IMAGE", "Level1", "cloud1"), 1200, 300, 0.5)) self.cloud_images.append(img.Image( DatabaseReceiver.get_level_data( "IMAGE", "Level1", "cloud2"), 1500, 250, 0.5)) self.cloud_images.append(img.Image( DatabaseReceiver.get_level_data( "IMAGE", "Level1", "cloud3"), 2000, 500, 0.5)) def run(self): self.map.run() # Make the enemy objects and add every enemy to the enemy_list. # Every enemy takes a x and y coordinate as argument. # (Spawn point) # And the range it can walk on the x axis. # The fish takes a third argument. # You got two choices: 'Water' or 'Lava'. # According to the fish you want. self.enemy_list.append(Fly(500, 600, 100)) self.enemy_list.append(Fly(1500, 100, 100)) self.enemy_list.append(Tank(2600, 50, 380)) self.enemy_list.append(Fish(1000, 700, 200, 'Water')) # Add a collider for the enemies and the player. # It takes the player, map group(tiles), # an array with all the enemy objects, Reference to # LevelStateManager # as arguments. self.collider = Collider(self.player, self.map.get_group(), self.enemy_list, self.LevelStateManager) # Load the background music. # The pygame.mixer.music.load # method takes the file location as an argument. # It has to be .wav or .mp3. self.level_background_music = \ pygame.mixer.music.load('../Data/Music/Level4_2.mp3') # Play the background music. # This is only necessary in level1, # because we don't stop the music when creating level2. pygame.mixer.music.play() # Create a camera for this level. self.camera = Camera(self.shift_start, self.shift_end, self.map, self.player, self.enemy_list) # Create a timer for this level. self.timer = Timer() # Load the best time of level 1. self.timer.load_best_time(1) def update(self): # Update the camera with the player's x speed. self.camera.update_camera(self.player.x_speed) self.timer.update() self.player.update() # Update all the enemies in the enemy_list. self.enemy_list = self.collider.enemy_list for e in self.enemy_list: e.update() self.collider.update() self.background.update(self.player.x_speed, 0, self.player.rect.x) # Update the clouds. for image in self.cloud_images: image.update(self.player.x_speed, 0, self.player.rect.x) # Opens the MainMenu when you press on the escape key. if pygame.key.get_pressed()[pygame.K_ESCAPE]: self.LevelStateManager.level_state = self self.LevelStateManager.states = self.main_menu def draw(self): self.background.draw() # Draw all the clouds on the surface. for cloud in self.cloud_images: cloud.draw() self.map.draw() # Draw all the enemies. for e in self.enemy_list: e.draw() self.player.draw() self.timer.draw() # Reset the best time with the given level. # The best time is in the lower right corner of all the levels. def reset_best_time(self): self.timer.reset_best_time(1)
def __init__(self, startValues, endValues, time = 5.0): self.startValues = startValues self.endValues = endValues self.time = time self.motionTimer = Timer() self.start()