def p_challenge_answer(): print("------ 挑战答题得分任务 ------") p = say("完成挑战答题,输入 x 退出查询") p.wait() while True: p = say("请输入关键字:") keyWord = input() p.kill() if keyWord == 'x': break searchRet = tiaozhanSearch(keyWord) answerList = [] remove_str = "温馨提示:相似题目,注意区分" for sr in searchRet: for s in sr.split('· '): s = s.replace(remove_str, '') s = s.replace("\r\n\r\n", '') s = s.replace("【", "\033[1;31m【") s = s.replace("】", "】\033[0m") answerList.append(s) answerList = list(filter(None, answerList)) p = say("搜索到" + str(len(answerList)) + "个结果") for i in range(0, len(answerList)): print('\033[1;36m <' + str(i + 1) + '>\033[0m ' + answerList[i]) p.wait() beep('coin') p = say("恭喜已完成该任务") p.wait()
def p_likesome(): print("------ 评论、转发、订阅得分任务 ------") print("提示:强国号多订阅无效") goon("选择一篇文章,评论 1 次,转发 2 次, 选择订阅 2 个新的强国号, \n请完成后") beep('coin') p = say("恭喜已完成该任务") p.wait()
def decoratedFun(*args, **kwargs): params = { 'timerShow': True, 'timerBeforeRun': None, 'timerPrefix': '', 'timerSuffix': '', 'timerBeep': False } params, kwargs = obtainParamsFromKwargs(kwargs, params) show, beep = params['timerShow'], params['timerBeep'] beforeRun, prefix, suffix = params['timerBeforeRun'], params[ 'timerPrefix'], params['timerSuffix'] if beforeRun is not None and show: output(beforeRun) startTime = time.time() retVal = fun(*args, **kwargs) t = formatT(startTime, time.time()) if show: output( f'{prefix}{t} -> [{fun.__name__[0].upper() + fun.__name__[1:]}]{suffix}' ) if beep: libBeepy.beep() return retVal
def audioRecorderCallback(self, fname): print("converting audio to text") r = sr.Recognizer() with sr.AudioFile(fname) as source: audio = r.record(source) # read the entire audio file # recognize speech using Google Speech Recognition try: googletext = r.recognize_google(audio) print('google says %s' % googletext) self.interpret(googletext) except sr.UnknownValueError: print("Google Speech Recognition could not understand audio") beepy.beep("error") except sr.RequestError as e: print( "Could not request results from Google Speech Recognition service; {0}" .format(e)) beepy.beep("error") os.remove(fname) return
def train(self, inputs, answers, iteration, learning_rate=0.1, sound=False): iter_delta = 0 iter_nb = 0 iter_duration = 0.1 iter_start = time.time() print('#'*40) self.print_accuracy(inputs, answers) for y in range(iteration): stdout.write("\rIteration {0:}/{1:}\t{2:.2f}%\t\tETA:{3:}"\ .format(y+1, iteration, ((y+1)/iteration)*100, convert_sec(int(iter_duration*(iteration-y+1))))) stdout.flush() i = random.randint(0,len(inputs)-1) self.one_train(inputs[i], answers[i], learning_rate) iter_delta = time.time() - iter_start iter_nb += 1 if iter_delta >= 2: iter_duration = iter_delta / iter_nb iter_start = time.time() iter_nb = 0 print("") self.print_accuracy(inputs, answers) print('#'*40) if sound: beepy.beep(sound=1) beepy.beep(sound=1)
def main(argv): seconds = 120 fileName = "recording.txt" # parse second if (argv[0] == "--sec"): seconds = int(argv[1]) print("RECORDING FOR " + str(seconds) + " SECONDS") else: print("RECORDING FOR DEFAULT" + str(seconds) + " SECONDS") if (argv[2] == "--file"): fileName = argv[3] print("Saving at: " + fileName) start = datetime.datetime.now() while (datetime.datetime.now() - start).seconds < seconds: # print("Wait for prompt -- seconds elapsed:" , datetime.datetime.now() - start) secsToWaitBeforePromp = random.randint(5, 8) time.sleep(secsToWaitBeforePromp) beepy.beep(sound=1) # integer as argument print("PERFORM ACTION NOW -- elapsed:", datetime.datetime.now() - start) outputLabels.append(str(datetime.datetime.now().time())) time.sleep(3) # wait 3 seconds to perform action writeToFile(fileName)
def play_beep(beep_name): ''' Plays notification sounds with the sound that the user choose Args: beep_name: beep sound ''' beepy.beep(sound=beep_name)
def get_fresh_response(num=1): print(num, get_time()) global DISTRICT_INFO if DISTRICT_INFO is None: DISTRICT_INFO = get_district_info(districts_names) centers = get_centers(DISTRICT_INFO) print(f"FOUND { len(centers) } POSSIBLE CENTERS") lst = [] for center in centers: parsed_content = parse_center_info(center) if len(parsed_content): lst.extend(parsed_content) if len(lst) == 0: print("NOTHING FREE") else: available_centers = {} for center in lst: if center["district_name"] not in available_centers: available_centers[center["district_name"]] = [] available_centers[center["district_name"]].append(center) with open("result.txt", "w") as file: file.writelines( [f"Found {len(lst)} ON {get_date()} AT {get_time()}\n"]) for district in available_centers: file.writelines([district, "\n"]) file.flush() for center in available_centers[district]: file.writelines([json.dumps(center, indent=1), "\n"]) file.flush() print(district, json.dumps(center, indent=1)) if center["available_capacity"] >= 10: beep(1) sleep(5)
def _test1(): ''' Simple test function with beeps ''' import beepy try: from decouple import config import matplotlib.pyplot as plt path88 = config('MRSS') dataset_filename = os.path.join( path88, 'full-pixel_mrss_s1_asc_t88_v4_080a1cbf7de1b6d42b3465772d9065fe7115d4bf.csv' ) obj = dataset(dataset_filename) location = [203338.4, 319520.3] radius = 100 subset = obj.create_subset(location, radius) print(f'Extend of the coordinates (wgs) is: {obj.extend_wgs}') beepy.beep(sound='coin') plt.figure() plt.scatter(subset['pnt_rdx'], subset['pnt_rdy']) plt.show() except Exception as e: print('error', e) beepy.beep(sound='error')
def get_centers(districts_info): centers = [] for district in districts_info: try: response = requests.get( "https://cdn-api.co-vin.in/api/v2/appointment/sessions/calendarByDistrict", headers={ "authority": "cdn-api.co-vin.in", "accept": "*/*", "access-control-request-method": "GET", "access-control-request-headers": "authorization", "origin": "https://selfregistration.cowin.gov.in", "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36", "sec-fetch-mode": "cors", "sec-fetch-site": "cross-site", "sec-fetch-dest": "empty", "referer": "https://selfregistration.cowin.gov.in/", "accept-language": "en-US,en;q=0.9", }, params=( ("district_id", district["district_id"]), ("date", get_date(date_to_look_from)), ), ) if response.status_code != 200: raise Exception( f"Request for {district['district_name'].upper()} returned status {requests.status_codes._codes[response.status_code][0].upper()}" ) response = json.loads(response.content.decode("utf8")) centers.extend(response["centers"]) except Exception as E: print(E) beep(2) return centers
def main(): # noqa: D103 # set up an argument parser parser = argparse.ArgumentParser(prog='vaccine.py') parser.add_argument("--total", dest="total_hours", type=int, help="Total Number of hours for which to run the script", default=3) parser.add_argument("--refresh", dest="refresh_minutes", help="Number of minutes after which to refresh results", type=int, default=1) parser.add_argument("--state", help="State to search, e.g., NJ", required=True) parser.add_argument("--cities", nargs='+', help="Full names of cities to search, separated by whitespace", required=True) # parse given command line arguments args = parser.parse_args() max_time = time.time() + args.total_hours * 60 * 60 state_url = CVS_URL.format(args.state.lower()) chosen_cities = [city.upper() for city in args.cities] # run for `args.total` hours or until Ctrl-C is pressed while time.time() < max_time: try: # get the latest response from CVS website response = requests.get(state_url, headers={"Referer": REFERER_URL}) payload = response.json() # save the status for the chosen cities in a dictionary statusdict = {} for item in payload["responsePayloadData"]["data"][args.state]: city, status = item['city'], item['status'] if city in chosen_cities: statusdict[city] = status # print out the values in the dictionary and make a sound to alert # the user if any of the chosen cities have appointments available print(time.ctime()) for city, status in statusdict.items(): print(city, status) if status != 'Fully Booked': beepy.beep(sound='coin') break # sleep for the given number of minutes # before refreshing again time.sleep(args.refresh_minutes * 60) print() except KeyboardInterrupt: print('Exiting ...') break
async def ldbot(): browser = await connect(browserWSEndpoint=ws_url) page = await browser.newPage() await page._client.send('Emulation.clearDeviceMetricsOverride') while True: for link in links: print(datetime.now()) stock = await get_stock(page, link) print(stock) if stock != "Out of Stock" and stock != "Store Pickup Only" and stock != None: beepy.beep() await page.waitForSelector('#add-to-cart') await page.click('#add-to-cart') await asyncio.sleep(3) await page.goto('https://www.londondrugs.com/cart/') # checkout btn await page.click( '#cart-items-form > fieldset > div > div.shopping-cart__order-processing > div > div.cart-total__payment-section > fieldset > button' ) await asyncio.sleep(3) # review billing await page.click( '#dwfrm_singleshipping_shippingAddress > button') await page.waitForXPath(cvv_xpath) # type cvv cvv_field = await page.xpath(cvv_xpath) await cvv_field[0].type('5155') await asyncio.sleep(3) # review order await page.click('#dwfrm_billing > button') await page.waitForXPath(tick_xpath) tickbox = await page.xpath(tick_xpath) await tickbox[0].click() # place order await page.click( 'body > main > div > div > div > section > form > ' 'div.ch-place-order-confirm > div.ch-place-order__action-button-bottom > button' ) await asyncio.sleep(5) telegram_send("LD Checkout") else: print("Not in stock :(") await asyncio.sleep(5) await asyncio.sleep(15)
def jarvisCHAT(): while True: if keyboard.is_pressed("esc"): print("Shutting Down") chatSpeech("Shutting Down") break elif keyboard.is_pressed("enter"): beepy.beep(sound=1) userText = str(speechChat()) if userText == "Errors": continue print("User: {}".format(userText)) new_user_input_ids = tokenizer.encode( userText + tokenizer.eos_token, return_tensors='pt').to("cuda") if step > 0: bot_input_ids = torch.cat( [chat_history_ids, new_user_input_ids], dim=-1) else: bot_input_ids = new_user_input_ids # generated a response while limiting the total chat history to 1000 tokens, chat_history_ids = model.generate( bot_input_ids, max_length=1000, pad_token_id=tokenizer.eos_token_id).to("cuda") # pretty print last ouput tokens from bot botText = tokenizer.decode( chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True) print("DialoGPT: {}".format(botText)) chatSpeech(botText) else: pass
def check_availibilty(date): try: for pin in PINCODE: print(f"\nPINCODE: {pin}\n") payload = {"pincode": pin, "date": date} resp = requests.get(URL, params=payload,headers=MOCK_HEADER) resp.raise_for_status() resp = resp.json() centers = resp['centers'] if centers: max_center_string_len = max([len(center['name']) for center in centers]) for center in centers: center_name = center['name'] sessions = center['sessions'] for session in sessions: available = session['available_capacity'] vaccine_type = session['vaccine'] session_date = session['date'] age = session['min_age_limit'] slots = session['slots'] print(f"{center_name:>{max_center_string_len}} => available:: {available:03}, date:: {session_date}, type:: {vaccine_type}, timing :: {slots}\n") # beep as many times as many vaccines are available # why? to piss off people for c in range(0,available): beep(sound=SOUND) print("=======================================\n") except requests.exceptions.RequestException as e: print(f"Error while checking availibilty {e}") raise SystemExit(e)
def chat_message(self, event): message = event['message'] username = event['username'] # Send message to WebSocket self.send(text_data=json.dumps({ 'username': username, 'message': message })) beep(sound=1)
def reset_timer(): """This function clears the timer""" interface.after_cancel(timer) beepy.beep(sound='error') canvas.itemconfig(timer_text, text="00:00") timer_label.config(text="Start Timer") checks.config(text="") global timer_repeat timer_repeat = 0
def UpdateActivity(edit, activity_log): ''' For updating the activity log each time there is a change on editor while the voice mode is on ''' #Beep is helpful for making the user realize that the change has been made on the editor beepy.beep(sound=3) activity_log.config(state='normal') activity_log.insert(END, edit) activity_log.config(state='disabled')
def p_weekend_answer(): print("------ 每周答题得分任务 ------") print("提示:本系统默认设置为每周一完成每周答题任务") wd = datetime.datetime.now().weekday() if wd == 0: # 周一 goon("完成每周答题,要小心别手残答错哟, \n请完成后") beep('coin') p = say("恭喜已完成该任务") p.wait()
def termin_suchen(self, plz): """Es wird nach einen verfügbaren Termin in der gewünschten PLZ gesucht. Ausgewählt wird der erstbeste Termin (!). Zurückgegeben wird das Ergebnis der Abfrage und der Status-Code. Bei Status-Code > 400 müssen die Cookies erneuert werden. Beispiel für ein Termin-Paar: [{ 'slotId': 'slot-56817da7-3f46-4f97-9868-30a6ddabcdef', 'begin': 1616999901000, 'bsnr': '005221080' }, { 'slotId': 'slot-d29f5c22-384c-4928-922a-30a6ddabcdef', 'begin': 1623999901000, 'bsnr': '005221080' }] :return: bool, status-code """ path = f"rest/suche/impfterminsuche?plz={plz}" while True: res = self.s.get(self.domain + path, timeout=15) if not res.ok or 'Virtueller Warteraum des Impfterminservice' not in res.text: break self.log.info('Warteraum... zZz...') time.sleep(30) if res.ok: res_json = res.json() terminpaare = res_json.get("termine") if terminpaare: # Auswahl des erstbesten Terminpaares self.terminpaar = choice(terminpaare) self.plz_termin = plz self.log.success(f"Terminpaar gefunden!") self.impfzentrum = self.verfuegbare_impfzentren.get(plz) self.log.success("'{}' in {} {}".format( self.impfzentrum.get("Zentrumsname").strip(), self.impfzentrum.get("PLZ"), self.impfzentrum.get("Ort"))) for num, termin in enumerate(self.terminpaar, 1): ts = datetime.fromtimestamp( termin["begin"] / 1000).strftime('%d.%m.%Y um %H:%M Uhr') self.log.success(f"{num}. Termin: {ts}") if ENABLE_BEEPY: beepy.beep('coin') return True, 200 else: self.log.info(f"Keine Termine verfügbar in {plz}") else: self.log.error( f"Terminpaare können nicht geladen werden: {res.text}") return False, res.status_code
def alert(text=None): if text: for _ in range(20): beep.beep(5) print('Waiting 4 minutes. Snoozing.') time.sleep(4 * 60) print("Starting again.") else: while True: beep.beep(7)
def command_received(self, commands): for command, i in zip(commands, range(4)): assert (command[0][:2] == f"0{i+1}") self.df_acq.loc[self.selected_item, [f"x{i+1}", f"y{i+1}", f"z{i+1}"]] = np.array(command[1:4], dtype=float)/100 # cm to m if not self.mute_sound_wgt.isChecked(): beepy.beep(1) self.df_acq.to_csv(f"{self.config['DEFAULT']['subject_dir']}/{self.subject}_df_acq.csv") self.tableView.selectRow(self.selection.selectedRows()[0].row()+1)
def notifi(name_stock, price): ICON_PATH = "icon.png" #icon path notify2.init("Stock Notifier") n = notify2.Notification(name_stock, price, icon=ICON_PATH) # set urgency level n.set_urgency(notify2.URGENCY_NORMAL) # set timeout for a notification n.set_timeout(100) beep(sound=4) n.show()
def main(): sound_played = False while (True): battery = psutil.sensors_battery() if (not battery.power_plugged or battery.percent != 100 and not sound_played): continue beepy.beep(sound=1) sound_played = True return
def find_w_pin(): num_days = 7 print("\n Find Vaccine slots by Pincode") age = input(">> Please enter the age: ") pin_code = input( ">> Please enter the Pin code. Add ',' if you are entering multiple pin codes: " ) pin_code_list = [pin.strip() for pin in pin_code.split(',')] list_format = [actual + timedelta(days=i) for i in range(num_days)] actual_dates = [i.strftime("%d-%m-%Y") for i in list_format] while True: counter = 0 for pinCode in pin_code_list: print(f"Finding Vaccine Slots for {pinCode}") for given_date in actual_dates: URL = "https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByPin?pincode={}&date={}".format( \ pinCode, given_date) result = requests.get(URL, headers=headers) if result.ok: response_json = result.json() if response_json["centers"]: for center in response_json["centers"]: for session in center["sessions"]: if (session["min_age_limit"] <= int(age) and session["available_capacity_dose1"] > 0 or session["available_capacity_dose2"] > 0): beep.beep(sound="ping") center_dict = {'Name': center['name'], 'Available Capacity': center['available_capacity'], 'Date': center['date'], \ 'Address': center['address'], 'Pincode': center['pincode']} print("=" * 25) for key, val in center_dict.items(): print(str(key) + ' : ' + str(val)) print("=" * 25) else: pass else: pass else: print("No Reponse") if (counter == 0): print("No Vaccination slot avaliable!") else: print("Search Completed!") dt = datetime.now() + timedelta(minutes=3) while datetime.now() < dt: time.sleep(1)
def make_beep_noise(): """Makes an audible beep sound. Supports Windows and Linux.""" if beep_enabled: if sys.platform == "win32": duration = 1000 freq = 1000 winsound.Beep(freq, duration) elif sys.platform == "linux": # Documentation here: https://docs.python.org/3/library/sys.html#sys.platform beep(sound=1) else: print("Platform not supported for make_beep_noise().")
def predict(self): # transform array values to 1-vector Tensor waveform = torch.Tensor([a for a in self.list]).flatten() with torch.no_grad(): mel = transform(waveform).squeeze(0).t() pred = self.get_pred(mel) if pred == 1: self.success_num = self.success_num + 1 beep(sound="coin") print(f"Success #{self.success_num}") time.sleep(0.1) # after keyword detection skip 100 ms
def find_w_dist(): print("\n Find Vaccine slots by Districts") num_days = 7 print("\n Find Vaccine slots by Districts") age = input(">> Please enter the age: ") dist = input(">> Please enter the District Name: ").capitalize() data = getdata.get_dataobj(filename, dist) if data is not None: dist_id = data[2] else: print(f"No dist found with the name {dist}") return list_format = [actual + timedelta(days=i) for i in range(num_days)] actual_dates = [i.strftime("%d-%m-%Y") for i in list_format] print(">> Starting search for Covid vaccine slots!") while True: counter = 0 for given_date in actual_dates: URL = "https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/findByDistrict?district_id={}&date={}".format( dist_id, given_date) response = requests.get(URL, headers=headers) if response.ok: response_to_json = response.json() if response_to_json['sessions']: for center in response_to_json['sessions']: if int(age) >= center['min_age_limit']: if (center['available_capacity_dose1'] > 0 or center['available_capacity_dose2'] > 0): beep.beep(sound="ping") center_dict = {'Name': center['name'], 'Available Capacity': center['available_capacity'], 'Date': center['date'], \ 'Address': center['address'], 'Pincode': center['pincode']} print("=" * 25) for key, val in center_dict.items(): print(str(key) + ' : ' + str(val)) print("=" * 25) else: pass else: print("No Response!") if (counter == 0): print("No Vaccination slot avaliable!") else: print("Search Completed!") dt = datetime.now() + timedelta(minutes=3) while datetime.now() < dt: time.sleep(1)
def readTranscript(): tactiqButton = wait.until(when.element_to_be_clickable((by.XPATH, '//div[@class="_2qlModb"]'))) tactiqButton.click() while True: time.sleep(0.3) all_texts = driver.find_elements_by_xpath('//div[@class="K4JPC9P"]') for text in all_texts[-3:]: check = any(item in text.text.lower() for item in trigger_words) if check is True: beepy.beep(sound = 5) else: continue
def GiveInput(command, editor, count, activity_log, code_input): ''' For giving input to the program ''' #Adding a pause between 2 consecutive commands time.sleep(0.5) #Everything after the chime will be the input to the program beepy.beep(sound=4) Input = Listen(activity_log) if Input is not None: code_input.insert(INSERT, Input) edit = str(count) + '::' + 'Added ' + Input + ' to input block\n' UpdateActivity(edit, activity_log)
def countdown(count): seconds = math.floor(count % 60) minutes = math.floor((count / 60) % 60) hours = math.floor((count / 3600)) label[ "text"] = f"Hours: {str(hours)} Minutes: {str(minutes)} Seconds: {str(seconds)}" if count >= 0: main.after(1000, countdown, count - 1) else: for _ in range(3): beepy.beep(sound=1) label["text"] = "Time is up!"