def main(): global s s = openPort() print('Enter to accept...') if listen() != b'\r': s.close() input('Aborted! Enter...') sys.exit(1) os.chdir('D:/') op = s.recvObj() while op != 'en': print(op) if op == 'ls': ls() elif op == 'cd': cd() elif op == 'cf': cf() elif op == 'tf': tf() elif op == 'td': td() else: s.close() input('Error: Strange command! ') op = s.recvObj() s.close() input('Session ends. Enter...')
def hub(port=2333, size=2): s = socket.socket() s.bind(('', port)) s.listen(size) queue = Queue() list_recver = [] print('Listening... ') for i in range(size): client, addr = s.accept() print(i + 1, '/', size, ': ', addr, sep='') list_recver.append(Recver(client, queue)) print('Go! ') queue.put(b'OK') for recver in list_recver: recver.start() sender = Sender(list_recver, queue) print('Enter to end...') while listen([b'\r'], .5) is None: pass with sender.condition: sender.do_stop = True while not sender.has_stopped: sender.condition.wait() del sender for recver in list_recver: with recver.condition: recver.do_stop = True while not recver.has_stopped: recver.condition.wait() del recver input('Ended. Enter... ')
def main(): global professional if len(sys.argv) == 2 and sys.argv[1] == '!': print('Professional mode. ') professional = True s = PickleSocket() print('My IP =', gethostbyname(gethostname())) print('or...', getLocalIP()) server = None try: print('Server or Client? s/c') if listen((b's', b'c')) == b's': s.bind(('', port)) s.listen(1) print('Listening...') server = s s, addr = server.accept() print('Connection from', addr) print('Accept? y/n') if listen((b'y', b'n')) == b'n': s.close() s = None input('Aborted. Enter to exit...') sys.exit(1) else: ip = input('Connect to IP: ') print('Connecting...') s.connect((ip, port)) print('Connected! Waiting for response... ') s.shakeHands('One ship python by Daniel Chin. ') esc = b'\x1b' op = b'' while op != esc: if op == b's': send(s) elif op == b'r': #Cannot use ELSE, cuz op maybe b''. recv(s) print() print('Send, receive, or exit? s/r/esc') op = listen((b's', b'r', esc)) finally: if s: s.close() if server: server.close()
def edit(self): if self._smartEntryCheck(): print('"m" to modify current line. ') print('"i" to insert line before current line. ') print('"d" to delete current line. ') print('Enter (\\r) to navigate to the next line. ') print() print('|:', self.now) edited = [] for line in self.dict[self.now].content.split('\n'): print(line + "> ", end='', flush=True) op = listen((b'm', b'i', b'd', b'\r', b'\n')) if op == b'm': print('\r', ' ' * len(line), '\r', end='', flush=True) edited.append(inputWithGen()) elif op == b'i': print('\r', ' ' * len(line), '\r', end='') edited.append(multilineInput()) edited.append(line) print(line) elif op == b'd': print("\r---Line deleted---", ' ' * len(line)) elif op in b'\r\n': edited.append(line) print() cls() edited = '\n'.join(edited) print('Old version: ') print(self.dict[self.now].content) print() print('New version: ') print(edited) print('Save? "y" to save, "n" to discard. >', end='', flush=True) op = listen((b'y', b'n')) if op == b'y': self.dict[self.now].content = edited self.dict[self.now].time = time() cls() print('Entry edited. ') self.unsaved_change = True else: cls() print('Change discarded. ')
def list(self): print('Enter to list by name, "t" to list by time. >') if listen((b't', b'\r')) == b't': sortedDict = self.__sort('last modified') else: sortedDict = self.dict page_pos = 0 for key, entry in sortedDict.items(): print(friendlyTime(entry.time), '|:', key) page_pos += 1 if page_pos == 20: page_pos = 0 if input('Enter to show more... ') != '': break
def copy(src_name=None, dest_name=None): ''' Copies only binary content, leaving meta data. ''' src_name = src_name or input('from: ') dest_name = dest_name or input('to: ') if isfile(dest_name): print('Destination file alreay exists. Overwrite? Y/N') if listen([b'y', b'n']) != b'y': print('Aborted. ') return with open(src_name, 'rb') as src: with open(dest_name, 'wb+') as dest: dest.write(src.read()) print('Copied. ')
def wget(url, filename=None): if filename is None: filename = guessFilename(url) if path.isfile(filename): print(filename, 'already exists. Overwrite? ') if listen('yn') != b'y': print('canceled. ') return print('Downloading...') try: response = urlopen(url) except ValueError: response = urlopen('https://' + url) with open(filename, 'wb+') as f: f.write(response.read()) print('Downloaded to', filename)
def main(): server = MyServer(MyOneServer, PORT) server.start() abspath = os.path.abspath(__file__) dname = os.path.dirname(abspath) os.chdir(dname) potential_ip = getLocalIP() imgs = [] class ShowImgThread(Thread): def __init__(self, img): Thread.__init__(self) self.img = img def run(self): self.img.show() potential_ip = {*potential_ip} - {'192.168.56.1'} # Cisco Anyconnect shit for ip in potential_ip: addr = 'http://%s:%d' % (ip, PORT) try: imgs.append(qrcode.make(addr)) except Exception as e: print('Error 198456', e) print(addr) print('Ctrl+C to stop.') print('Q to display QR code for phone scan.') try: while True: op = listen(timeout=1) if op == b'\x03': raise KeyboardInterrupt elif op == b'q': [ShowImgThread(x).start() for x in imgs] print('Loading image.') elif op == b'\r': print() except KeyboardInterrupt: print('Received ^C. ') finally: server.close() server.join()
def main(): global terminate_flag, sustaining print(f'Press {PEDAL_DOWN.decode()} to sustain. ') print(f'Press {PEDAL_UP .decode()} to release. ') print('Press ESC to quit. ') terminateLock.acquire() pa = pyaudio.PyAudio() streamOutContainer.append(pa.open( format = DTYPE[1], channels = 1, rate = SR, output = True, frames_per_buffer = PAGE_LEN, )) streamIn = pa.open( format = DTYPE[1], channels = 1, rate = SR, input = True, frames_per_buffer = PAGE_LEN, stream_callback = onAudioIn, ) streamIn.start_stream() try: while streamIn.is_active(): op = listen((b'\x1b', PEDAL_DOWN, PEDAL_UP), 2, priorize_esc_or_arrow=True) if op is None: continue if op == b'\x1b': print('Esc received. Shutting down. ') break sustaining = op == PEDAL_DOWN print(sustaining) except KeyboardInterrupt: print('Ctrl+C received. Shutting down. ') finally: print('Releasing resources... ') terminate_flag = 1 terminateLock.acquire() terminateLock.release() streamOutContainer[0].stop_stream() streamOutContainer[0].close() while streamIn.is_active(): sleep(.1) # not perfect streamIn.stop_stream() streamIn.close() pa.terminate() print('Resources released. ')
def portForward(inside_port, inbound_port, afraid=False): ''' Set `afraid` to True to manually accept connections. ''' outServerSocket = socket.socket() outServerSocket.bind(('', inbound_port)) outServerSocket.listen(afraid and 1 or 10) allForwarders = [] allSockets = [] try: while True: print('listening at port %d...' % inbound_port) outSocket, addr = outServerSocket.accept() print('Inbound connection from', addr) if afraid == True: print('Accept? y/n') if listen(['y', 'n']) != b'y': outSocket.close() print('Refused. ') continue inSocket = socket.socket() allSockets.append(outSocket) allSockets.append(inSocket) print('Connecting inside port', inside_port) inSocket.connect(('localhost', inside_port)) allForwarders += bothForward(outSocket, inSocket, addr) print('-= ESTABLISHED =-') print() except KeyboardInterrupt: print('Ctrl+C received. ') finally: print('Closing all sockets...') [x.close() for x in allSockets] outServerSocket.close() print('Joining...') panic = Panic() panic.start() for forwarder in allForwarders: forwarder.join() print('All have joined. ') panic.all_is_fine = True
def recv(s): global last_dir print('Waiting for sender...') basename = s.recvObj() size = s.recvObj() path = { 'Windows': 'D:/downloads/', 'Linux': '/sdcard/download/', 'Darwin': '/' }[platform.system()] print('Default receive path:', path) print('Use it, or change? Enter/c') if listen((b'c', b'\r')) == b'c': if professional: filename = input('path/file.ext = ') else: if Tk: root = Tk() root.withdraw() root.update() filename = filedialog.asksaveasfilename( title='Where to receive', initialdir='D:/', initialfile=basename) else: filename = askSaveWhere(last_dir, initialfile=basename) last_dir = dirname(filename) if filename == '': s.close() input('Error: filename="". Enter to exit...') sys.exit(1) else: filename = path + basename while isfile(filename): base, ext = splitext(filename) base += '2' filename = base + ext recvFile(s.socket, size, filename) print('File received:', filename)
def changePass(self): print('Setting password.') try: mismatch = True password1 = getpass('New password:'******'Repeat:') assert password1 == password2 password3 = getpass('Type in reverse:') assert password1 == ''.join(reversed(password3)) mismatch = False print('Confirm to set new password?') assert listen(['y', 'n']) == b'y' except AssertionError: if mismatch: print('Password mismatch.') print('Abort. Did not set new password.') return False self.salt = urandom(SALT_LEN) self.fernet = self._getFernet(password1, self.salt) self.unsaved_change = True print('Password loaded. ') return True
elif op == 'C': raise CloseOutputNow print('Closing. ') else: print('Choose one from above ', end='') continue break def addToDict(word): with open(packagePath('my_personal_dict_that_is_public_on_github.txt'), 'a') as f: print(word, file=f) print('Added. ') if __name__ == '__main__': print('(i)nteractive, or (a)utomatic, or (c)onsole?') op = listen('iac') if op in b'ia': with open('example.txt', 'r') as inp: with open('example.fix.txt', 'w') as outp: if op == b'i': fixIO(inp, outp, interactive=True) else: fixIO(inp, outp) print('Done! ') else: from console import console console(globals())
def main(): global terminate_flag, sustaining, f, last_pedal print(f'Hold {PEDAL_DOWN.decode()} to sustain. ') # print(f'Press {PEDAL_UP .decode()} to release. ') print('Press ESC to quit. ') terminateLock.acquire() pa = pyaudio.PyAudio() if REALTIME_FEEDBACK: streamOutContainer.append( pa.open( format=DTYPE[1], channels=1, rate=SR, output=True, frames_per_buffer=PAGE_LEN, )) if WRITE_FILE is not None: f = wave.open(WRITE_FILE, 'wb') f.setnchannels(1) f.setsampwidth(4) f.setframerate(SR) streamIn = pa.open( format=DTYPE[1], channels=1, rate=SR, input=True, frames_per_buffer=PAGE_LEN, stream_callback=onAudioIn, ) streamIn.start_stream() try: while streamIn.is_active(): op = listen((b'\x1b', PEDAL_DOWN), PEDAL_DELAY, priorize_esc_or_arrow=True) if op == b'\x1b': print('Esc received. Shutting down. ') break if sustaining: if op is None: if time() - last_pedal > PEDAL_DELAY: sustaining = False print('Pedal up!') else: last_pedal = max(time(), last_pedal) else: if op == PEDAL_DOWN: sustaining = True # last_pedal = time() + .5 last_pedal = time() print('Pedal down!') except KeyboardInterrupt: print('Ctrl+C received. Shutting down. ') finally: print('Releasing resources... ') terminate_flag = 1 terminateLock.acquire() terminateLock.release() if REALTIME_FEEDBACK: streamOutContainer[0].stop_stream() streamOutContainer[0].close() if WRITE_FILE is not None: f.close() while streamIn.is_active(): sleep(.1) # not perfect streamIn.stop_stream() streamIn.close() pa.terminate() print('Resources released. ')
from typofix import * from interactive import listen, multiLineInput from myfile import sysArgvOrInput from os.path import splitext from io import StringIO from console import console def doIt(inFile, outFile): print('(i)nteractive, or (a)utomatic?') if listen('ia') == b'i': fixIO(inFile, outFile, interactive = True) else: fixIO(inFile, outFile) print('open (f)ile, or paste (r)aw text? ') if listen('fr') == b'f': filename = sysArgvOrInput() with open(filename, 'r') as inFile: base, ext = splitext(filename) base += '_fix' with open(base + ext, 'w') as outFile: doIt(inFile, outFile) print('done') else: print('Please paste here and Ctrl + Z: ') inFile = StringIO() outFile = StringIO() raw = multiLineInput(inFile) inFile.seek(0) doIt(inFile, outFile) outFile.seek(0)
# Yield a result for each half of the page yield PageMerge().add(src, viewrect=(0, 0, ratio, 1)).render() yield PageMerge().add(src, viewrect=(ratio, 0, 1 - ratio, 1)).render() if __name__ == '__main__': inp = sys.argv[1:] if inp == []: inpfn = input('path/file.ext = ').strip('"') else: inpfn, = inp outfn = os.path.join(os.path.dirname(inpfn), 'unspread.' + os.path.basename(inpfn)) writer = PdfWriter(outfn) pages = PdfReader(inpfn).pages ratio = input('Ratio (default 0.5) = ') if ratio == '': mySplitpage = splitpage else: ratio = float(ratio) mySplitpage = lambda page: splitpage(page, ratio) jdt = Jdt(len(pages)) for i, page in enumerate(pages): writer.addpages(mySplitpage(page)) jdt.acc() writer.write() jdt.complete() print('start briss? ') if listen(['y', 'n']) == b'y': cmd('briss.lnk "%s"' % outfn)
def doIt(inFile, outFile): print('(i)nteractive, or (a)utomatic?') if listen('ia') == b'i': fixIO(inFile, outFile, interactive = True) else: fixIO(inFile, outFile)
def fixMultiTail(word, interactive, buffer, inFile, following): fixes = [] def addFix(fixed): fixed += right if fixed in fixes: return fixes.append(fixed) clearLine() print(Fore.LIGHTCYAN_EX, end='') print(len(fixes) - 1, ':', fixed) print(Fore.RESET, end='calculating...\r', flush=True) if word.lower() in all_words: return word else: if interactive: saved_pos = inFile.tell() print() print(''.join(buffer), Back.RED, word, Back.RESET, following, inFile.read(PEEK_LEN), sep='') inFile.seek(saved_pos) print() cursor = 0 left = word right = '' for cursor in range(-1, -len(word) - 1, -1): if interactive: fixed = fix(left, False, addFix) else: fixed = fix(left) if fixed == CORRECT: return left + right if not interactive and fixed not in (TOO_LONG, NOT_A_WORD): return fixed + right if word[cursor] not in RIGHT_BORDER: break left = word[:cursor] right = ''.join([RIGHT_BORDER_MAP[x] for x in word[cursor:]]) if not interactive: return word else: clearLine() print('A : Add to my personal dictionary that is public on Github') print('I : Ignore') print('M : Manually fix it') print('C : Close and save the file now') op = None while True: op = input('> ').upper() try: return fixes[int(op)] except (ValueError, IndexError): if op == 'A': addToDict(word) return word elif op == 'I': return word print('Ignored. ') elif op == 'M': manual = inputChin(f'Let {word} be ' + Fore.CYAN, word, cursor=0) print(Fore.RESET, end='') manual_letters = manual.rstrip(SYMBOLS).lower() if manual_letters not in all_words: print( 'Add', Fore.CYAN, manual_letters, Fore.RESET, 'to my personal dictionary that is public on Github? y/n' ) if listen('yn') == b'y': addToDict(manual_letters) else: print(manual_letters, 'is already in the dictionary. ') return manual elif op == 'C': raise CloseOutputNow print('Closing. ') else: print('Choose one from above ', end='') continue break
def main(): global terminate_flag, f, synth print('Press ESC to quit. ') terminateLock.acquire() synth = HarmonicSynth(N_HARMONICS, SR, PAGE_LEN, DTYPE[0], True, DO_SWIPE, .3) pa = pyaudio.PyAudio() info = pa.get_host_api_info_by_index(0) n_devices = info.get('deviceCount') devices = [] in_devices = [] out_devices = [] for i in range(n_devices): info = pa.get_device_info_by_host_api_device_index(0, i) devices.append(info['name']) if info['maxInputChannels'] > 0: in_devices.append([i, info['name']]) elif info['maxOutputChannels'] > 0: out_devices.append([i, info['name']]) print() print('Input Devices:') for i, name in in_devices: print(i, name) default_in = guess(in_devices, ['Headset', 'Microphone Array']) in_i = int(inputChin('select input device: ', default_in)) print() print('Input device:', devices[in_i]) print() print('Output Devices:') for i, name in out_devices: print(i, name) default_out = guess(out_devices, ['VoiceMeeter Input']) out_i = int(inputChin('select output device: ', default_out)) print() print('Output device:', devices[out_i]) streamOutContainer.append( pa.open( format=DTYPE[1], channels=1, rate=SR, output=True, frames_per_buffer=PAGE_LEN, output_device_index=out_i, )) streamIn = pa.open( format=DTYPE[1], channels=1, rate=SR, input=True, frames_per_buffer=PAGE_LEN, stream_callback=onAudioIn, input_device_index=in_i, ) if WRITE_FILE is not None: f = wave.open(WRITE_FILE, 'wb') f.setnchannels(1) f.setsampwidth(4) f.setframerate(SR) streamIn.start_stream() print('go!') try: while streamIn.is_active(): op = listen(b'\x1b', priorize_esc_or_arrow=True) if op == b'\x1b': print('Esc received. Shutting down. ') break except KeyboardInterrupt: print('Ctrl+C received. Shutting down. ') finally: print('Releasing resources... ') terminate_flag = 1 terminateLock.acquire() terminateLock.release() streamOutContainer[0].stop_stream() streamOutContainer[0].close() if WRITE_FILE is not None: f.close() while streamIn.is_active(): sleep(.1) # not perfect streamIn.stop_stream() streamIn.close() pa.terminate() print('Resources released. ')