def check_command(audio): global source if audio.lower() in welcoming_q: speak(random.choice(welcoming_a)) elif audio in thanks_q: # Raise if say thanks speak(random.choice(thanks_a)) elif audio in who_q: # Raise when identity ask speak(random.choice(who_a)) elif audio in goodness_q: speak(random.choice(goodness_a)) elif audio.lower() in quit_q: # Raise when i want to close the program speak(random.choice(quit_a)) raise SystemExit(0) elif audio.lower() in search_q: # Raise when i want to search something speak(random.choice(search_a)) search() elif audio in video_q: speak(random.choice(video_a)) get_video() elif audio in alarm_q: speak(random.choice(alarm_a)) alarm(sr.Microphone()) elif audio in currency_q: speak(random.choice(currency_a)) get_currency() elif audio in email_q: speak(random.choice(email_a)) get_mail_info()
def test_generate_playlist(self): '''based on the path, generate a list of files''' alarm1 = alarm.alarm(**alarms_list[1]) path = alarm.alarm(**alarms_list[6]) self.assertEqual(alarm1.generate_playlist(), root_playlist) self.assertEqual(path.generate_playlist(), path_playlist)
def alarm_t(): while 1: try: ring.wait(None) alarm.alarm(3) except Exception as e: print(e)
def uploadFile(fileHash, fileContent, username, backend, fileName): '''Uploads a file to the dropbox for online. ''' logging.debug('dropBox::uploadFile(%s, %s [len], %s, %s, %s)', fileHash, len(fileContent), username, backend, fileName) logging.info('uploadFile(): Checking whether the hash is valid...') checkHash(fileHash) logging.info('uploadFile(): %s: Checking the file content hash...', fileHash) fileContentHash = getHash(fileContent) if fileHash != fileContentHash: raise DropBoxError('The given file hash %s does not match with the file content hash %s.' % (fileHash, fileContentHash)) logging.info('uploadFile(): %s: Checking whether the file already exists...', fileHash) state = dataAccess.getFileState(fileHash) if state == 'Uploaded': raise DropBoxError('The uploaded file with hash %s already exists in the Uploaded files (i.e. not yet processed). This probably means that you sent the same request twice in a short time.' % fileHash) if state == 'Pending': raise DropBoxError('The uploaded file with hash %s already exists in the Pending files (i.e. files that are waiting to be pulled by online that were already checked). This probably means that you sent the same request twice in a short time.' % fileHash) if state == 'Acknowledged': raise DropBoxError('The uploaded file with hash %s already exists in the Acknowledged files (i.e. files that were already pulled by online not too long ago -- we do not keep all of them forever). This probably means that you sent the same request twice after some time.' % fileHash) if state == 'Bad': raise DropBoxError('The uploaded file with hash %s already exists in the Bad files (i.e. files that were wrong for some reason). Therefore this file will be skipped since the results of the checks should be the same again (i.e. wrong).' % fileHash) logging.info('uploadFile(): %s: Saving the uploaded file in the database...', fileHash) dataAccess.insertFile(fileHash, 'Uploaded', backend, username, fileName, fileContent) logging.info('uploadFile(): %s: Checking the contents of the file...', fileHash) try: metadata = check.checkFile(fileHash, fileContent, backend) except DropBoxError as e: failUpload(fileHash) raise e except Exception as e: # Other kind of exception: this is a bug :( alarm.alarm('Non-DropBoxError exception raised in check.py: %s' % e) failUpload(fileHash) raise DropBoxError('Oops, something went wrong while checking your file. This is most likely a bug in the DropBox. %s' % config.notifiedErrorMessage) # Divide the metadata in the userText and the real metadata userText = metadata['userText'] metadata['userText'] = '' logging.info('uploadFile(): %s: Inserting entry in the fileLog...', fileHash) try: dataAccess.insertFileLog(fileHash, Constants.WAITING_FOR_START, dumpJson(metadata), dumpJson(userText)) except cx_Oracle.IntegrityError: failUpload(fileHash) raise DropBoxError('The uploaded file %s was already requested in the database.' % fileHash) logging.info('uploadFile(): %s: Updating state of the file to Pending...', fileHash) dataAccess.updateFileState(fileHash, 'Pending') logging.info('uploadFile(): %s: The upload was successful.', fileHash)
def pic_verify(self): succ, msg = validate_pic(self.pic) if succ is False: alarm(ALARM_LEVEL.CRITICAL, ALM_POSTER_IMAGE_GONE, "picture of url{url} cannot be loaded, err({err_msg})\n" "\nlocation: \n{location}".\ format(url=self.pic, err_msg=msg, location=settings.show_exam_stack())) return False return True
def recognition(im): """ @param im the sudoku grid picture @return grille an array with the sudoku grid digits @brief Fonction principale de la reconnaissance des chiffres Réalise une reconnaissance de la grille selon les 4 orientations possibles, puis détermine l'orientation donnant le meilleur résultat (en se basant sur la distance moyenne entre plus proche voisins). La grille correspondant à cette orientation sera la grille à résoudre. """ angles = [0, 90, 180, 270] distance_moyenne = 0.0 grille = [] angleOpt = 0 for angle in angles: sudoku, distance, zero = single_recognition(im, 9, angle) print("> Orientation", angle, "° : distance moyenne entre plus poches voisins :", distance) #Recherche de la distance moyenne minimale. La condition (distance == 0) validée signifie que la reconnaissance n'a pas fonctionné et/ou que la grille est invalide. if (distance < distance_moyenne or distance_moyenne == 0) and (distance != 0): grille = sudoku distance_moyenne = distance angleOpt = angle iszero = zero print(grille) print("Angle Valentin : ", angleOpt) #Si cette condition n'est pas satisfaite, cela signifie qu'il y a très probablement deux coefficients sur la même ligne, colonne ou bloc. try: assert ( len(grille) != 0 ), "La grille reconnue ne semble pas respecter les règles du sudoku" except: print("Veuillez réessayer") alarm() #A ce stade, la grille optimale est choisie. Il reste à savoir si elle contient des zéros. Si tel est le cas, la grille ne doit pas être envoyée à l'algorithme de résolution... try: assert ( iszero == False ), "Un zéro a été détecté dans la grille. Veuillez changer les conditions d'éclairage ou d'inclinaison" except: print("Veuillez réessayer") alarm() #Remplacement des cases vides (ici, coefficient = 10) par des zéros. Ces coefficients 10 étaient précédemment nécessaires pour assurer la vérification de la grille. Ainsi, si l'algorithme détecte deux zéros dans la grille (par exemple, si celle-ci est mal tournée), la reconnaissance s'arrête immédiatement (gain de temps). for i in range(0, 9): for j in range(0, 9): if grille[i][j] == 10: grille[i][j] = 0 return (grille, angleOpt)
def self_verify_basic(self): om_output("Basic verify the Facet %s" % self._short()) settings.exam_stack_push(self) if not self.pic_verify(): settings.exam_stack_pop() return False api = api_module.api_mapping[self.typecode] if self.typecode not in api_module.module_mapping: om_err_output( "Facet::self_verify_basic() no api module defined for " "typecode %s" % self.typecode) settings.exam_stack_pop() return False # get class type related to the typecode cl = api_module.module_mapping[self.typecode] m = cl(self.id) if not m.valid(): om_err_output("apimodule is not valid for typecode %s" % self.typecode) settings.exam_stack_pop() return False if not m.verify_basic(): for ecode, emsgs in m.last_err.items(): om_err_output("fail to basic verify %s" % (self._short())) alarm_msg = "" for m in emsgs: om_err_output("meet error %s, %s" % (ecode, m)) alarm_msg += m + "\n" alm = None # check every error code for the api module, and send related # alarm according to the severity level alarm_msg += "\nlocation:\n%s" % settings.show_exam_stack() if ecode == ErrCode.RESOURCE_CANT_ACCESS: alarm(ALARM_LEVEL.CRITICAL, ALM_NETWORK_ISSUE, alarm_msg) elif ecode == ErrCode.RESOURCE_OFFLINE: alarm(ALARM_LEVEL.CRITICAL, ALM_MEDIA_OFFLINE, alarm_msg) elif ecode == ErrCode.DATA_INVALID: alarm(ALARM_LEVEL.HIGH, ALM_MEDIA_DATA_INVALID, alarm_msg) elif ecode == ErrCode.BAD_LIST_VIEW_MEDIA or \ ecode == ErrCode.BAD_LIST_VIEW_IMAGE: alarm(ALARM_LEVEL.HIGH, ALM_CATEGORY_HAS_BAD_MEDIAS, alarm_msg) else: alarm(ALARM_LEVEL.NORMAL, ALM_BASIC, alarm_msg) settings.exam_stack_pop() return False settings.exam_stack_pop() return True
def self_verify_basic(self): om_output("Basic verify the Facet %s"%self._short()) settings.exam_stack_push(self) if not self.pic_verify(): settings.exam_stack_pop() return False api = api_module.api_mapping[self.typecode] if self.typecode not in api_module.module_mapping: om_err_output("Facet::self_verify_basic() no api module defined for " "typecode %s"%self.typecode) settings.exam_stack_pop() #return False # currently the not support api module need not return fail return True # get class type related to the typecode cl = api_module.module_mapping[self.typecode] m = cl(self.id) if not m.valid(): om_err_output("apimodule is not valid for typecode %s"%self.typecode) settings.exam_stack_pop() return False if not m.verify_basic(): for ecode, emsgs in m.last_err.items(): om_err_output("fail to basic verify %s"%(self._short())) alarm_msg = "" for m in emsgs: om_err_output("meet error %s, %s"%(ecode, m)) alarm_msg += m + "\n" alm = None # check every error code for the api module, and send related # alarm according to the severity level alarm_msg += "\nlocation:\n%s"%settings.show_exam_stack() if ecode == ErrCode.RESOURCE_CANT_ACCESS: alarm(ALARM_LEVEL.CRITICAL, ALM_NETWORK_ISSUE, alarm_msg) elif ecode == ErrCode.RESOURCE_OFFLINE: alarm(ALARM_LEVEL.CRITICAL, ALM_MEDIA_OFFLINE, alarm_msg) elif ecode == ErrCode.DATA_INVALID: alarm(ALARM_LEVEL.HIGH, ALM_MEDIA_DATA_INVALID, alarm_msg) elif ecode == ErrCode.BAD_LIST_VIEW_MEDIA or \ ecode == ErrCode.BAD_LIST_VIEW_IMAGE: alarm(ALARM_LEVEL.HIGH, ALM_CATEGORY_HAS_BAD_MEDIAS, alarm_msg) else: alarm(ALARM_LEVEL.NORMAL, ALM_BASIC, alarm_msg) settings.exam_stack_pop() return False settings.exam_stack_pop() return True
def __init__(self, argv, map=None, timeout=None, close_when_done=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, preexec_fn=None, bufsize=0, **popen_keyw): """Accepts all the same arguments and keywords as `subprocess.Popen`. Input or outputs specified as `PIPE` (now the default) for are wrapped in an asynchronous pipe dispatcher. The timeout is used to create an alarm, which can be cancelled by calling `cancel_timeout()`, `communicate()`, `wait()` or `kill()`. """ Observable.__init__(self) self._map = map # Create the subprocess itself, wrapping preexec_fn in the clear_signals call Popen.__init__(self, argv, preexec_fn=lambda: self.clear_signals(preexec_fn), stdin=stdin, stdout=stdout, stderr=stderr, **popen_keyw) # Set the timeout on the subprocess. If it fails, ignore the failure. try: fto = float(timeout) self._alarmobj = alarm.alarm(fto, self.kill) if fto > 0 else None except: self._alarmobj = None # Wrap the pipe I/O. Sets the Popen and pipe buffer sizes the same; perhaps not optimal. if stdout == PIPE: self.stdout = OutputPipeDispatcher(self.stdout, map=map, ignore_broken_pipe=True, universal_newlines=self.universal_newlines, maxdata=bufsize) self.stdout.obs_add(self._pipe_event) if stderr == PIPE: self.stderr = OutputPipeDispatcher(self.stderr, map=map, ignore_broken_pipe=True, universal_newlines=self.universal_newlines, maxdata=bufsize) self.stderr.obs_add(self._pipe_event) if stdin == PIPE: self.stdin = InputPipeDispatcher(self.stdin, map=map, ignore_broken_pipe=True, close_when_done=close_when_done, maxdata=bufsize) self.stdin.obs_add(self._pipe_event)
def showAlarm(self): self.rightSideInfo.close() self.rightSideInfo = alarm.alarm(self, self.studId) # clientSocket이랑 학번이 필요함 self.rightSideInfo.setMinimumSize(300, 500) self.rightSideLayout.addWidget(self.rightSideInfo)
def test_add_alarm_correct_alarms(self): '''create a set of alarms''' alarms = alarm.alarmset() for a in alarms_list: alarms.add(alarm.alarm(**a)) al = alarms[-1] self.are_all_the_vars_present(al, default, **a) self.assertEqual(alarms.exists(a['name']), True)
def __init__(self, argv, map=None, timeout=None, close_when_done=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, preexec_fn=None, bufsize=0, **popen_keyw): """Accepts all the same arguments and keywords as `subprocess.Popen`. Input or outputs specified as `PIPE` (now the default) for are wrapped in an asynchronous pipe dispatcher. The timeout is used to create an alarm, which can be cancelled by calling `cancel_timeout()`, `communicate()`, `wait()` or `kill()`. """ Observable.__init__(self) self._map = map # Create the subprocess itself, wrapping preexec_fn in the clear_signals call Popen.__init__(self, argv, preexec_fn=lambda: self.clear_signals(preexec_fn), stdin=stdin, stdout=stdout, stderr=stderr, **popen_keyw) # Set the timeout on the subprocess. If it fails, ignore the failure. try: fto = float(timeout) self._alarmobj = alarm.alarm(fto, self.kill) if fto > 0 else None except: self._alarmobj = None # Wrap the pipe I/O. Sets the Popen and pipe buffer sizes the same; perhaps not optimal. if stdout == PIPE: self.stdout = OutputPipeDispatcher( self.stdout, map=map, ignore_broken_pipe=True, universal_newlines=self.universal_newlines, maxdata=bufsize) self.stdout.obs_add(self._pipe_event) if stderr == PIPE: self.stderr = OutputPipeDispatcher( self.stderr, map=map, ignore_broken_pipe=True, universal_newlines=self.universal_newlines, maxdata=bufsize) self.stderr.obs_add(self._pipe_event) if stdin == PIPE: self.stdin = InputPipeDispatcher(self.stdin, map=map, ignore_broken_pipe=True, close_when_done=close_when_done, maxdata=bufsize) self.stdin.obs_add(self._pipe_event)
def test_remove_alarm(self): '''remove an alarm from a set''' alarms = alarm.alarmset() for a in alarms_list: name = a['name'] alarms.add(alarm.alarm(**a)) self.assertEqual(alarms.exists(name), True) alarms.remove(alarms[name]) self.assertEqual(alarms.exists(name), False)
def test_play_a_song(self): '''play a song form file''' alarm1 = alarm.alarm(**alarms_list[1]) self.assertEqual(alarm1.playing, False) self.assertEqual(alarm1.blocking, False) self.assertEqual(alarm1.player_active(), False) alarm1.play(root_playlist[0]) time.sleep(0.2) self.assertEqual(alarm1.playing, True) self.assertEqual(alarm1.blocking, False) self.assertEqual(alarm1.player_active(), True) alarm1.stop()
def test_edit_alarm_correct(self): '''update an alarm with the parameters of another alarm''' if len(alarms_list) < 2: # need at least 2 alarms for this test return for i in range(len(alarms_list)-1): a1 = alarms_list[i] a2 = alarms_list[i+1] al = alarm.alarm(**a1) copy_of_default = default.copy() self.are_all_the_vars_present(al, copy_of_default, **a1) al.update_alarm(**a2) copy_of_default.update(a1) self.are_all_the_vars_present(al, copy_of_default, **a2)
def data_initialize(): om_output("start to initialize frontpage data") retry_times_left = 3 while retry_times_left > 0: frontpage_data = get_frontpage_data() if frontpage_data is not None and len(frontpage_data) > 0: break retry_times_left -= 1 if retry_times_left <= 0: alarm( ALARM_LEVEL.CRITICAL, "NETWORK_ISSUE", "cannot get frontpage " "data after several reties, url(%s) is not accessable" % settings.VOD_FRONTPAGE_URL) exit(-1) try: frontj = json.loads(frontpage_data) except: om_fatal_output("frontpage data can not be jsonlized, exit now") exit(-1) if 'apiMapping' not in frontj: om_fatal_output( "no apiMapping information in frontpage data, exit now") exit(-1) parse_api_mapping(frontj['apiMapping']) if 'masterViews' not in frontj: om_fatal_output( "no apiMapping information in masterViews data, exit now") exit(-1) for v in frontj['masterViews']: view = parse_view(v) if view is None: return False settings.master_views.append(view) return True
def test_save_and_load_alarms(self): alarms_1 = alarm.alarmset() alarms_2 = alarm.alarmset() for a in alarms_list: alarms_1.add(alarm.alarm(**a)) alarms_1.save_alarms('test_config.file') alarms_2.load_alarms('test_config.file') for a_1, a_2 in zip (alarms_1, alarms_2): self.assertEqual(a_1.name, a_2.name) self.assertEqual(a_1.time, a_2.time) self.assertEqual(a_1.date, a_2.date) self.assertEqual(a_1.days, a_2.days) self.assertEqual(a_1.path, a_2.path) self.assertEqual(a_1.active, a_2.active)
def getAddress(address): '''Gets an address if the address is not an email but a CERN username: If it contains '@', i.e. an email, leave it like that. If not, it is a CERN username and we use LDAP to get the real email. The advantage of doing the LDAP lookup here is to take out problems with the LDAP server from the normal dropBox workflow to here. ''' if '@' in address: return address try: return cernldap.CERNLDAP().getUserEmail(address) except cernldap.NotFoundError as e: # If there is no user for that account, still send the email # but replace the address with a default one and alarm about the issue, # since it should not happen. # # This makes sense, since this way we do have the original email # to resend it if needed plus the alarm and it does not stop an email # being sent just because one user was not in CERN LDAP. # Unless, of course, the problem was with just the fromAddress # -- in this case we just receive the alarm but the original email # is sent anyway to the users, so should not be a problem either. alarm.alarm('User %s not found in CERN LDAP: %s' % (address, str(e))) return config.defaultAddress except Exception as e: # In other cases, alarm and raise our own exception since we want # to retry to send the email (e.g. we couldn't reach CERN LDAP) later message = 'Impossible to get email from user %s: %s' % (address, str(e)) alarm.alarm(message) raise Exception(message)
def getAddress(address): """Gets an address if the address is not an email but a CERN username: If it contains '@', i.e. an email, leave it like that. If not, it is a CERN username and we use LDAP to get the real email. The advantage of doing the LDAP lookup here is to take out problems with the LDAP server from the normal dropBox workflow to here. """ if "@" in address: return address try: return cernldap.CERNLDAP().getUserEmail(address) except cernldap.NotFoundError as e: # If there is no user for that account, still send the email # but replace the address with a default one and alarm about the issue, # since it should not happen. # # This makes sense, since this way we do have the original email # to resend it if needed plus the alarm and it does not stop an email # being sent just because one user was not in CERN LDAP. # Unless, of course, the problem was with just the fromAddress # -- in this case we just receive the alarm but the original email # is sent anyway to the users, so should not be a problem either. alarm.alarm("User %s not found in CERN LDAP: %s" % (address, str(e))) return config.defaultAddress except Exception as e: # In other cases, alarm and raise our own exception since we want # to retry to send the email (e.g. we couldn't reach CERN LDAP) later message = "Impossible to get email from user %s: %s" % (address, str(e)) alarm.alarm(message) raise Exception(message)
def data_initialize(): om_output("start to initialize frontpage data") retry_times_left = 3 while retry_times_left > 0: frontpage_data = get_frontpage_data() if frontpage_data is not None and len(frontpage_data) > 0: break retry_times_left -= 1 if retry_times_left <= 0: alarm(ALARM_LEVEL.CRITICAL, "NETWORK_ISSUE", "cannot get frontpage " "data after several reties, url(%s) is not accessable" %settings.VOD_FRONTPAGE_URL) exit(-1) try: frontj = json.loads(frontpage_data) except: om_fatal_output("frontpage data can not be jsonlized, exit now") exit(-1) if 'apiMapping' not in frontj: om_fatal_output("no apiMapping information in frontpage data, exit now") exit(-1) parse_api_mapping(frontj['apiMapping']) if 'masterViews' not in frontj: om_fatal_output("no apiMapping information in masterViews data, exit now") exit(-1) for v in frontj['masterViews']: view = parse_view(v) if view is None: return False settings.master_views.append(view) return True
def __init__(self): ''' Initialize required objects ''' # Construct the camera captddure object from camera import camera self.cam = camera() # Using container to store images from container import dataContainer self.imgContainer = dataContainer() # Contruct a alarm object from alarm import alarm self.eventAlarm = alarm() # Construct the image processing strategy from strategy import strategyConstructor self.strategyConstruction = strategyConstructor(self.eventAlarm) # check if X11 DISPLAY exist self._isgui = self._checkGUI()
def test_is_the_next_alarm_correct(self): '''test next_alarm''' for a in alarms_list: myalarm = alarm.alarm(**a) nexttime = alarm_times[myalarm.name] self.assertEqual(myalarm.next_alarm(current_time), nexttime)
# coding=utf-8 import requests from aliyunsdkcore.client import AcsClient from aliyunsdkcore.request import CommonRequest from inquire import icbcInquire, cmbInquire from alarm import alarm if __name__ == "__main__": alarm(cmbInquire())
def test_create_alarm(self): '''create a basic alarm''' for a in alarms_list: al = alarm.alarm(**a) self.are_all_the_vars_present(al, default, **a)
import time from utils import get_file_to_read_from, calculate_sleep_time from task import read_tasks, print_tasks from alarm import alarm, find_next_alarm_time fileToRead = "" # TODO add better error and exception handling fileToRead = get_file_to_read_from("../data/currentActiveTaskListDir.txt") tasks = read_tasks(fileToRead) print_tasks(tasks) while True: sleep_time = calculate_sleep_time(find_next_alarm_time(tasks)) print(sleep_time/60) time.sleep(sleep_time) alarm("sonar.ogg", 15)
def wake_time(): t = clock.nexttime(time(7,15)) if t.weekday() in (5, 6): t+= timedelta(hours=1) return t.time() ede = location(lat=52.053055, lon=5.638889) bri_cycle = find_next_change(brightness_cycle(wake_time, bed_time, sinus(charge(BRI_SINUS_CHARGE)))) ct_cycle = find_next_change(ede.ct_cycle(wake_time, bed_time)) def process_events(lights, events, attr): while True: t, v = events.next() print "Next %s event at:" % attr, t yield t print " setting %s:" % attr, v for light in lights: light.send(**{attr:v}) alarm( turn_on_between((light_studeer, tap_keuken), wake_time, ede.dawn_end), #TODO remove woonkamer turn_on_between(lights_all, ede.dusk_begin, bed_time), process_events(lights_all, bri_cycle, 'bri'), process_events(lights_all, ct_cycle, 'ct') ) while True: sleep(10)
def read_input(speech_input): def if_match(cons): split = speech_input.split() if set(cons).issubset(set(split)): return True else: return False if if_match(["представи", "се"]): conversations.introduction() elif if_match(["кой", "си", "ти"]): conversations.introduction() elif if_match(["здрасти"]) or if_match(["здравей"]): conversations.hello_rep() elif if_match(["мерси"]) or if_match(["благодаря"]): conversations.thanks() elif if_match(["какво", "е"]): writeOnLCD("Wikipedia") wikipedia_check.search_in_wiki(speech_input) elif if_match(["какво", "можеш", "да", "правиш"]): conversations.i_can() elif if_match(["колко", "е", "температурата"]): conversations.temperature() elif if_match(["кажи", "температурата", "в"]) or if_match( ["температурата", "в"]): weather.give_me_the_weather(speech_input) elif if_match(["дай", "прогнозата", "за"]): weather.give_me_the_weather(speech_input) elif if_match(["музика", "ютуб"]): writeOnLCD("Playing music from YT") youtube_music.play() elif if_match(['направи', 'аларма', 'за']): print("Това е демо за аларма.") talk("Това е демо за аларма.") alarm.alarm() elif if_match(["пусни", "музика"]): print("Търся песни!") writeOnLCD("Music () ) )") talk("Търся песни!") music.player(".") elif if_match(["спри", "се"]): talk("Дочуване") sys.exit() else: writeOnLCD(":(") conversations.problem() lcd.clear()
def test_the_next_alarm_in_set(self): '''alarmset next_alarm''' alarms = alarm.alarmset() for a in alarms_list: alarms.add(alarm.alarm(**a)) self.assertEqual(alarms.next_alarm(current_time).next_alarm(current_time), current_time)
# 登陆成功 start_time = datetime.datetime.now() while True: # 开始循环查询 last_time = (datetime.datetime.now() - start_time).seconds logger.info("********************* 上轮用时%d秒 *********************", last_time) start_time = datetime.datetime.now() num = num + 1 logger.info("********************* 开始第%d遍查询 *********************", num) try: if num != 1 and last_time == 0: try: browser.find_element(By.CSS_SELECTOR, "#rightRange > #dialog .btn").click() browser.find_element(By.ID, "btnBackToSearch").click() time.sleep(1) except Exception as e: continue if inquiry_april_ukvi(browser): # 查询4月份UKVI是否开放 alarm("4UKVIOK") # if inquiry_april_remain(browser): # 4月份普通雅思考试考位预警 # alarm("4月份普通雅思考位剩余不多") # if inquiry_april_ukvi(browser): # 4月份雅思捡漏 # alarm("4月份普通雅思考位有剩余") except Exception as e: logger.error(e.args) continue time.sleep(5) browser.find_element_by_xpath("//*[text()='我的主页']").click() # 返回主页 time.sleep(5)
def __init__(self): """ initiates a new manager object """ self.alarm_device = alarm.alarm() self.camera_device = camera.camera()
def call_monitor(): # firstly check the static frontpage data start_ts = int(time.time() * 1000) data = get_frontpage_data() if data is None: alarm(ALARM_LEVEL.CRITICAL, ALM_NETWORK_ISSUE, "static frontpage load fail") return False end_ts = int(time.time() * 1000) delta = end_ts - start_ts if delta > STATIC_FRONTPAGE_THRESHOLD_lvl2: alarm(ALARM_LEVEL.CRITICAL, ALM_NETWORK_SLOW, "static frontpage load consume too much time %s(threshold %s)" %(delta, STATIC_FRONTPAGE_THRESHOLD_lvl2)) elif delta > STATIC_FRONTPAGE_THRESHOLD_lvl1: alarm(ALARM_LEVEL.HIGH, ALM_NETWORK_SLOW, "static frontpage load consume too much time %s(threshold %s)" %(delta, STATIC_FRONTPAGE_THRESHOLD_lvl1)) jdata = json.loads(data) settings.re_num = int(jdata['re_num']) settings.model_id = jdata['model_id'] # secondly check the recom frontpage data start_ts = int(time.time() * 1000) data = get_recom_data() if data == None: alarm(ALARM_LEVEL.CRITICAL, ALM_NETWORK_ISSUE, "recom frontpage load fail") return False end_ts = int(time.time() * 1000) delta = end_ts - start_ts if delta > RECOM_FRONTPAGE_THRESHOLD_lvl2: alarm(ALARM_LEVEL.CRITICAL, ALM_NETWORK_SLOW, "recom frontpage load consume too much time %s(threshold %s)" %(delta, RECOM_FRONTPAGE_THRESHOLD_lvl2)) elif delta > RECOM_FRONTPAGE_THRESHOLD_lvl1: alarm(ALARM_LEVEL.HIGH, ALM_NETWORK_SLOW, "recom frontpage load consume too much time %s(threshold %s)" %(delta, RECOM_FRONTPAGE_THRESHOLD_lvl1)) return True
import MySQLdb as mdb import smtplib import re import getpass print getpass.getuser() parser = argparse.ArgumentParser(description=""""Send an email indicating the alarm will be silenced given freezer id and alarm level""") parser.add_argument("-f", "--freezerid", type=int) parser.add_argument("-a", "--alarmlevel", type=int) args = parser.parse_args() freezer = args.freezerid alarmLevel = args.alarmlevel changeAlarm = alarm() # Get necessary information from database readQuery = ( "select freezer_alarm_ID, freezer_setpoint1, freezer_setpoint2, freezer_location, freezer_name, freezer_description, freezer_send_alarm from freezers where freezer_id = %s" ) changeAlarm.readcursor.execute(readQuery, (freezer)) alarmIDData = changeAlarm.readcursor.fetchall() freezerAlarmID = alarmIDData[0][0] setpoint1 = float(alarmIDData[0][1]) setpoint2 = float(alarmIDData[0][2]) location = alarmIDData[0][3] name = alarmIDData[0][4] description = alarmIDData[0][5] # Send Alarm = 0 it will not sound an alarm
p_pool.append(l_server) if oracle_servers: for i in xrange(len(oracle_servers)): o_server = Process( target=check_oracle, args=(oracle_servers[i][0], oracle_servers[i][1], oracle_servers[i][2], oracle_servers[i][3], oracle_servers[i][4], oracle_servers[i][5], oracle_servers[i][6], oracle_servers[i][7])) o_server.start() my_log.logger.info('%s 开始采集oracle数据库信息' % oracle_servers[i][0]) p_pool.append(o_server) if mysql_servers: for i in xrange(len(mysql_servers)): m_server = Process( target=check_mysql, args=(mysql_servers[i][0], mysql_servers[i][1], mysql_servers[i][2], mysql_servers[i][3], mysql_servers[i][4])) m_server.start() my_log.logger.info('%s 开始采集mysql数据库信息' % mysql_servers[i][0]) p_pool.append(m_server) for each_server in p_pool: each_server.join() # 告警 alarm.alarm() my_log.logger.info('%s 秒后开始下一次轮询' % check_sleep_time) time.sleep(check_sleep_time)
import alarm from signal import pause from time import sleep alarm.alarm(10) #while 1: pass #pause() sleep(5) 100L**100**100
chart_status_t = pi_sys.start_thread( chart_d.online_chart_mode, (error_q, oline_command_entry_q), 'online_chart_status_Thread') try: #初始模式和词典,开机默认为系统设置模式 current_run_mode = running_mode_dict['system_mode'] current_dict_no = SYN7318_dict['system'] #创建各个对象实例 chart_d = chart.dialogue(current_dict_no) pi_sys = pi_system.pi_system() mp3 = MP3_player.player(current_dict_no, 'song') pi_alarm = alarm(current_dict_no, alarm_q) syn7318_handle = SYN7318_handles(SYN7318_cb, syn7318_q) # 打开各处理线程 receive_status_t = pi_sys.start_thread(syn7318_handle.receive_status, error_q, 'receive_status_Thread') song_status_t = pi_sys.start_thread(mp3.play_mp3, error_q, 'MP3_status_Thread') email_status_t = pi_sys.start_thread(pi_email.receive_email_t, error_q, 'email_status_Thread') alarm_status_t = pi_sys.start_thread(pi_alarm.alarm_handle, error_q, 'alarm_status_Thread') online_chart_status_t = pi_sys.start_thread( chart_d.online_chart_mode, (error_q, oline_command_entry_q), 'online_chart_status_Thread')
def run(self): touchQ = mp.Queue() touchT = mp.Process(target=self.touch, args=(touchQ, )) touchT.start() tq = mp.Queue() tk = timekeeper(tq) tk.start() sq = mp.Queue() sp = separator(sq) sp.start() dq = mp.Queue() cd = calendar(dq) cd.start() aq = mp.Queue() al = alarm(aq) al.start() current = "Starting" currentSep = "" currentDate = "Aquiring calendar data" currentAlarm = "" #lastTime = "" while 1: self.clock.tick(100) newTouch = None try: newTouch = touchQ.get_nowait() except mp.queues.Empty: pass if (newTouch): print(newTouch) newTime = None try: newTime = tq.get_nowait() except mp.queues.Empty: pass if (newTime): current = newTime newSep = None try: newSep = sq.get_nowait() except mp.queues.Empty: pass if (newSep): currentSep = newSep newDate = None try: newDate = dq.get_nowait() except mp.queues.Empty: pass if (newDate): currentDate = newDate newAlarm = None try: newAlarm = aq.get_nowait() except mp.queues.Empty: pass if (newAlarm): currentAlarm = newAlarm #if(lastTime != current) : if (newTime or newSep or newDate or newAlarm): if (currentAlarm == "alarm"): color = self.a_color s_color = self.a_s_color else: color = self.default_color s_color = self.default_s_color time_surface = self.font.render(current, True, color) time_surface_shadow = self.font.render(current, True, s_color) colon_surface = self.font.render(currentSep, True, color) colon_surface_shadow = self.font.render( currentSep, True, s_color) #tz_surface = self.font.render(tz, True, color) date_surface = self.dateFont.render(currentDate, True, color) date_surface_shadow = self.dateFont.render( currentDate, True, s_color) self.screen.scr.fill(self.b_color) self.screen.scr.blit(time_surface_shadow, (8, 26)) self.screen.scr.blit(time_surface, (2, 22)) self.screen.scr.blit(colon_surface_shadow, (227, 26)) self.screen.scr.blit(colon_surface, (223, 22)) #self.screen.scr.blit(tz_surface, (120, 196)) #self.screen.scr.blit(tz_surface, (120, 196)) self.screen.scr.blit(date_surface_shadow, (12, 12)) self.screen.scr.blit(date_surface, (10, 10)) #lastTime = current pygame.display.update()
#project: LinkedList #author: Rick Anderson from alarm import alarm alarm = alarm()
%(delta, RECOM_FRONTPAGE_THRESHOLD_lvl1)) return True def set_alarm_configration(): # set the alarm file alarm_file = "%s_%s.alm"%(os.path.splitext(sys.argv[0])[0], settings.VENDER) os.environ['alarm_file'] = alarm_file # if the file already exit, just clear it if os.path.exists(alarm_file): os.remove(alarm_file) if __name__ == "__main__": handle_argv() set_alarm_configration() while True: start_ts = int(time.time() * 1000) succ = call_monitor() if succ is False: continue end_ts = int(time.time() * 1000) delta = end_ts - start_ts if delta > TOTAL_FRONTPAGE_THRESHOLD_lvl2 : alarm(ALARM_LEVEL.CRITICAL, ALM_NETWORK_SLOW, "total frontpage load consume too much time %s(threshold %s)" %(delta, TOTAL_FRONTPAGE_THRESHOLD_lvl2)) elif delta > TOTAL_FRONTPAGE_THRESHOLD_lvl1: alarm(ALARM_LEVEL.HIGH, ALM_NETWORK_SLOW, "total frontpage load consume too much time %s(threshold %s)" %(delta, TOTAL_FRONTPAGE_THRESHOLD_lvl1)) time.sleep(2)
elif "read me" in query: speak("Reading myself") file = open("bio.txt", "r") speak(file.read()) elif "where is" in query: query = query.replace("where is", "") location = query speak("User asked to Locate") speak(location) webbrowser.open("https://www.google.co.in/maps/place/"+location+"") break elif 'alarm' in query: alarm.alarm(query) elif 'message' in query: try: speak("Tell me the number") no=input('>>>') speak("tell me the message") txt=takeCommand().lower() speak("Tell me the time") tm=takeCommand().lower() a=datefinder.find_dates(tm)#a is a object for x in a: pass strA=str(x) timeA=strA[11:]
def parse_api_string(parameters): error_returnstring = ''' format for parameters is alarm_id=<name> action=stop|play|add|delete|update|list|info|exists|gen_name|wakeup_light eg <url>/alarm_id=alarm1&action=info aditional parameters for the action update time=hh:mm name=<name> -> updating name will update alarm_id. It must be unique days=MO,TU,WE,TH,FR,SA,SU -> one or more of the previous, comma seperated volume=[0..100] -> the volume setting of the alarm (100 is max) color=rrggbb -> where rrggbb is the hexcolorcode for the color color_onset=<secs> -> seconds before the daylight effect starts date=YYYY-MM-DD active=true|false repeating=true|false ''' print (parameters) response = "" params = {} web_response = "nothing" try: params = dict(a.split('=') for a in parameters.split('&')) action = params['action'].lower() except: return error_returnstring if 'alarm_id'in params: name = params['alarm_id'] id_present = 'alarm_id' in params and alarms.exists(params['alarm_id']) if action == 'stop': response +='stopping all playing alarms' alarms.stop() elif action == 'add' and 'alarm_id' in params: response +='adding alarm '+ name time = datetime.datetime.now() alarms.add(alarm.alarm(name, time, active = False)) response += name +' at ' + time.strftime(format) web_response = render_alarm(alarms[name]) elif action == 'play' and id_present: play_button_pressed(name) response += 'playing '+ name +' '+ alarms[name].track elif action == 'delete' and id_present: delete_alarm_web(name) elif action == 'update' and id_present: if 'name' in params: newName = params['name'] else: newName = params['alarm_id'] update_alarm_web(params) response += 'updated ' + name response += ' new id =' + newName web_response = render_alarm(alarms[newName]) elif action == 'update_time': response += 'updating_time' web_response = render_topbar(alarms) elif action == 'list': response += 'listing alarms' web_response = alarm_list_web(alarms) elif action == 'info' and id_present: response += 'info on alarm ' + name web_response = alarm_info_web(alarms[name]) elif action == 'exists' and alarm_id in params: response += 'exists '+ alarm_id web_response = 'true' if alarms.exists(params[alarm_id]) else 'false' elif action == 'gen_name': name = alarms.generate_name() response += 'name ' +name web_response = name elif action == 'wakeup_light' and id_present: wakeup_button_pressed(name) response += 'wakeup light ' + name + ' color ' + alarms[name].color response += ' duration ' + str(alarms[name].color_onset) else: response += 'arguments not recognized' web_response = error_returnstring print (response) return web_response