def set_data_clipboard(self, column): s = clipboard.paste() s_var = s n = s.count('\t', 0, s.find('\n')) header = '' for i in self.HeaderLabels[column:column+n+1]: header += i + '\t' header = header[:-1] header = header + '\n' s = header + s clipboard.copy(s) try: data = pd.read_clipboard() for i in data.keys(): self.data[i] = remove_nan(data[i]) self.logger.info('Data loading from clipboard successfully') self.notify_observers() except (MyException, IsnanInput) as e: print(e) self.logger.info('Data loading error; Check clipboard values') self.logger.error(str(e)) finally: clipboard.copy(s_var) self.datastatus = self.check_datastatus() if self.datastatus == 'full' or self.datastatus == 'partlyfull': self.step_E = self.data['Xe'][1]-self.data['Xe'][0] self.step_L = self.data['Xl'][1]-self.data['Xl'][0] self.notify_observers_datastatus()
def handle(self, *args, **options): urban = self.get_urban_dictionary_word() search_word = urban["word"] url = urban["url"] search_results = spotify_conn.search( q="track:%s" % urban["word"], limit=20 ) if len(search_results["tracks"]["items"]) == 0: # tweet = u"\U0001F4A9 \U0000201C there are no songs for \"%s\" %s" % ( tweet = u"\u201C%s\u201D is up for grabs on @spotify... just in case you were looking for a song name. %s \u266A" % ( urban["word"], urban["url"] ) print "Tweeting..." print tweet # twitter_conn.update_status(status=tweet) clipboard.copy(tweet) return None # Get the closest track from the spotify search for track in search_results["tracks"]["items"]: ratio = fuzz.ratio(urban["word"], track["name"]) track["match"] = ratio closest_track = max(search_results["tracks"]["items"], key=lambda item: item["match"]) # Get the artist's twitter handle user_search = twitter_conn.search_users( q="Amateur musician", count=20 ) if len(user_search) > 0: print random.choice(user_search)
def process_file(args, file_or_url): if "https://transfer.sh" in file_or_url: try: download(args, file_or_url) except Exception: LOG.exception("error while downloading %s", file_or_url) return else: if not os.path.exists(file_or_url): LOG.warning("File doesn't exist: %r", file_or_url) return try: password, file_url = upload(args, file_or_url) except Exception: LOG.exception("error while uploading %s", file_or_url) return if not file_url: LOG.error("Could not get uploaded file url!") return if password: file_url = file_url + '#' + password print("\n"+file_url+"\n") clipboard.copy(file_url) clipboard.paste() print ("Uploaded file link is copied to clipboard, bye")
def clipboard_copy(self, *args): """\ returns a copy of self to be inserted in the clipboard """ import clipboard clipboard.copy(self)
def get_data_clipboard(self, columns): """ Copies data from table columns """ try: data = [] for col in columns: data.append(self.data[self.HeaderLabels[col]]) len_arr = 0 for arr in data: n = len(arr) if len_arr < n: len_arr = n data_str = "" col = 0 while col < len_arr: for i in range(len(data)): try: data_str = data_str + "%.3f" % data[i][col] except IndexError: pass finally: if i != len(data) - 1: data_str = data_str + '\t' if i == len(data) - 1: data_str = data_str + '\n' col += 1 clipboard.copy(data_str) #df = pd.DataFrame(data) #df.to_clipboard(excel = True) except: self.logger.info('Nothing was copied')
def main(): # parse args parser = argparse.ArgumentParser(description='Quick upload a file.') parser.add_argument('file_name', metavar='File', type=str, help='File to upload') parser.add_argument('-n', dest='dest_name', metavar='Filename', type=str, help='Destination filename', default=None) parser.add_argument('-c', dest='copy', action='store_true', help="Copy the URL to the clipboard") parser.set_defaults(copy=False) args = parser.parse_args() # does file exist? if not os.path.isfile(args.file_name): return print("Error: File does not exist") # upload the file upload_file(args.file_name, args.dest_name) if args.dest_name is not None: result = URL_PREFIX + args.dest_name else: result = URL_PREFIX + os.path.basename(args.file_name) if args.copy: clipboard.copy(result) print('Copied to clipboard!') print(result)
def expron(word): page_source = fetch_page_source(word) pron_url = extract_pron_url(page_source) if pron_url: filename = word+'.mp3' clipboard.copy('[sound:{}]'.format(filename)) download_pronfile(filename, pron_url) play_downloaded(filename)
def copy(value=None, name=None): value = value or not sys.stdin.isatty() and sys.stdin.read() value = smart_str(value) with Storage() as storage: storage.save(value, name=name) if not name: clipboard.copy(value)
def do_copy(): if sys.argv[1:]: copy(" ".join(sys.argv[1:])) return True elif not os.isatty(sys.stdin.fileno()): copy(sys.stdin.read()) return True return False
def paste(name=None): with Storage() as storage: if not name: data = clipboard.paste() or storage.get() else: data = storage.get(name) data = smart_str(data) clipboard.copy(data) return data
def test(): clipboard.copy(""" >>> def count_down(value): ... for x in range(value, 0, -1): ... yield x ... """) print(replace_clipboard())
def replace_clipboard(): text = clipboard.paste() new_text = [] for line in text.splitlines(): line = line.strip().replace(">>> ", "").replace("... ", "") if not line.startswith("..."): new_text.append(line) output = "\n".join(new_text) subprocess.call(["notify-send", f"replace clipboard: {output}"]) clipboard.copy(output)
def copy(dest): try: f = open(sys.argv[1], "r") payload = f.read() clipboard.copy(payload) f.close() sys.exit() except Exception as e: print "[*] Impossible to open file %s." %sys.argv[1] print e
def supload(): filename = "Screenshot_" + datetime.datetime.now().strftime("%m-%d-%y_%I.%M.%S%p") + ".png" path = os.path.join(directory, filename) os.system("screencapture -s " + path) file = {'file': (filename, open(path, 'rb'), 'image/png')} payload = {'owner': owner, 'password':password} r = requests.post(url, files=file, data=payload) clipboard.copy("https://i.frogbox.es/" + r.text + ".png")
def copy_current_file_offset(): """Get the file-offset mapped to the current address.""" start, end = sark.get_selection() try: file_offset = sark.core.get_fileregion_offset(start) clipboard.copy("0x{:08X}".format(file_offset)) except sark.exceptions.NoFileOffset: message("The current address cannot be mapped to a valid offset of the input file.")
def supload(): filename = "Screenshot_" + datetime.datetime.now().strftime("%m-%d-%y_%I.%M.%S%p") + ".png" path = os.path.join(directory, filename) os.system("scrot -s " + path) file = {"file": (filename, open(path, "rb"), "image/png")} payload = {"owner": owner, "password": password} r = requests.post(url, files=file, data=payload) clipboard.copy("https://i.frogbox.es/" + r.text + ".png") os.system('notify-send "Screenshot uploaded!"')
def get(): lines = pfp() header = lines[0] hidx = {h:i for i, h in enumerate(header)} plines = lines[1:] out = [] def vals(p): return p[hidx["Name"]], p[hidx["DPS"]] for p in plines: out.append(" %-15s %s"%vals(p)) s = "\n".join(out) clipboard.copy(s)
def main(): l_id = parse_jira_id_from_file(sys.argv[1]) s_id = unique_jira_id_and_sort(l_id) s_id_histroy = load_histroy() s_id_not_recorded = s_id - s_id_histroy prepare() for item in s_id_not_recorded: addr = "https://jira01.devtools.intel.com/si/jira.issueviews:issue-xml/GMINL-%d/GMINL-%dxml" % (item, item) clipboard.copy(addr) savexml() s_id_histroy.add(item) save_history(s_id_histroy)
def tupload(): filename = "Clipboard_" + datetime.datetime.now().strftime("%m-%d-%y_%I.%M.%S%p") + ".txt" path = os.path.join(directory, filename) text = clipboard.paste() f = open(path, 'w') f.write(text) f.close() file = {'file': (filename, open(path, 'r'), 'text/plain')} payload = {'owner': owner, 'password':password} r = requests.post(url, files=file, data=payload) clipboard.copy("https://i.frogbox.es/" + r.text + ".txt")
def execute(self, message): if "entrar" in message: self.keyboard.tap_key(self.keyboard.enter_key) return True if "fechar aba" == message: self.keyboard.press_key(self.keyboard.control_key) self.keyboard.tap_key('w') self.keyboard.release_key(self.keyboard.control_key) return True if "nova janela" == message: self.keyboard.press_key(self.keyboard.control_key) self.keyboard.tap_key('n') self.keyboard.release_key(self.keyboard.control_key) return True if "nova aba" == message: self.keyboard.press_key(self.keyboard.control_key) self.keyboard.tap_key('t') self.keyboard.release_key(self.keyboard.control_key) return True if "endereço" == message: self.keyboard.press_key(self.keyboard.control_key) self.keyboard.tap_key('l') self.keyboard.release_key(self.keyboard.control_key) return True if "salvar" == message: self.keyboard.press_key(self.keyboard.control_key) self.keyboard.tap_key('s') self.keyboard.release_key(self.keyboard.control_key) return True if "imprimir" == message: self.keyboard.press_key(self.keyboard.control_key) self.keyboard.tap_key('p') self.keyboard.release_key(self.keyboard.control_key) return True if "texto" in message: text = message.replace("texto ", "") clipboard.copy(text) # self.keyboard.type_string(text) self.keyboard.press_key(self.keyboard.control_key) self.keyboard.tap_key('v') self.keyboard.release_key(self.keyboard.control_key) return True return False
def tupload(): filename = "Clipboard_" + datetime.datetime.now().strftime("%m-%d-%y_%I.%M.%S%p") + ".txt" path = os.path.join(directory, filename) text = clipboard.paste() f = open(path, "w") f.write(text) f.close() file = {"file": (filename, open(path, "r"), "text/plain")} payload = {"owner": owner, "password": password} r = requests.post(url, files=file, data=payload) clipboard.copy("https://i.frogbox.es/" + r.text + ".txt") os.system('notify-send "Clip uploaded!"')
def encurtar(ctrlv): global API_KEY # (╯°□°)╯ Preciso melhorar esse regex! regexes = [ "^(?:http|ftp)s?://", "(www\.)?[a-z0-9\.:].*?(?=\s)" ] # Cria um regex que inclue todas nossas condições. HTTP_regex = "(" + ")|(".join(regexes) + ")" # Condição para expandir o link bitly do cliboard. if 'bit.ly' in ctrlv: print '[ Expandindo o URL ... ]' print requests.get(ctrlv).url clicks(ctrlv) exit(1) # Condição para verificar se o cliboard é um UR valido ou não. elif re.match(HTTP_regex, ctrlv): print "[ Encurtando o URL ... ]" parametros = {'access_token': API_KEY,'longUrl': ctrlv} URL = 'https://api-ssl.bitly.com/v3/shorten' response = requests.get(URL, params=parametros, verify=False) data = json.loads(response.content) if '500' in response.content: print '[!] Não é um URL válido' else: print data['data']['url'] # Variavel do Clipboard short_url = data['data']['url'] # Adiciona ao Clipboard, agora é só dar ctrl+v nessa porra. clipboard.copy(short_url) else: print "[!] Não achei URL no seu clipboard"
def run_cmd(cmd, pl_tree_set): if cmd == "CMD_LATEX_TABLE": if pl_tree_set != None and len(pl_tree_set) != 0 : table = pl_tree_set.make_table() s = make_latex_table(table) print s clipboard.copy(s) elif cmd == "CMD_SEMANTIC_DERIV": if pl_tree_set != None and len(pl_tree_set) == 1: pl_tree = pl_tree_set[0] s = pl_tree.seman_derive() print s clipboard.copy(s) elif cmd == "CMD_EMPTY": pass else: print "Invalid command. "
def copy(self): if 'indows' in platform.system(): try: import clipboard clipboard.copy(self.data) return clipboard.paste() except: import win32clipboard as w import win32con w.OpenClipboard() w.EmptyClipboard() w.SetClipboardData(w.CF_TEXT, self.data) return w.GetClipboardData(win32con.CF_TEXT) elif 'inux' in platform.system(): try: import clipboard clipboard.copy(self.data) return clipboard.paste() except: try: check_01 = os.system('which xsel') if check_01 != '': from subprocess import Popen, PIPE p = Popen(['xsel','-pi'], stdin=PIPE) p.communicate(input='data') return os.popen('xsel').read() else: return "\tplease install xsel (apt-get xsel) or clipboard (pypi)\n\tOn Windows you must install pywin32 (pypi) or clipboard (pypi)\n" except: if self.check_call('xsel') == 0: from subprocess import Popen, PIPE p = Popen(['xsel','-pi'], stdin=PIPE) p.communicate(input='data') return os.popen('xsel').read() else: return "\tplease install xsel (apt-get xsel) or clipboard (pypi)\n\tOn Windows you must install pywin32 (pypi) or clipboard (pypi)\n" elif 'arwin' in platform.system(): os.system("echo '%s' | pbcopy" % self.data) from AppKit import NSPasteboard from LaunchServices import * pb = NSPasteboard.generalPasteboard() text = pb.stringForType_(kUTTypeUTF8PlainText) return text else: print "\t you not in Windows, Linux or Mac, this support for windows/linux/mac yet"
def testCopy(self): self._createVault() self._addLoginItem('mysite', 'myuser', 'mypass', 'mysite.com') clipboard.copy('test') if clipboard.paste() != 'test': # running on a system without clipboard support # (eg. Linux sans Xorg) self.skipTest('Clipboard not supported') return (self.exec_1pass('copy mysite') .wait()) self.assertEqual(clipboard.paste(), 'mypass') (self.exec_1pass('copy mysite user') .wait()) self.assertEqual(clipboard.paste(), 'myuser')
def runQuery(driver, text, explainOnly=False): offset = adjustXOffset() pyautogui.moveTo(600+offset, 400) pyautogui.click() # Clear the buffer. time.sleep(shortSleep) pyautogui.hotkey('command', 'a') time.sleep(shortSleep) pyautogui.press('del') time.sleep(shortSleep) # New query. clipboard.copy(text) pyautogui.hotkey('command', 'v') time.sleep(shortSleep) if explainOnly: return 0 try: execute = driver.find_element_by_class_name("execute-query") except: time.sleep(1) execute = driver.find_element_by_class_name("execute-query") execute.click() magicString = "previous next" startTime = time.time() time.sleep(0.5) while 1: time.sleep(0.5) try: results = driver.find_element_by_class_name("query-process-results-panel") except: # Failed query print "Failed query, returning" return 1 if results.text.find(magicString) > -1: endTime = time.time() totalTime = endTime - startTime print "Query is done, time = %f" % totalTime time.sleep(1) return 0
def _code_helper(line, func, copy=True): args = shlex.split(line) if not args: s = clipboard.paste() print 'Will decode:' print printable_data(s) s = func(s) if copy: try: clipboard.copy(s) except: print 'Result cannot be copied to the clipboard. Result not copied.' return s else: s = func(args[0].strip()) if copy: try: clipboard.copy(s) except: print 'Result cannot be copied to the clipboard. Result not copied.' return s
def getSite(self, key, copytoclipboard=None): ''' .. codeauthor:: Firstname Lastname <*****@*****.**> :param key: string number :type key: string :returns: str :raise: Traceback ''' url = 'http://keyserver.ubuntu.com/pks/lookup?op=get&search=0x{0}'.format(key) site = self.handle.getSite(url) if site is not False: soup = bs(site) data1 = soup.find("pre") if copytoclipboard: clipboard.copy(unicode(data1.contents[0]).encode('UTF-8')) return unicode(data1.contents[0]).encode('UTF-8') else: return ''
def symbolDecoder(): while ser != '': #main loop while ser.readline().decode('utf-8')[:2]: #when there is a relevant serial value try: #try to run the main script ind = ser.read() board = clipboard.paste() #store the clipboard contents in the variable clipboard.copy(symbols[ind]) if platform.system() == 'Linux' or platform.system() == 'Windows' : #for windows and linux k.press_key('Control_L') #paste the clipboard k.tap_key('v') k.release_key('Control_L') #k.tap_key('Return') elif platform.system() == 'Darwin': k.press_key('Command') k.tap_key('v') k.release_key('Command') #pass time.sleep(.1) #pause for .1 seconds clipboard.copy(board) #restore the clipboard contents except: #if there is an error pass #do not do anything
def cmd_copy(self): from base64 import b64encode message = { "type": "clipboard", "data": { k: b64encode(v).decode('utf8') for k, v in clipboard.copy().items() } } s = scanner() while True: dests = s.scan(0.1) if dests: for i, dest in enumerate(dests): print(i, dest.desc['name']) choice = input('> ') if choice: d = dests[int(choice)] d.send(message) break else: input('Nobody found, press enter to scan again ')
def copytoclipboard(self, value): clipboard.copy(value)
def copydaily(self): clipboard.copy(self.iteminput.text) b = clipboard.paste()
def onCopyButtonClicked(self): self.outputTransform = str(self.imageToProbe.GetElement(0,0))+" "+ str(self.imageToProbe.GetElement(0,1))+" "+str(self.imageToProbe.GetElement(0,2))+" "+str(self.imageToProbe.GetElement(0,3))+ "\r\n"+str(self.imageToProbe.GetElement(1,0))+" "+str(self.imageToProbe.GetElement(1,1))+" "+str(self.imageToProbe.GetElement(1,2))+" "+str(self.imageToProbe.GetElement(1,3)) + "\r\n"+str(self.imageToProbe.GetElement(2,0))+" "+str(self.imageToProbe.GetElement(2,1))+" "+str(self.imageToProbe.GetElement(2,2))+" "+str(self.imageToProbe.GetElement(2,3)) clipboard.copy(self.outputTransform)
def cp_to_Clipboard(): with open('up.txt', 'r') as f: clipboard.copy(f.read()) print('\n\033[1;94mCopied to clipboard!\033[0m')
if len(meta_description) == 0: print("there is no a meta tag with a description") exit(0) meta_description = str(meta_description[0]) #print(type(meta_description)) trainslation_match = re.search("- (.*)\s-\s(.*)' name", meta_description) if trainslation_match == None: print("there is no match") exit(0) # convert from a string ti a list trainslation = trainslation_match[2].split("; ") i = 1 for meaning in trainslation: print(f"{i} {meaning}") i += 1 echo = word_with_spaces + " " + transcription[1] + " - " + trainslation[0] #echo = echo.replace("\n", "") #os.system("echo " + echo + " | xclip -selection c") clipboard.copy(echo) print() print(diki_link) print("done") exit(0)
import clipboard import time clipboard.copy('') text_0 = '' count = 0 while True: if clipboard.paste() != '' and clipboard.paste() != text_0: text_0 = clipboard.paste() text = clipboard.paste().encode('utf-8') if '\r\n' not in text: text += '\r\n' else: text = text.replace('\r\n', ' ') text = text.replace('et al. ', 'et al.') if text[-1] == ',': continue elif text[-1] == '.' and text[-6:] != 'et al.': text += '\r\n' f = file('text.txt', 'a') f.write(text) f.close() else: time.sleep(0.1) continue
stdscr.addstr(4, 1, 'You have entered ' + str(rows) + ' cols.', curses.A_NORMAL) space = 10 row_template = (" " * space).join(["0" for i in range(cols)]) diff = 6 for line_num in range(diff, rows + diff): stdscr.addstr(line_num, 3, row_template, curses.A_NORMAL) matrix = modify_matrix(stdscr, diff, 3, space, rows, cols) return_str = "\\begin{pmatrix}" + \ "\\\\".join(["&".join(i) for i in matrix]) + "\\end{pmatrix}" stdscr.addstr(diff + rows + 3, 1, "Latex output:", curses.A_NORMAL) stdscr.addstr(diff + rows + 4, 1, return_str, curses.A_NORMAL) clipboard.copy(return_str) stdscr.addstr(diff + rows + 6, 1, "Output has been copied to clipboard. Press 'q' to exit.", curses.A_NORMAL) while True: # stay in this loop till the user presses 'q' ch = stdscr.getch() if ch == ord('q'): break # -- End of user code -- except Exception as _: traceback.print_exc() # print trace back log of the error
def process_clip(s): # 将lc给出的input调整为适合c++,java等使用的格式 s = s.replace("\"", "\'") s = s.replace("[", "{") s = s.replace("]", "}") clipboard.copy(s)
import requests from bs4 import BeautifulSoup import html5lib import clipboard url = input("주소를 입력하세요 : ") r = requests.get(url) soup = BeautifulSoup(r.text, 'html.parser') title = soup.find("title").text body = [] for wrapper in soup.find_all('p'): A = wrapper.text body.append(A) try: body.remove("\n") except ValueError: pass html = "<script src=\"http://code.jquery.com/jquery-latest.js\"></script><script>$(document).ready(function() { $(\'#AnnotationContent\').css(\"overflow-y\", \"scroll\");});</script><style type=\"text/css\">.tg {border-collapse:collapse;border-spacing:0;border-color:#aabcfe;}.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#aabcfe;color:#000000;background-color:#e8edff;}.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#aabcfe;color:#000000;background-color:#b9c9fe;}.tg .tg-s268{text-align:left}</style><table class=\"tg\"><tr><th class=\"tg-s268\">" + title + "</th></tr><tr><td class=\"tg-s268\">" + body[ 0] + "</td></tr></table>" clipboard.copy(html)
n, n_char, n_num) print("Contraseña:", generated_password) while True: ans = input( "¿Desea generar otra contraseña? (s/n): ") if ans.lower() == 's': generated_password = generar_contraseña( n, n_char, n_num) print("Contraseña:", generated_password) elif ans.lower() == 'n': break ans = input( "¿Desea copiar la contraseña al portapapeles? (s/n): " ) if ans.lower() == 's': clipboard.copy(generated_password) ans = input("¿Desea hacer otra operación? (s/n): ") if ans.lower() == 'n': break else: print( "No se puede generar la contraseña deseada. Inténtelo otra vez" ) elif option == "2": usuario = input("Introduce el usuario: ") database = leer_database(DATABASE_FILEPATH) if usuario in database: password = input("Introduce la contraseña: ") hashed_password = hashlib.sha256(password.encode()).hexdigest() if hashed_password == database[usuario]:
def pt_actions(text: str) -> None: translated_object: Translated = trans.translate(text) play_sound(translated_object.text) clipboard.copy(translated_object.text)
def nsm_login(user_id, user_pwd): #pyperclip.copy('prime200*') clipboard.copy('prime200*') pyautogui.click(x=890, y=580) # login dailog setFocus pyautogui.hotkey('ctrl', 'v', interval = 0.15) pyautogui.click(x=1030, y=568) # 로그인 버튼 클릭
request_strings = [] for taskgroup in taskgroups: for task in taskgroup: request = task.generate_api_request( caller=caller, input_container_url=read_only_sas_url, image_path_prefix=None, **additional_task_args) request_str = json.dumps(request, indent=1) request_strings.append(request_str) pprint.pprint(request_strings) # clipboard.copy(request_strings[0]) clipboard.copy('\n\n'.join(request_strings)) #%% Run the tasks (don't run this cell unless you are absolutely sure!) # I really want to make sure I'm sure... if False: for i_taskgroup,taskgroup in enumerate(taskgroups): for i_task,task in enumerate(taskgroup): task_id = task.submit() print('Submitted task {} ({})'.format(task.name, task_id)) if not ((i_taskgroup == len(taskgroups)-1) and (i_task == len(taskgroup)-1)): print('Sleeping to be extra-safe about rapid submissions') time.sleep(submission_time_between_tasks)
def copyparty(self): clipboard.copy(self.itemin.text) b = clipboard.paste()
def duplicate(self, *args): clipboard.copy(self) clipboard.paste(common.app_tree.root.widget)
elif data_byte == 0xbc: next_bytes = (data[start + offset + 1] << 8) | (data[start + offset]) offset += 2 comps.append(f'\tSND_jump ${next_bytes:04x}') break elif data_byte == 0xbd: next_byte = data[start + offset] offset += 1 comps.append(f'\tSND_setDelay ${next_byte:02x}') elif data_byte == 0xbe: # if aud 4, this is actually +5 next_bytes = data[start + offset:start + offset + 5] offset += 5 delay_byte = data[start + offset] offset += 1 j_next_bytes = ' '.join(f'${byte:02x}' for byte in next_bytes) comps.append( f'\tSND_setHWRegsAndDelay {j_next_bytes}, ${delay_byte:02x}') elif data_byte < 0xa0: high3bits = data_byte >> 5 freqBits = data_byte & 0x1f comps.append(f'\tNOTE {notes[freqBits]}, {delay_lens[high3bits]}') else: print(f'{start_addr+offset:04x}') raise Exception(f'{data_byte:02x}') final_str = '\n'.join(comps) print(final_str) print(f'{start_addr+offset:04x}') clipboard.copy(final_str)
def pdfcp(q, e): """Continously monitors for clipboard contents copied from pdf and updates clipboard with the same text without line breaks and, if desired by user with quotes and/or a carriage return automatically appended. MODIFIED CODE DISCLAIMER AND ATTRIBUTION: The pdfcp() function is modified from the code specified in reference 2 of the "References" section in the "Final project PDF copy paster.ipynb" notebook. However, the organization and functionality of pdfcp() was significantly updated (refactoring the code, and/or updating functionality more than just updating naming, style and documentation) and SHOULD BE CONSIDERED PART OF MY GRADED PROJECT CODE. Parameters ---------- q : str ("y" or "") Quote append user input specifying whether or not to append quotes to newly copied pdf text. e : str ("y" or "") Carriage return append user input specifying whether or not to append a carriage return to newly copied pdf text. """ # Allows user to specify optional copied text operations after # main line break removal operation is run quotes(q) enter(e) # Starts termination function thread to run continuously while # pdfcp() monitors and updates clipboard contents threading.Thread(target=terminate).start() # Empty string value which is updated and copied to clipboard with # newly modified text initially copied from a pdf pdfnew = "" # pdfcp() runs unless termination function sets "f" to False while f: # Gets current windows clipboard contents pdftxt = clipboard.paste() # Only modifies NEW clipboard contents to avoid # modifying copied text twice if pdftxt != pdfnew: # Removes line breaks via the replace string method pdfnew = pdftxt.replace("\r\n", " ") # Updates clipboard with modified text clipboard.copy(pdfnew) # Only runs if user selected to enclose text in quotes if pdftxt != pdfnew and q is "y": # Adds quotation mark to both ends of copied pdf text pdfnew = f'"{pdfnew}"' clipboard.copy(pdfnew) # Only runs if user selected to append carriage return to text if pdftxt != pdfnew and e is "y": # Adds two carriage returns to end of copied text to # create a new line in word document ready to paste in # next modified segment of pdf text avoiding the need # for user to manually press return each time they paste text. pdfnew = (pdfnew + '\r\n\r\n') clipboard.copy(pdfnew) # Runs compare() after each while loop iteration to act as a # proxy return comparing pre and post modified copied pdf text compare(pdftxt, pdfnew) # Allows pdfcp() function to rest for 1 sec before running again # to increase overall script stability and save cpu and memory resources time.sleep(1)
def copy_short_url(): try: clipboard.copy(str_url.get()) print("URL copied successfully!") except: str_url.set("Something went wrong, Please try again!")
print() print("--create generates an random password") print("--title <value> tile for Keepass entry") print("--username <value> username for Keepass entry") print("--count amount of characters") print("--hide hide password") print("--temp do not write to keepassfile") print("") print("--getuser <searchstring> get username") print("--getpassword <search string> get password") if arg == '--getuser': all = kp.entries result = kp.find_entries(title=sys.argv[idx+1], first=True) clipboard.copy(result.username) if arg == '--getpassword': all = kp.entries result = kp.find_entries(title=sys.argv[idx+1], first=True) clipboard.copy(result.password) if arg == '--hide': DISPLAYPWD = False if arg == '--temp': KEEPASSWRITE = False if arg == '--create': CREATE = True
def goTo(url): pyautogui.click(400, 59) clipboard.copy(url) pyautogui.typewrite(clipboard.paste()) pyautogui.typewrite('enter', 0.5)
so that the user can just paste the formalized string without doing anything. The program will detect whether the user copied string or image, if its image, the program continur, if it's string, then it formalize it """ import clipboard import time from PIL import ImageGrab print("Start formalizing str in clipboard...") # initialization for the loop comparison use copiedStr = "A1,2p;;[3[]0" # random string while True: img = ImageGrab.grabclipboard() if type(img) != type(None): continue else: # if copied string changed, then formalize the str # and place it in the clipboard so that user can paste it. copiedNewStr = clipboard.paste() if copiedNewStr != copiedStr: clipboard.copy(copiedNewStr) time.sleep(0.4) """ https://pypi.org/project/clipboard/ https://www.devdungeon.com/content/grab-image-clipboard-python-pillow """
def copy_short_url(): try: clipboard.copy(str_url.get()) print("URL copied!") except: str_url.set("Something go wrong! try again...")
def open_vim(self, compile_latex): f = tempfile.NamedTemporaryFile(mode='w+', delete=False) f.write('$$') f.close() subprocess.run([ 'urxvt', '-fn', 'xft:Iosevka Term:pixelsize=24', '-geometry', '60x5', '-name', 'popup-bottom-center', '-e', "vim", "-u", "~/.minimal-tex-vimrc", f"{f.name}", ]) latex = "" with open(f.name, 'r') as g: latex = g.read().strip() os.remove(f.name) if latex != '$$': if not compile_latex: svg = f"""<?xml version="1.0" encoding="UTF-8" standalone="no"?> <svg> <text style="font-size:10px; font-family:'Iosevka Term';-inkscape-font-specification:'Iosevka Term, Normal';fill:#000000;fill-opacity:1;stroke:none;" xml:space="preserve"><tspan sodipodi:role="line" >{latex}</tspan></text> </svg> """ copy(svg, target=TARGET) else: m = tempfile.NamedTemporaryFile(mode='w+', delete=False) m.write(r""" \documentclass[12pt,border=12pt]{standalone} \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \usepackage{textcomp} \usepackage[dutch]{babel} \usepackage{amsmath, amssymb} \newcommand{\R}{\mathbb R} \begin{document} """ + latex + r"""\end{document}""") m.close() working_directory = tempfile.gettempdir() subprocess.run(['pdflatex', m.name], cwd=working_directory, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) subprocess.run(['pdf2svg', f'{m.name}.pdf', f'{m.name}.svg'], cwd=working_directory) with open(f'{m.name}.svg') as svg: subprocess.run(['xclip', '-selection', 'c', '-target', TARGET], stdin=svg) self.press('v', X.ControlMask) self.press('Escape')
def copy_to_clipboard(text): cp.copy(text.get(1.0, END)[:-1])
#%% Test single-query lookup if False: #%% matches = get_taxonomic_info('equus quagga') print_taxonomy_matches(matches) #%% q = 'equus quagga' # q = "grevy's zebra" taxonomy_preference = 'gbif' m = get_preferred_taxonomic_match(q) print(m.source) print(m.taxonomy_string) import clipboard clipboard.copy(m.taxonomy_string) #%% Read the input data df = pd.read_excel(species_by_dataset_file) #%% Run all our taxonomic lookups # i_row = 0; row = df.iloc[i_row] # query = 'lion' output_rows = [] for i_row, row in df.iterrows(): dataset_name = row['dataset'] query = row['species_label']
def order(**kwargs): for key, value in kwargs.items(): if key == 'name': dbundle['name'] = value if key == 'item': dbundle['products'][0]['item_type'] = value if key == 'asset': dbundle['products'][0]['product_bundle'] = value if key == 'idlist': l = [] if value.endswith('.csv'): with open(value) as f: try: reader = csv.reader(f) for row in reader: item_id = row[0] if str(item_id.isalpha()) == 'False': l.append(item_id) except Exception as e: print('Issue with reading: ' + str(value)) elif value.endswith('.txt'): with open(value) as f: for line in f: item_id = line.strip() l.append(item_id) dbundle['products'][0]['item_ids'] = l k = dbundle for key, value in kwargs.items(): if key == 'op' and value != None: for items in value: if items == 'clip': dbundle['tools'].append(dclip) elif items == 'toar': dbundle['tools'].append(dtoar) elif items == 'zip': dbundle.update(dzip) elif items == 'email': dbundle.update(demail) elif items == 'aws': dbundle.update(daws) elif items == 'azure': dbundle.update(dazure) elif items == 'gcs': dbundle.update(dgcs) elif items == 'composite': dbundle['tools'].append(dcomposite) elif items == 'reproject': dbundle['tools'].append(dreproject) elif items == 'ndvi': dndvi = { "pixel_type": "32R", "ndvi": "(b4 - b3) / (b4+b3)" } dbmath['bandmath'].update(dndvi) elif items == 'gndvi': dgndvi = { "pixel_type": "32R", "gndvi": "(b4 - b2) / (b4+b2)" } dbmath['bandmath'].update(dgndvi) elif items == 'ndwi': dndwi = { "pixel_type": "32R", "ndwi": "(b2 - b4) / (b4+b2)" } dbmath['bandmath'].update(dndwi) elif items == 'bndvi': bndvi = {"pixel_type": "32R", "bndvi": "(b4-b1)/(b4+b1)"} dbmath['bandmath'].update(bndvi) elif items == 'tvi': dtvi = { "pixel_type": "32R", "tvi": "((b4-b3)/(b4+b3)+0.5) ** 0.5" } dbmath['bandmath'].update(dtvi) elif items == 'osavi': dosavi = { "pixel_type": "32R", "osavi": "1.16 * (b4-b3)/(b4+b3+0.16)" } dbmath['bandmath'].update(dosavi) elif items == 'evi2': devi2 = { "pixel_type": "32R", "evi2": "2.5 * (b4 - b3) / ((b4 + (2.4* b3) + 1))" } dbmath['bandmath'].update(devi2) elif items == 'sr': dsr = {"pixel_type": "32R", "sr": "(b4/b3)"} dbmath['bandmath'].update(dsr) elif items == 'msavi2': dmsavi2 = { "pixel_type": "32R", "msavi2": "(2 * b4 - ((2 * b4 + 1) ** 2 - 8 * (b4 - b3)) ** 0.5) / 2" } dbmath['bandmath'].update(dmsavi2) elif items == 'compression': dbundle['tools'].append(dtiff) for key, value in kwargs.items(): if key == 'boundary' and value != None: for items in k['tools']: if items.get('clip'): try: if value.endswith('.geojson'): with open(value) as aoi: aoi_resp = json.loads(aoi.read()) items['clip']['aoi']['coordinates'] = aoi_resp[ 'features'][0]['geometry']['coordinates'] elif value.endswith('.json'): with open(value) as aoi: aoi_resp = json.load(aoi) items['clip']['aoi']['coordinates'] = aoi_resp[ 'config'][0]['config']['coordinates'] elif value.endswith('.kml'): getcoord = kml2coord(value) items['clip']['aoi']['coordinates'] = getcoord except Exception as e: print('Could not parse geometry') # #print(e) for key, value in kwargs.items(): if key == 'aws' and value != None: with open(value, 'r') as ymlfile: cfg = yaml.load(ymlfile) for section in cfg: k['delivery']['amazon_s3']['bucket'] = cfg['amazon_s3'][ 'bucket'] k['delivery']['amazon_s3']['aws_region'] = cfg[ 'amazon_s3']['aws_region'] k['delivery']['amazon_s3']['aws_access_key_id'] = cfg[ 'amazon_s3']['aws_access_key_id'] k['delivery']['amazon_s3']['aws_secret_access_key'] = cfg[ 'amazon_s3']['aws_secret_access_key'] k['delivery']['amazon_s3']['path_prefix'] = cfg[ 'amazon_s3']['path_prefix'] for key, value in kwargs.items(): if key == 'azure' and value != None: with open(value, 'r') as ymlfile: cfg = yaml.load(ymlfile) for section in cfg: k['delivery']['azure_blob_storage']['account'] = cfg[ 'azure']['account'] k['delivery']['azure_blob_storage']['container'] = cfg[ 'azure']['container'] k['delivery']['azure_blob_storage']['sas_token'] = cfg[ 'azure']['sas_token'] k['delivery']['azure_blob_storage'][ 'storage_endpoint_suffix'] = cfg['azure'][ 'storage_endpoint_suffix'] k['delivery']['azure_blob_storage']['path_prefix'] = cfg[ 'azure']['path_prefix'] for key, value in kwargs.items(): if key == 'gcs' and value != None: with open(value, 'r') as ymlfile: cfg = yaml.load(ymlfile) for section in cfg: k['delivery']['google_cloud_storage']['bucket'] = cfg[ 'gcs']['bucket'] k['delivery']['google_cloud_storage']['credentials'] = cfg[ 'gcs']['credentials'] k['delivery']['google_cloud_storage']['path_prefix'] = cfg[ 'gcs']['path_prefix'] for key, value in kwargs.items(): if key == 'compression' and value != None: for items in k['tools']: if items.get('tiff_optimize'): items['tiff_optimize']['compression'] = value for key, value in kwargs.items(): if key == 'kernel' and value != None: for items in k['tools']: if items.get('reproject'): items['reproject']['kernel'] = value for key, value in kwargs.items(): if key == 'projection' and value != None: for items in k['tools']: if items.get('reproject'): items['reproject']['projection'] = value bnames = [] for items in dbmath['bandmath']: if items != 'pixel_type': bnames.append(items) rg = len(bnames) if rg < 6: dck = ['b' + str(el) for el in range(1, rg + 1)] #get serialized bands plist = [list(pair) for pair in zip(dck, bnames)] x.field_names = ["Band Number", "Band Name"] for items in plist: i = items[0] f = items[1] x.add_row([i, f]) dbmath['bandmath'][i] = dbmath['bandmath'].pop(f) else: print('You can only use upto 5 bands') sys.exit() if len(dbmath['bandmath']) > 0: k['tools'].append(dbmath) json_data = json.dumps(k) payload = json_data if len(bnames): print('\n') print(x) print('\n') # print('') #print(dbmath) #print(payload) headers = {'content-type': 'application/json', 'cache-control': 'no-cache'} response = requests.request('POST', url, data=payload, headers=headers, auth=(PL_API_KEY, '')) if response.status_code == 202: content = response.json() try: clipboard.copy(str(url) + '/' + str(content['id'])) print('Order created at ' + str(url) + '/' + str(content['id'] + ' and url copied to clipboard')) except Exception: print('Headless Setup: Order created at ' + str(url) + '/' + str(content['id'])) else: print(response.text)
def paste_style(self, combination): """ This creates the style depending on the combination of keys. """ # Stolen from TikZ pt = 1.327 # pixels w = 0.4 * pt thick_width = 0.8 * pt very_thick_width = 1.2 * pt style = {'stroke-opacity': 1} if {'s', 'a', 'd', 'g', 'h', 'x', 'e'} & combination: style['stroke'] = 'black' style['stroke-width'] = w style['marker-end'] = 'none' style['marker-start'] = 'none' style['stroke-dasharray'] = 'none' else: style['stroke'] = 'none' if 'g' in combination: w = thick_width style['stroke-width'] = w if 'h' in combination: w = very_thick_width style['stroke-width'] = w if 'a' in combination: style['marker-end'] = f'url(#marker-arrow-{w})' if 'x' in combination: style['marker-start'] = f'url(#marker-arrow-{w})' style['marker-end'] = f'url(#marker-arrow-{w})' if 'd' in combination: style['stroke-dasharray'] = f'{w},{2*pt}' if 'e' in combination: style['stroke-dasharray'] = f'{3*pt},{3*pt}' if 'f' in combination: style['fill'] = 'black' style['fill-opacity'] = 0.12 if 'b' in combination: style['fill'] = 'black' style['fill-opacity'] = 1 if 'w' in combination: style['fill'] = 'white' style['fill-opacity'] = 1 if {'f', 'b', 'w'} & combination: style['marker-end'] = 'none' style['marker-start'] = 'none' if not {'f', 'b', 'w'} & combination: style['fill'] = 'none' style['fill-opacity'] = 1 if style['fill'] == 'none' and style['stroke'] == 'none': return # Start creation of the svg. # Later on, we'll write this svg to the clipboard, and send Ctrl+Shift+V to # Inkscape, to paste this style. svg = ''' <?xml version="1.0" encoding="UTF-8" standalone="no"?> <svg> ''' # If a marker is applied, add its definition to the clipboard # Arrow styles stolen from tikz if ('marker-end' in style and style['marker-end'] != 'none') or \ ('marker-start' in style and style['marker-start'] != 'none'): svg += f''' <defs id="marker-defs"> <marker id="marker-arrow-{w}" orient="auto-start-reverse" refY="0" refX="0" markerHeight="1.690" markerWidth="0.911"> <g transform="scale({(2.40 * w + 3.87)/(4.5*w)})"> <path d="M -1.55415,2.0722 C -1.42464,1.29512 0,0.1295 0.38852,0 0,-0.1295 -1.42464,-1.29512 -1.55415,-2.0722" style="fill:none;stroke:#000000;stroke-width:{0.6};stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1" inkscape:connector-curvature="0" /> </g> </marker> </defs> ''' style_string = ';'.join( '{}: {}'.format(key, value) for key, value in sorted(style.items(), key=lambda x: x[0])) svg += f'<inkscape:clipboard style="{style_string}" /></svg>' copy(svg, target=TARGET) self.press('v', X.ControlMask | X.ShiftMask)
def em(en): struct = "" for index, item in enumerate(en): print(index, item) struct += f"{index} {item} \n" clipboard.copy(struct)
options.debugMaxDir = -1 options.debugMaxRenderDir = -1 options.debugMaxRenderDetection = -1 options.debugMaxRenderInstance = -1 folder_name = folder_names[task_index] api_output_filename = folder_name_to_combined_output_file[folder_name] filtered_output_filename = path_utils.insert_before_extension(api_output_filename, 'filtered_{}'.format(rde_string)) folder_name_to_filtered_output_filename[folder_name] = filtered_output_filename suspiciousDetectionResults = repeat_detections_core.find_repeat_detections(api_output_filename, None, options) clipboard.copy(os.path.dirname(suspiciousDetectionResults.filterFile)) #%% Manual RDE step ## DELETE THE VALID DETECTIONS ## #%% Re-filtering from api.batch_processing.postprocessing.repeat_detection_elimination import remove_repeat_detections remove_repeat_detections.remove_repeat_detections( inputFile=api_output_filename, outputFile=filtered_output_filename, filteringDir=os.path.dirname(suspiciousDetectionResults.filterFile)
def copylocker(self): clipboard.copy(self.ini.text) b = clipboard.paste()