class DashboardTimer(): def __init__(self, interval_min): self.interval_sec = interval_min * 60 self.timer = Timer(self.interval_sec, self._dashboard_update) def run(self): self.timer.run() self.timer = Timer(self.interval_sec, self._dashboard_update) def cancel(self): self.timer.cancel() @staticmethod def _dashboard_update(): disable_warnings(exceptions.InsecureRequestWarning) log_with_timestamp("Start to update dashboard.") dashboard = Dashboard() succeeded = False max_retry = 5 for i in range(0, max_retry): try: dashboard.update() except Exception as e: log_with_timestamp(f'Failed to update dashboard. [{e}]') continue succeeded = True break if succeeded: log_with_timestamp('Dashboard data updated.') else: log_with_timestamp( f'Dashboard data failed to update after {max_retry} retries.')
def main(): while True: today = datetime.datetime.today() # tomorrow = today tomorrow = today.replace(hour=8, minute=0, second=0, microsecond=0) + datetime.timedelta(days=1) delta = tomorrow - today timer = Timer(delta.total_seconds(), broadcast_mail) timer.run()
def callback(event): """ 鼠标左键回调事件,选中图片 :param event: :return: """ global select_first global first_select_rectid, second_select_rectid global p1 global p2 # 换算棋盘坐标 x = event.x // BLOCK_SIZE y = event.y // BLOCK_SIZE print("clicked at", x, y) if map[x][y] == '': showinfo(title="提示", message="此处无方块") else: if not select_first: p1 = Point(x, y) # 在所选块周围画线表示选中 first_select_rectid = cv.create_rectangle(x * BLOCK_SIZE, y * BLOCK_SIZE, (x + 1) * BLOCK_SIZE, (y + 1) * BLOCK_SIZE, outline='blue') select_first = True else: p2 = Point(x, y) # 判断第二次点击是否和第一次点击时同一个坐标 if p1.x == p2.x and p1.y == p2.y: return # 画选中x2, y2处的框线 print("第2次点击的方块", x, y) second_select_rectid = cv.create_rectangle(x * BLOCK_SIZE, y * BLOCK_SIZE, (x + 1) * BLOCK_SIZE, (y + 1) * BLOCK_SIZE, outline='yellow') print("第2次点击的方块", second_select_rectid) cv.pack() # 是同一张图且两者之间可以连通 if is_same_img(p1, p2) and is_link(p1, p2): print("连通", x, y) select_first = False # 画选中方块之间的连接线 draw_link_line(p1, p2) # 定时函数清除连通成功的方块和之间的连线 t = Timer(timer_interval, delay_run) t.run() else: # 删除第一个选定框线和第二个选定框线 cv.delete(first_select_rectid) cv.delete(second_select_rectid) select_first = False
def find2block(event): """ 鼠标右键的回调事件,智能查找功能.查找能够连通的两个点 :param event: :return: """ global first_select_rectid, second_select_rectid m_n_row = WIDTH m_n_col = HEIGHT b_found = False # 第一个方块从地图的0位置开始 for i in range(0, m_n_row * m_n_col): if b_found: break x1 = i % m_n_col y1 = i // m_n_col p1 = Point(x1, y1) # 无图案则继续判断下一个 if map[x1][y1] == "": continue for j in range(i + 1, m_n_row * m_n_col): x2 = j % m_n_col y2 = j // m_n_col p2 = Point(x2, y2) # 第二个方块不为空,且与第一个方块的图标相同 if map[x2][y2] != "" and is_same_img(p1, p2): if is_link(p1, p2): b_found = True break if b_found: print("找到了,", p1.x, p1.y, p2.x, p2.y) # 找到后在两个图标之间绘制连线? first_select_rectid = cv.create_rectangle(x1 * 40, y1 * 40, x1 * 40 + 40, y1 * 40 + 40, width=2, outline='red') second_select_rectid = cv.create_rectangle(x2 * 40, y2 * 40, y2 * 40 + 40, y2 * 40 + 40, width=2, outline='red') # 定时清除连线 t = Timer(timer_interval, delay_run) t.run() return b_found
class SSHConsumer(WebsocketConsumer): def connect(self): self.name = self.scope["url_route"]["kwargs"]["name"] self.kub_stream = Timer(interval=2, function=time_send, args=(self, )) self.kub_stream.run() self.accept() def disconnect(self, close_code): self.kub_stream.cancel() def receive(self, text_data): print("heh")
class Game: def __init__(self, chat_id): self.chat_id = chat_id self.magicians = list() self.type = 'battle' self.turn = 0 self.timer = None self.speed = 60 self.exists = True self.pause = False def join(self, user_id): self.magicians.append(Magician(user_id)) def next_turn(self): if not self.exists: return if not self.magicians: bot.send_message(self.chat_id, 'Все сдохли! Игра окончена.') self.exists = False return elif len(self.magicians) == 1: bot.send_message( self.chat_id, f'{self.magicians[0].name} выиграл! Игра окончена.') self.exists = False return tts = f'Ход {self.turn + 1}!' for magician in self.magicians: tts += f'\n\n{magician.name}:\n' \ f'{magician.heart}️ХП: {magician.xp}' defences = [ constants.rus(element) for element in magician.states['defence'] if magician.states['defence'][element] ] if defences: tts += '\nЗащита от элементов: ' + ", ".join(defences) if magician.states_cleaning: magician.states_cleaning -= 1 else: magician.clean_states() magician.casted = False bot.send_message(self.chat_id, tts) self.turn += 1 self.timer = Timer(30, self.next_turn) self.timer.run()
class Launcher(Frame): def __init__(self, master=None, game=None): Frame.__init__(self, master) self.pack() self.game = game self.banner = Label(self) self.banner.config(text=str(self.game), height=2, font=font.Font(family='Helvetica', size=16, weight='bold')) self.banner.pack(side="top") self.board = Board(self, self.game) self.gameover = Timer(0.1, self.game_over) self.gameover.run() def game_over(self): if self.game.winner is not None: print("GAME OVER") else: print("Continue to play")
async def giveaway(self, ctx, time: str, *item): if not time.isdigit(): return await ctx.send('Use: `?giveaway (time in minutes) (item)`') embed = Embed(title='Giveaway', color='red', description=' '.join(item)) msg = await ctx.send(embed) msg.add_reaction('🎉') def check(): reacted = [ reaction for reaction in msg.reactions if reaction.emoji is '🎉' ][0].users().flatten() pps = [ user for user in reacted if user.id is not self.bot.user.id and user.id in map(get_id, iter(ctx.guild.members)) ] winner = choice(pps) msg.send_message(f'{winner.mention} won the giveaway!') t = Timer(int(time), check) t.run()
def MainProcess(address, user, passwd): try: Driver = chargeDriver(address) Driver = log_in(Driver, user, passwd) commentList = extractComments() for tiempo, comentario in commentList: if (tiempo == None): Driver = comentar(Driver, comentario) sleep(3) else: x = datetime.today() delta_t = tiempo - x secs = delta_t.seconds + 1 print "Quedan " + str( secs) + " segundos para enviar el comentario " + comentario t = Timer(secs, comentar, [Driver, comentario]) t.run() #Aquí debería ir el script Driver.quit() except: traceback.print_exc() raw_input("Ha ocurrido un error, pulsa cualquier tecla para salir.") Driver.quit()
os.chdir(dirname) filename = date.strftime('%Y-%m-%d_%H-%M-%S') capture = cv.CaptureFromCAM(0) img = cv.QueryFrame(capture) cv.SaveImage('%s.jpg' % filename, img) os.chdir('..' + os.sep + '..') printLog('Capture', 'Success ...') except: printLog('Capture', 'Falied ...') def printLog(section, log): date = datetime.datetime.today() print '[%s - %s] %s' % (date.strftime('%Y-%m-%d %H:%M:%S'), section, log) if __name__ == "__main__": printLog('SYSTEM', 'Starting Look at me ...') captureFromCam() sec = 15.0 printLog('SYSTEM', 'Timer Setting ... (%d sec)' % sec) while True: t = Timer(sec, captureFromCam) t.run()
class StreamListener(tweepy.StreamListener): #This is a class provided by tweepy to access the Twitter Streaming API. def __init__(self, api=None, max_tweets=10000, max_mins=10, words_list=None): self.streamming_tweets = 0 self.max_mins = max_mins self.max_tweets = max_tweets self.words_list = words_list self.start_time = time.time() self.message_timer = Timer(5, self.show_messages_info) self.message_timer.start() self.time_timer = Timer(max_mins * 60, self.finalize_by_time) self.time_timer.start() self.mongo_tweets_dict = {} self.mongo_tweets_ids_list = [] self.tweets_no_repetidos = [] self.trunk = min(500, max_tweets) self.first_tweet_id = None self.last_tweet_id = None self.max_created_at = None self.min_created_at = None # self.client = MongoClient(mongo_conector.MONGO_HOST) # # Use twitterdb database. If it doesn't exist, it will be created. # self.db = self.client.twitterdb def show_messages_info(self): print("[SHOW MESSAGES INFO] {} tweets collected in {:.0f} seconds". format(self.streamming_tweets, (time.time() - self.start_time))) self.message_timer.run() def on_connect(self): # Called initially to connect to the Streaming API print("[ON CONNECT] You are now connected to the streaming API.") def finalize_by_time(self): self.on_disconnect( "Se ha agotado el tiempo maximo especificado por el usuario") def on_disconnect(self, notice): self.time_timer.cancel() self.message_timer.cancel() print("[ON DISCONNECT INFO] {}".format(notice)) print( "[ON DISCONNECT INFO] You are now disconnected to the streaming API.\n\n" ) if len(self.mongo_tweets_ids_list) > 0: #coger lo que retorna el insert many tweets_no_reps = mongo_conector.insertar_multiples_tweets_en_mongo_v2( self.mongo_tweets_dict, self.mongo_tweets_ids_list, mongo_conector.current_collection) # cambiar por insert many mongo_conector.insert_or_update_query_file_streamming( mongo_conector.current_collection, self.words_list, len(tweets_no_reps), self.first_tweet_id, self.last_tweet_id, self.min_created_at, self.max_created_at) print("[ON DISCONNECT INFO] FINISH") def on_error(self, status_code): # On error - if an error occurs, display the error / status code print('\n\n[STREAM ERROR] An Error has occured: ' + repr(status_code)) codigo = 0 try: codigo = int(status_code) if codigo == 420: print("[ON ERROR] You have reached your rate limit\n") except Exception as e: pass def on_limit(self, track): print(track + "\n") return def on_status(self, status): """Called when a new status arrives""" pass def on_data(self, data): try: # if "start" in data: # print(data) # Decode the JSON from Twitter datajson = get_mongo_document( data) # controlamos los errores antes de insertarlo if datajson is not None: #analizar tweet current_tweet_id = datajson["id_str"] current_created_at = datajson["created_at"] self.last_tweet_id = current_tweet_id self.max_created_at = current_created_at if self.first_tweet_id == None: self.first_tweet_id = current_tweet_id self.min_created_at = current_created_at self.mongo_tweets_dict[datajson["_id"]] = datajson self.mongo_tweets_ids_list.append(datajson["_id"]) if len(self.mongo_tweets_ids_list) > self.trunk: print( "[ON DATA INFO] {} messages are going to be inserted in mongo" .format(len(self.mongo_tweets_ids_list))) self.tweets_no_repetidos = mongo_conector.insertar_multiples_tweets_en_mongo_v2( self.mongo_tweets_dict, self.mongo_tweets_ids_list, mongo_conector.current_collection ) # cambiar por insert many mongo_conector.insert_or_update_query_file_streamming( mongo_conector.current_collection, self.words_list, len(self.tweets_no_repetidos), self.first_tweet_id, current_tweet_id, self.min_created_at, current_created_at) self.mongo_tweets_dict = {} self.mongo_tweets_ids_list = [] if (self.streamming_tweets >= self.max_tweets): print( "[ON_DATA] \n\n{} messages has been collected".format( self.streamming_tweets)) self.on_disconnect( "User disconnected after get the required amount of tweets" ) return False # paramos el streamming self.streamming_tweets += 1 except Exception as e: print("[ON DATA ERROR] {} {}".format(e, e.__cause__))
class OpenCloseValve(object): 'A class that controls a valve with a close and a open signal' def man(self, tag, value): tag = value self.Documentation(tag, value) return tag def Close(self): self.Man_Close_OUT = True self.CloseTimer = Timer(self.Time_Close, self.man, [self.Man_Close_OUT, False]) self.CloseTimer.run() def Open(self): self.Man_Open_OUT = True self.OpenTimer = Timer(self.Time_Open, self.man, [self.Man_Open_OUT, False]) self.OpenTimer.run() def __init__(self): self.deadband = 2.0 self.Man_Open = False self.Man_Close = False self.Man_Close_OUT = False self.Man_Open_OUT = False self.Name = 'a' self.Time_Open = 3.0 # Seconds the valve shall open self.Time_Close = 2.0 # Seconds the valve shall close #Declar instances for logging #self.Write_Stat_Open = Write_temp(self.Man_Open, 'VS1_SV1_Open') #self.Write_Stat_Close = Write_temp(self.Man_Close, 'VS1_SV1_Close') self.Control_Time = 0 self.Control_Active = False self.ControlTimeReset = time.time() def Documentation(self, direction, value): with open('Docs/' + self.Name, 'a+') as f: f.write('{} went {} {} at {}'.format( self.Name, direction, value, time.time())) def main(self, PV, SP): '''In this method the temperatures are compared, and some control variables are set for later activaion of the IO ''' self.deltaT = SP - PV if self.deadband < self.deltaT: 'If deltaT is bigger than the deadband, open valve and Heat' #Open self.Control_Active = True self.Man_Open = True self.Man_Close = False elif self.deltaT > 0 - self.deadband: '''If deltaT is less than 0 minus deadband, close valve and Dont heat''' #close self.Control_Active = True self.Man_Close = True self.Man_Open = False else: 'If none is true, do nothing' self.Control_Active = False self.Man_Close = False self.Man_Open = False def control(self): '''Here the IO are controlled based on the control variables from main method ''' #Can only run Control method once every 10 seconds if self.Man_Close and self.ControlTimeReset + 10 < time.time() and not self.Man_Open_OUT: #Run the Close method self.Close() #Reset the reset time so it only runs every 10 seconds self.ControlTimeReset = time.time() if self.Man_Open and self.ControlTimeReset + 10 < time.time() and not self.Man_Close_OUT: #Run the Open method self.Open() #Reset the reset time so it only runs every 10 seconds self.ControlTimeReset = time.time()
class Dungeon(Game): def __init__(self, chat_id): super().__init__(chat_id) self.type = 'dungeon' self.level = 0 self.max_level = 5 self.mobs = [] self.win_text = 'Вы очистили все подземелье и дошли до последнего уровня! Выжившие: {}' def init_mobs(self): self.mobs = [ random.choice(constants.mobs[self.level])(game=self, mob_id=i) for i in range( random.randint(len(self.magicians), len(self.magicians) + 2)) ] def next_turn(self): self.next_level() def next_level(self): if not self.exists: return if not self.magicians: bot.send_message( self.chat_id, f'Все маги погибли! Игра окончена. Вы дошли до {self.level} уровня.' ) self.exists = False return if not self.mobs: if self.max_level == self.level: bot.send_message( self.chat_id, self.win_text.format(", ".join( [magician.name for magician in self.magicians]))) return self.turn = 0 self.init_mobs() if not self.mobs and self.level != 0: bot.send_message( self.chat_id, f'Вы убили всех мобов на этом уровне и перешли на следующий,' f' {self.level} уровень!\nНовые мобы: ' f' {", ".join([mob.name for mob in self.mobs])}') self.level += 1 self.turn += 1 tts = f'Уровень {self.level}, ход {self.turn}!' for mob in self.mobs: bot.send_message(self.chat_id, mob.attack()) tts += f'\n\n{mob.name}:\n' \ f'{mob.heart}ХП: {mob.xp}' defences = [ constants.rus(element) for element in mob.states['defence'] if mob.states['defence'][element] ] if defences: tts += '\nЗащита от элементов: ' + ", ".join(defences) for magician in self.magicians: tts += f'\n\n{magician.name}:\n' \ f'{magician.heart}️ХП: {magician.xp}' defences = [ constants.rus(element) for element in magician.states['defence'] if magician.states['defence'][element] ] if defences: tts += '\nЗащита от элементов: ' + ", ".join(defences) if magician.states_cleaning: magician.states_cleaning -= 1 else: magician.clean_states() magician.casted = False bot.send_message(self.chat_id, tts) self.timer = Timer(30, self.next_turn) self.timer.run()
class DevBase(object): def __init__(self, name, url='0.0.0.0', unit=1, regs_r_address=10000, reg_r_num=0, regs_w_address=0, reg_w_num=0): # device info self.summary = str(name) + ' ' self.regsR = [] self.regsRLast = [] self.regsW = [] # devices registers info self.regsRInter = 1 self.regsWInter = 1 self.unit = unit self.regsRAddress = regs_r_address self.regsRNum = reg_r_num self.regsWAddress = regs_w_address self.regsWNum = reg_w_num # data sharing info # self.filePath = inspect.getfile(inspect.currentframe()) + str(name) + '.dat' self.filePath = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) + '/' + str( name) + '.dat' self.file = '' self.normalizeLen = 32 self.create_data_file() self.mmapData = mmap.mmap(self.file.fileno(), 0) # devices address info self.url = url self.modbusClient = ModbusTcpClient(self.url) self.readingTimer = Timer(self.regsRInter, self.__read_regs__) self.writingTimer = Timer(self.regsWInter, self.__send_regs__) # for internal using self.regs_r_pos = 0 self.regs_w_pos = self.regs_r_pos + self.regsRNum * self.normalizeLen + 1 # skip the first line and symbol of newline def create_data_file(self): open(self.filePath, "w+").close() # create an empty file self.file = open(self.filePath, 'r+') for i in range(0, self.regsRNum): self.file.write(self.normalizeLen * '0') self.file.write('\n') # the second line for writing self.file.write('0') # 1 means ready to send regs_w to devices for i in range(0, self.regsWNum): self.file.write(self.normalizeLen * '0') self.file.seek(0) def __normalize_num__(self, src): # numbers to strings target = [] for i, d1 in enumerate(src): d1 = str(d1) if len(d1) < self.normalizeLen: target.append(' ' * (self.normalizeLen - len(d1)) + str(d1)) elif len(d1) == self.normalizeLen: target.append(str(d1)) else: print('item: \"', d1, '\" index: \"', i, '\" too long...') target.append(d1[:self.normalizeLen]) return target def compare_regs_r_last(self): for i, j in zip(self.regsR, self.regsRLast): if i != j: return False return True def __write_regs_to_mmap__(self): data = self.__normalize_num__(self.regsR) print(data) for i in range(0, self.regsRNum - 1): self.mmapData[i * self.normalizeLen:(i + 1) * self.normalizeLen] = bytes(data[i], 'utf8') def __read_regs__(self): # print 'reading...' try: res = self.modbusClient.read_holding_registers(address=self.regsRAddress, count=self.regsRNum, unit=self.unit) self.regsR = res.registers print('read registers: \t', self.regsR) if self.compare_regs_r_last(): # write to mmap only the data is different with last time pass else: self.regsRLast = self.regsR self.__write_regs_to_mmap__() regs_r_changed() except pymodbus.exceptions.ConnectionException: print('Communication failed ...') finally: self.readingTimer.run() if len(self.regsR) == self.regsRNum: print('Reading success...') def __send_regs__(self): self.regsW = [] print(self.mmapData.readline()) for i in range(0, self.regsWNum): d1_begin = self.regs_w_pos + i * self.normalizeLen d1_end = self.regs_w_pos + (i + 1) * self.normalizeLen d1 = str(self.mmapData[d1_begin:d1_end]) d1 = d1.strip() self.regsW.append(int(d1)) print(self.regsW) try: res = self.modbusClient.write_registers(address=self.regsWAddress, values=self.regsW, unit=self.unit) print('write registers: \t', self.regsW, 'result: ', res) self.__write_regs_to_mmap__() except pymodbus.exceptions.ConnectionException: print('Communication failed ... ') except pymodbus.exceptions.IndexError: print('Writing failed ... ', sys.exc_info()) finally: self.writingTimer.run() def __check_net_OK__(self): import subprocess res = subprocess.call("ping -c 1 %s" % self.url, shell=True, stdout=open('/dev/null', 'w'), stderr=subprocess.STDOUT) if res == 0: return True else: return False def start_data_server(self): print('starting update data ... \n', time.ctime()) if self.__check_net_OK__(): self.readingTimer.start() self.writingTimer.start() else: print('Can not access', self.url) def stop_data_server(self): print('stopping update data ... \n', time.ctime()) self.readingTimer.cancel() self.writingTimer.cancel()
def run(self): Timer.run(self)
class TicketService: def __init__(self): self.venue = Venue(4, 5) self.seats_being_held_dictionary = {} self.reserved_seats = {} self.hold_time = 120 self.hold_check_polling_timer = Timer(2, self.check_hold) self.schedule_check_hold() def num_seats_available(self): return self.venue.total_seats_available() def find_and_hold_a_seat(self, seat_name, email): seat = self.venue.find_and_hold_seats(seat_name, email) if seat is not None: if email in self.seats_being_held_dictionary: self.seats_being_held_dictionary[email].append(SeatHold(seat)) def find_and_hold_seats(self, num_seats, customer_email): if num_seats <= self.num_seats_available(): seats_being_held = [] venue_iterator = iter(self.venue) counter = 0 while counter < num_seats: seat = next(venue_iterator) if seat.is_available(): self.venue.hold_a_seat(seat) seats_being_held.append(SeatHold(seat)) counter = counter + 1 self.seats_being_held_dictionary[customer_email] = seats_being_held def generate_unique_confirmation_number(self): confirmation_number = randint(10000, 99999) while confirmation_number in self.reserved_seats: confirmation_number = randint(10000, 99999) return confirmation_number def reserve_seat(self, email): if email in list(self.seats_being_held_dictionary): reserved_seats = [] for seat_hold in self.seats_being_held_dictionary[email][:]: seat = seat_hold.seat seat.reserve_seat(email) reserved_seats.append(seat) confirmation_number = self.generate_unique_confirmation_number() print("your confirmation number is: " + str(confirmation_number)) self.reserved_seats[confirmation_number] = Reservation( email, reserved_seats) self.seats_being_held_dictionary.pop(email) def check_hold(self): for email in list(self.seats_being_held_dictionary): seats_being_held = self.seats_being_held_dictionary[email] for seat_hold in seats_being_held[:]: # for i in range(len(seats_being_held)): if (time.time() - seat_hold.timer) >= self.hold_time: self.venue.make_seat_available(seat_hold.seat) seats_being_held.remove(seat_hold) if len(seats_being_held) is 0: self.seats_being_held_dictionary.pop(email) self.hold_check_polling_timer.run() def schedule_check_hold(self): self.hold_check_polling_timer.start() def stop_checking_holds(self): self.hold_check_polling_timer.cancel() def display_venue(self): self.venue.display_venue() def display_reservation(self, confirmation_number): confirmation_number = int(confirmation_number) if confirmation_number in self.reserved_seats: reservation = self.reserved_seats[confirmation_number] for seat in reservation.seats: print(seat) else: print("Invalid confirmation number") def display_hold(self, email): if email in self.seats_being_held_dictionary: seat_holds = self.seats_being_held_dictionary[email] for seat_hold in seat_holds: print( str(seat_hold.seat) + " is being held for " + str(self.hold_time - (time.time() - seat_hold.timer)) + " more seconds") else: print("Email address was not found")