def tick(self): """ advance the clock by one second """ previous_hour = self._hours # super().tick() Clock.tick(self) if (self._hours < previous_hour): self.advance()
def now(cls, clock=None, zone=None): if clock is None and zone is None: return cls.now(Clock.system_default_zone()) elif zone is None: return cls.now(Clock.system(zone)) else: now = clock.instant() offset = clock.getZone().getRules().getOffset(now) return cls.of_epoch_second(now.get_epoch_second(), now.get_nano(), offset)
def handle_ticktock_to_next_update(force): t = res_manager.get_next_update_time() if t < 0: return False else: if force: while Clock.get() < t: Clock.tick() return handle_ticktock(1) else: return handle_ticktock(t - Clock.get())
class System(object): def reset(self, seed=None): self.feq = FutureEventsQueue() self.clock = Clock() self.stats = Stats() if seed is not None: random.seed(seed) self.initialize() def update_averages(self, overall_stats): for stat in self.stats: overall_stats.add(stat, self.stats.get(stat)) def run(self, trials, duration, seed=None): overall_stats = Stats() for i in range(trials): self.reset(seed) while self.feq.has_events(): event = self.feq.next_event() self.clock.update(event.time) if self.clock.has_run(duration): break self.update() self.handle(event) self.finalize() self.update_averages(overall_stats) print "Completed trial %d/%d" % (i+1, trials) print return overall_stats def schedule_event(self, event): """ Convenience function """ self.feq.schedule_event(event) def initialize(self): """ System-specific variables are initialized here and the first event is scheduled """ pass def update(self): """ Anything that must be updated every single iteration regardless of event type goes here """ pass def handle(self, event): """ Updating of system state and stats, and scheduling of next event should go here """ pass def finalize(self): """ All final calculations go here before the stats object is returned """ pass
def main(): database = Database() alarmLog = AlarmLog() summarizer = Summarizer(database, alarmLog) clock = Clock(summarizer) alarmWriter = AlarmWriter(summarizer) driver1 = Driver(1, summarizer) clock.start() alarmWriter.start() driver1.start() sleep(1000)
def __init__(self,screen,bgcolor): screenHeight = screen.get_height() screenWidth = screen.get_width() targetHeight = HDMIClock.defaultHeight * screenHeight Clock.__init__(self,targetHeight,HDMIClock.defaultColor) width = self.clockFace.get_width() height = self.clockFace.get_height() self.dimensions = pygame.Rect((screenWidth-width)/2,(screenHeight-height)/2,width,height) self.screen = screen self.bgcolor = bgcolor
def tick_or_tock(): global __on_tick if not __on_tick: res_manager.changed_res_set.clear() res_manager.run_timer() __on_tick = True if len(__clock_tick_event_receiver) > 0: for receiver in __clock_tick_event_receiver: notify_id = sky_client.write((RECEIVER, "Event", receiver),fill_content_id=True) #sky_client.take(template=(TARGET, notify_id, '?')) else: res_manager.run_listener() Clock.tick() report() __on_tick = False
def run_timer(): clk = Clock.get() if clk not in timers: return callback_list = timers[clk] for callback in callback_list: callback()
def __init__(self, speed, *groups): BackgroundObject.__init__(self, (0, 0), speed, *groups) self.image = pygame.image.load('gfx/terrain/example_editor.png').convert_alpha() self.rect = pygame.Rect((0, app.screen_height - self.image.get_height()), (0, 0)) self.clock = Clock()
def reset(self, seed=None): self.feq = FutureEventsQueue() self.clock = Clock() self.stats = Stats() if seed is not None: random.seed(seed) self.initialize()
def get_next_update_time(): while len(timers) > 0: t = min(timers) if t < Clock.get(): timers.pop(t, None) else: return t return -1
def clockinit(args): POL = GPIO("480", "out") CLK = GPIO("481", "out") clock = Clock(CLK, POL) statestore = StateStore(clock) statestore.restore() nvramstore = NVRAMStore(clock) if args.require_nvram and not nvramstore.restore(): print("Cannot read clock state from the NVRAM. Exiting...") sys.exit(1) if args.invert: clock.inverse = True if args.uninvert: clock.inverse = False if args.state: clock.setState(args.state) return (clock, statestore, nvramstore)
def run(self): """Method that starts the game running.""" timeController = Clock(self.S_TURN) self.isRunning = True while self.isRunning: # start turn timeController.start() leftTime = self.S_TURN #TODO think if input should be processed inside the inner loop # process user input to Game self.iMngr.processUserInput(self) #isRunning = not self.iMngr.closedGame() while timeController.time_left() > self.S_UPDATE: #sync with remote self.nMngr.updateGame(self) # update state of the game self.uMngr.updateGame(self) #newState = self.readState() #self.world.update(newState) # play sounds self.sMngr.updateGame(self) # render self.gMngr.draw(timeController.time_left(), self) #self.worldView.draw() # sleep if necessary timeController.sleep()
def report_xml(file_name="report.xml", clock=-1): cur = Clock.get() if clock < 0: clock += cur content = E.content(clock=str(clock)) for name in pool: value = str(pool.get(name).get_value(clock)) content.insert(0, E.feature(E.name(name), E.currentValue(value))) with open(file_name, "w") as fout: fout.write(tostring(content, encoding='utf-8', xml_declaration=True, pretty_print=True))
def get_value(self, clock=-1): cur = Clock.get() if clock < 0: clock = cur + clock if clock > cur or clock < 0: return None for item in reversed(self.value): if item[0] <= clock: return item[1]
def get_value(value, v): if utils.is_callable(value): return value() elif value == "$self": return v elif value == "$clock": return Clock.get() elif utils.is_string(value) and value.startswith("$"): return res_manager.get(value[1:]) else: return value
class BackgroundImage(BackgroundObject): def __init__(self, speed, *groups): BackgroundObject.__init__(self, (0, 0), speed, *groups) self.image = pygame.image.load('gfx/terrain/example_editor.png').convert_alpha() self.rect = pygame.Rect((0, app.screen_height - self.image.get_height()), (0, 0)) self.clock = Clock() def update(self): delta_y = round(self.clock.frame_span() * self.speed / 1000) self.rect.move_ip(0, delta_y)
class System(object): def reset(self, seed=None): self.feq = FutureEventsQueue() self.clock = Clock() self.stats = Stats() if seed is not None: random.seed(seed) self.initialize() def run(self, duration, seed=None): self.reset(seed) while self.feq.has_events(): event = self.feq.next_event() self.clock.update(event.time) if self.clock.has_run(duration): break self.update() self.handle(event) return self.stats def schedule_event(self, event): """ Convenience function """ self.feq.schedule_event(event) def initialize(self): """ System-specific variables are initialized here and the first event is scheduled """ pass def update(self): """ Anything that must be updated every single iteration regardless of event type goes here """ pass def handle(self, event): """ Updating of system state and stats, and scheduling of next event should go here """ pass
def __init__(self, aSize): self.disc = Disc() self.memory = MainMemory(aSize) self.memoryManager = ContinuousAssignment(LogicalMemory(self.memory),self) self.handler = InterruptionHandler(self) self.cpu = Cpu(self.memoryManager,self.handler) self.scheduler = Scheduler(self.cpu) self.clock = Clock() self.IO = io.IO(self) self.clock.addSuscribed(self.cpu) self.clock.addSuscribed(self.IO) self.clock.addSuscribed(self.handler) #tabla que contiene todos los pcb (k,v) => (pid,pcb) self.table = {}
def __init__(self): self.clock = Clock() self.logger = logging.getLogger('mats') self.accepting_new_quote = True self.accepting_new_trade = True self.ticker_handlers = { 'incomplete_read': self.incomplete_read_handler, 'ssl_error': self.ssl_error_handler, 'unknown_error': self.unknown_error_handler, 'connected': self.connected_handler, 'new_quote': self.new_quote_handler, 'new_trade': self.new_trade_handler, 'empty_watchlist': self.empty_watchlist_handler }
class BackgroundObject(pygame.sprite.Sprite): def __init__(self, pos, speed, *groups): pygame.sprite.Sprite.__init__(self, *groups) self.rect = pygame.Rect(pos, (0, 0)) self.speed = speed self.clock = Clock() def update(self): delta_y = round(self.clock.frame_span() * self.speed / 1000) self.rect.move_ip(0, delta_y) if self.rect.top >= app.screen_height: self.kill() del self def left(self): return self.rect.left def right(self): return self.rect.right def top(self): return self.rect.top def bottom(self): return self.rect.bottom
def get_value_history(self): values = self.value clk = Clock.get() ret = [None] * clk if values is None or len(values) == 0: return idx = 0 pre_value = None for time, value in values: while idx < time: ret[idx] = pre_value idx += 1 pre_value = value if time < clk: ret[time] = value while idx < clk: ret[idx] = pre_value idx += 1 return ret
def activate(self, ev): """ Instantiate the components and clock for the mode. The event passed in argument contains data sent by the previous mode. For example, the LevelTransitionMode sends a GameStart event containing the next level number to the GameMode. This way, the GameMode knows which level to instantiate. The GameMode sends a GameWon event containing the score to the LevelTransitionMode so that it can be displayed. Small drawback: to keep the code generic, ALL the components are given in argument the mode's EM and the event. Some components may not need the event, but we can't know in advance, so we pass it anyway. """ em = self.em self.active_components = [comp(em, ev) for comp in self.components] self.clock = Clock(em) self.clock.start() # returns when the clock is turned off, ie transition or quit self.em.clear() # this removes the clock and MSM from the EM subscribers self.active_components = [] # last ref to component instances is lost self.clock = None
def main(srvHost, srvPort): w = dict() em = EventManager() nm = NetworkManager(em, w) FRAME_TIME = 0.2 # 200 ms c = Clock(FRAME_TIME) c.start() slept_time = 0.0 nm.start(srvHost, srvPort) counter = 100 exit = False while not exit: nm.update(slept_time + c.time_passed()) counter -= 1 if counter <= 0: exit = True slept_time = c.time_left() c.sleep() print "%s" % (counter * FRAME_TIME)
def main(): cliMngr = ClientManager() clock = Clock(FRAMETIME) clock.start() while True: state = '{"team":[[10,10]],[[10,20]]}' # check if there are new clients trying to conect cliMngr.receive_connections() # send game state to all clients cliMngr.broadcast(state) # read clients input while we can timeout = clock.time_left() cliMngr.read_incoming_msgs(timeout) # drop clients that are not responsive cliMngr.check_clients_liveness() clock.sleep()
def start (self): """Creates the socket and starts the threads""" try: self.piglow = PiGlow () except IOError as e: if e[0] == errno.EACCES: print >> sys.stderr, "Permission denied, try running as root" else: print >> sys.stderr, "Unknown error accessing the PiGlow" sys.exit (1) self.piglow.all (0) self.clock = Clock (self.piglow) self.alert = Alert (self.piglow) self.in_progress = In_Progress (self.piglow) address = (self.cfg.HOST, self.cfg.PORT) serversock = socket (AF_INET, SOCK_STREAM) serversock.setsockopt (SOL_SOCKET, SO_REUSEADDR, 1) serversock.bind (address) serversock.listen (5) self.check_jobs_thread = Thread (None, self.check_jobs, None, ()) self.socket_manager_thread = Thread (None, self.socket_manager, None, (serversock, )) self.start_threads () while self.running == True: sleep (1) self.stop ()
def test_clocks_with_negative_hours_and_minutes(self): self.assertEqual(Clock(7, 32), Clock(-12, -268))
class TheLoop: def __init__(self): self.clock = Clock() self.logger = logging.getLogger('mats') self.accepting_new_quote = True self.accepting_new_trade = True self.ticker_handlers = { 'incomplete_read': self.incomplete_read_handler, 'ssl_error': self.ssl_error_handler, 'unknown_error': self.unknown_error_handler, 'connected': self.connected_handler, 'new_quote': self.new_quote_handler, 'new_trade': self.new_trade_handler, 'empty_watchlist': self.empty_watchlist_handler } def loop(self): self.ticker_p, self.ticker_conn = self.launch_ticker() while True: self.loop_iter() def loop_iter(self): if not self.clock.is_market_open(): self.logger.info('theloop: market is closed. killing ticker.') self.ticker_p.terminate() # block until ticker child has time to exit while self.ticker_p.is_alive(): pass # now go to sleep self.go_to_sleep() elif not self.ticker_p.is_alive(): self.ticker_p, self.ticker_conn = self.launch_ticker() if self.ticker_conn.poll(): data = self.ticker_conn.recv() self.ticker_handlers[data.name](data) def ticker(self, conn): ticker = Ticker(conn) ticker.start() def launch_ticker(self): self.logger.info('theloop: spawning ticker child process') parent, child = Pipe() p = Process(target=self.ticker, name='ticker', args=(child,)) p.start() return (p, parent) def incomplete_read_handler(self, data): self.logger.error('theloop: ticker had incompleteread error, attempting to respawn ticker.') self.ticker_p, self.ticker_conn = self.launch_ticker() def ssl_error_handler(self, data): self.logger.error('theloop: ticker had ssl_error, attempting to respawn ticker.') self.ticker_p, self.ticker_conn = self.launch_ticker() def unknown_error_handler(self, data): self.logger.error('theloop: ticker had an unknown error, attempting to respawn ticker.') self.ticker_p, self.ticker_conn = self.launch_ticker() def connected_handler(self, event): self.logger.info('theloop: ticker connected to stream') def go_to_sleep(self): secs = self.clock.secs_until_open() time_slept = time.time() self.logger.info('theloop: sleeping for ' + str(secs) + ' seconds.') time.sleep(secs) secs_asleep = time.time() - time_slept self.logger.info('theloop: waking up after ' + str(secs_asleep) + ' seconds') self.logger.info('theloop: attempting to respawn ticker.') self.ticker_p, self.ticker_conn = self.launch_ticker() def new_quote_handler(self, event): self.logger.debug('theloop: ticker reports new quote') def new_trade_handler(self, event): self.logger.debug('theloop: ticker reports new trade') def empty_watchlist_handler(self, event): self.logger.info('theloop: exiting.') exit(0)
def test_clocks_an_hour_apart(self): self.assertNotEqual(Clock(14, 37), Clock(15, 37))
def test_clocks_with_hour_overflow_by_several_days(self): self.assertEqual(Clock(3, 11), Clock(99, 11))
def test_clocks_with_negative_hour(self): self.assertEqual(Clock(22, 40), Clock(-2, 40))
def test_clocks_with_negative_hour_that_wraps_multiple_times(self): self.assertEqual(Clock(13, 49), Clock(-83, 49))
def test_subtract_more_than_two_days(self): self.assertEqual(str(Clock(2, 20) - 3000), '00:20')
def test_sixty_minutes_is_next_hour(self): self.assertEqual(str(Clock(1, 60)), '02:00')
def test_hour_rolls_over_continuously(self): self.assertEqual(str(Clock(100, 0)), '04:00')
def test_hour_rolls_over(self): self.assertEqual(str(Clock(25, 0)), '01:00')
def test_full_clock_and_zeroed_clock(self): self.assertEqual(Clock(24, 0), Clock(0, 0))
def test_clocks_with_negative_hours_and_minutes_that_wrap(self): self.assertEqual(Clock(18, 7), Clock(-54, -11513))
def test_minutes_roll_over_continuously(self): self.assertEqual(str(Clock(0, 1723)), '04:43')
def test_clocks_with_negative_minute_that_wraps(self): self.assertEqual(Clock(4, 10), Clock(5, -1490))
def test_subtract_more_than_two_hours(self): self.assertEqual(str(Clock(0, 0) - 160), '21:20')
def test_clocks_with_minute_overflow(self): self.assertEqual(Clock(0, 1), Clock(0, 1441))
def test_clocks_with_negative_hour_that_wraps(self): self.assertEqual(Clock(17, 3), Clock(-31, 3))
def test_past_the_hour(self): self.assertEqual(str(Clock(11, 9)), '11:09')
def test_subtract_across_midnight(self): self.assertEqual(str(Clock(0, 3) - 4), '23:59')
def test_clocks_a_minute_apart(self): self.assertNotEqual(Clock(15, 36), Clock(15, 37))
def test_clocks_with_hour_overflow(self): self.assertEqual(Clock(10, 37), Clock(34, 37))
class Kernel: def __init__(self, aSize): self.disc = Disc() self.memory = MainMemory(aSize) self.memoryManager = ContinuousAssignment(LogicalMemory(self.memory),self) self.handler = InterruptionHandler(self) self.cpu = Cpu(self.memoryManager,self.handler) self.scheduler = Scheduler(self.cpu) self.clock = Clock() self.IO = io.IO(self) self.clock.addSuscribed(self.cpu) self.clock.addSuscribed(self.IO) self.clock.addSuscribed(self.handler) #tabla que contiene todos los pcb (k,v) => (pid,pcb) self.table = {} def getLogicalMemory(self): return self.logicalMemory def getMemoryManager(self): return self.memoryManager def getDisc(self): return self.disc def getCpu(self): return self.cpu def getMemory(self): return self.memory def getMemoryManager(self): return self.memoryManager def getHandler(self): return self.handler def getIO(self): return self.IO def getClock(self): return self.clock def getScheduler(self): return self.scheduler def getTable(self): return self.table #Comienza con la ejecucion del clock def startUp(self): self.getClock().startUp() #Corta la ejecucion del clock def shutDown(self): self.getClock().shutDown() def run(self, name): print "[Kernel] Ejecutar programa: " + str(name) self.handler.newIrq(name) #Obtiene todos los programas del disco def getProgramasDelDisco(self, name): return self.getDisc().getProgram(name) #Agrega el pcb en la table def addPcb(self,aPcb): self.table[aPcb.getPid()] = aPcb print "LALALALAAAAA " + str(len(self.table)) #Borra el pcb en la table def removePcb(self,aPcb): #guardo las keys para tener una lista #y ver si la tabla de pcb esta vacia o no keys = self.table.keys() if(len(keys) != 0): del self.table[aPcb.getPid()] print "RERERERERER " + str(len(self.table))
def test_midnight_is_zero_hours(self): self.assertEqual(str(Clock(24, 0)), '00:00')
def test_clocks_with_negative_minute(self): self.assertEqual(Clock(2, 40), Clock(3, -20))
def test_subtract_more_than_one_day(self): self.assertEqual(str(Clock(5, 32) - 1500), '04:32')
def test_clocks_with_negative_minute_that_wraps_multiple_times(self): self.assertEqual(Clock(6, 15), Clock(6, -4305))
def get(data, return_type=None): if type(data) is not dict or "method" not in data: if return_type is None: return data elif return_type == "lambda": return lambda: data else: return None method = data["method"] parameter = data["parameter"] if method.startswith(MATH_PREFIX): if method == METHOD_MATH_ADD: a = get(parameter["a"]) b = get(parameter["b"]) method = lambda value: get_value(a, value) + get_value(b, value) elif method == METHOD_MATH_DIVISION: a = get(parameter["a"]) b = get(parameter["b"]) method = lambda value: get_value(a, value) / get_value(b, value) elif method == METHOD_MATH_MINUS: a = get(parameter["a"]) b = get(parameter["b"]) method = lambda value: get_value(a, value) - get_value(b, value) elif method == METHOD_MATH_MULTIPLY: a = get(parameter["a"]) b = get(parameter["b"]) method = lambda value: get_value(a, value) * get_value(b, value) elif method == METHOD_MATH_MOD: a = get(parameter["a"]) b = get(parameter["b"]) method = lambda value: get_value(a, value) % get_value(b, value) elif method == METHOD_MATH_LINEAR: a = get(parameter["a"]) b = get(parameter["b"]) x = get(parameter["x"]) method = lambda value: get_value(a, value) * get_value(x, value) + get_value(b, value) elif method == METHOD_MATH_SIN: a = get(parameter["a"]) b = get(parameter["b"]) x = get(parameter["x"]) method = lambda value: get_value(a, value) * math.sin(get_value(x, value)) + get_value(b, value) elif method == METHOD_MATH_LOG: a = get(parameter["a"]) b = get(parameter["b"]) x = get(parameter["x"]) method = lambda value: get_value(a, value) * math.log(get_value(x, value)) + get_value(b, value) elif method == METHOD_MATH_MEAN: terms = parameter["term"] method = lambda value: 1.0 * sum([get_value(term, value) for term in terms]) / len(terms) elif method == METHOD_MATH_SUM: terms = parameter["term"] #print terms method = lambda value: sum([get_value(term, value) for term in terms]) else: print "not support method:", method elif method.startswith(PROBABILITY_PREFIX): if method == METHOD_PROBABILITY_MARKOV_CHAIN: state_set = parameter["state_set"] init_state = parameter["init_state"] trans_matrix = parameter["trans_matrix"] method = lambda value: markov_chain(value, state_set, init_state, trans_matrix) elif method == METHOD_PROBABILITY_NORMAL_VARIATE_RAND: mu = get(parameter["mu"]) sigma = get(parameter["sigma"]) method = lambda value: normalvariate(get_value(mu, value), get_value(sigma, value)) elif method == METHOD_PROBABILITY_SIMPLE_RAND: min_value = get(parameter["min"]) max_value = get(parameter["max"]) method = lambda value: randint(get_value(min_value, value), get_value(max_value, value)) else: print "not support method:", method else: if method == METHOD_OTHERS_COMBINE: sections = parameter["section"] # print "sections:", sections method = lambda value: dict((section, get_value(section, value)) for section in sections) elif method == METHOD_OTHERS_DATA_LIST: data_list = parameter["data_list"] method = lambda value: data_list[Clock.get() % len(data_list)] else: print "not support method:", method return method
def test_subtract_more_than_two_hours_with_borrow(self): self.assertEqual(str(Clock(6, 15) - 160), '03:35')
def test_hour_and_minutes_roll_over(self): self.assertEqual(str(Clock(25, 160)), '03:40')
def test_clocks_with_minute_overflow_by_several_days(self): self.assertEqual(Clock(2, 2), Clock(2, 4322))
def __init__(self, pos, speed, *groups): pygame.sprite.Sprite.__init__(self, *groups) self.rect = pygame.Rect(pos, (0, 0)) self.speed = speed self.clock = Clock()
def test_hour_and_minutes_roll_over_continuously(self): self.assertEqual(str(Clock(201, 3001)), '11:01')
def test_minutes_roll_over(self): self.assertEqual(str(Clock(0, 160)), '02:40')
def test_clocks_with_same_time(self): self.assertEqual(Clock(15, 37), Clock(15, 37))