def pair(port, host_ip = 'localhost', handshake_msg = 'mysocket.pair'): ''' Establish pickleSocket pair with minimum security (asks user to confirm IP) ''' role = inputUntilValid('Client or Server?', 'cs') s = PickleSocket() if role == 's': s.bind((host_ip, port)) s.listen(1) print(f'Waiting for connection @ {host_ip}:{port}...') cs, addr = s.accept() print('Connection from', addr) if inputUntilValid('Accept?', 'yn') != 'y': cs.close() s.close() raise ConnectionRefusedError cs.shakeHands(handshake_msg) s.close() return 's', cs, addr[0] elif role == 'c': ip = inputChin('IP = ', 'localhost') s.connect((ip, port)) print('Waiting for server to accept...') try: s.shakeHands(handshake_msg) except ConnectionResetError: s.close() raise ConnectionRefusedError return 'c', s, ip
def main(): print('Welcome to Folder Go.') os.chdir(inputChin('Path = ', os.getcwd())) print('In here, there are', len(os.listdir()), 'items.') print('Warning: Some may be overwritten.') print() session()
def chooseRegionOfInterest(folder, duration_of_interest): os.chdir(folder) image = Image.open(duration_of_interest[-1]) x1, y1 = 0, 0 x2, y2 = image.size while True: try: x1, y1, x2, y2 = eval( inputChin('x, y, width, height = ', str((x1, y1, x2, y2)))) except EOFError as e: raise e except Exception as e: print(e) continue image = Image.open(duration_of_interest[-1]) draw = ImageDraw.Draw(image) draw.rectangle((x1, y1, x2, y2), outline='red') del draw print('The cropping preview has been shown in red rectangle.') print('Close the image window to proceed.') image.show() print('Are you happy with', (x1, y1, x2, y2), '?', end=' ') if input('y/n > ').lower() == 'y': break os.chdir('..') return x1, y1, x2, y2
def chooseFolder(): folders = [x for x in os.listdir() if x[:6].isdigit() and os.path.isdir(x)] folders = sorted(folders) print('=' * 16) print('\n'.join(folders)) print('=' * 16) folder = None while folder not in folders: folder = inputChin('Type folder name (or up down arrow keys too): ', '', history=folders) return folder
def chooseDurationOfInterest(folder): files = sorted([x for x in os.listdir(folder) if x.endswith('.jpg')]) print('Total jpg files:', len(files)) boundaries = [] for i, prompt in [(0, 'start = '), (-1, 'end = ')]: dt = datetime.fromtimestamp(parseFilename(files[i])) default = dt.__repr__().split('.', 1)[1] boundaries.append(eval(inputChin(prompt, default)).timestamp()) start, end = boundaries last_timestamp, time_delta = None, None before_start = 0 duration = [] for file in files: now_timestamp = parseFilename(file) if now_timestamp < start: before_start += 1 continue if now_timestamp > end: break if last_timestamp is None: last_timestamp = now_timestamp else: if time_delta is None: time_delta = int( inputChin('time_delta = ', now_timestamp - last_timestamp)) if abs((now_timestamp - last_timestamp) / time_delta - 1) > TIME_FLUCT_TOLERANCE: print('Error! Missing a frame at', datetime.fromtimestamp(last_timestamp + time_delta)) console(locals()) exit() last_timestamp = now_timestamp duration.append(file) taken = len(duration) print(before_start, 'before start,', taken, 'taken, and', len(files) - before_start - taken, 'after end. ') return duration
def selectAudioDevice( pa, in_guesses = ['Line', 'Headset', 'Microphone Array'], out_guesses = ['VoiceMeeter Input'], ): 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, in_guesses) 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, out_guesses) out_i = int(inputChin('select output device: ', default_out)) print() print('Output device:', devices[out_i]) return in_i, out_i
def main(): filename = sysArgvOrInput() outputs = mido.get_output_names() for i, name in enumerate(outputs): print(i, name, sep='\t') port_name = outputs[int(inputChin('> ', 0))] with mido.open_output(port_name) as port: with mido.MidiFile(filename) as mid: print('playing...') try: for msg in mid.play(): print(msg) port.send(msg) except KeyboardInterrupt: print('Stop. ') print('ok')
def present(f): print('Prepareing to present...') mag = np.absolute(f) # mag = mag[1:] # get rid of DC n_bins, w, h, n_colors = mag.shape # this line helps me think max_value = np.max(mag) while True: try: stacking_method = eval('np.' + inputChin('stacking_method = ', 'vstack')) break except EOFError as e: raise e except Exception as e: print(e) print('stacking...') wide_array = (stacking_method(mag) / max_value * 256).astype(np.uint8) wide_image = Image.fromarray(wide_array) wide_image.show() return locals()
def console(namespace={}, prompt='>>> ', use_input=False, fixer=None): if random.randint(0, 5) == 0: print( 'console.console Warning: no support for reassigning module global variables. ' ) else: print('No global. ') history = [] kernal = Kernal(namespace) next(kernal) while True: if use_input: try: command = input(prompt) except EOFError: command = 'exit()' else: try: command = inputChin(prompt, '', history, kernal) except EOFError: command = 'exit()' except KeyboardInterrupt: command = 'print("KeyboardInterrupt")' if not command: continue stripped = command.strip() long_string = stripped.count("'''") % 2 == 1 if long_string or stripped[:1] == '@' or stripped[-1:] in ':({[\\': # `:1` so blank input doesnt trigger IndexError got = command while True: history.append(got) try: got = inputChin('... ', '', history, kernal) except KeyboardInterrupt: command = 'print("KeyboardInterrupt")' break command += '\n' + got if long_string: if got.count("'''") % 2 == 1: break else: if not got: break if fixer is not None: command = fixer(command) if command in ('exit', 'exit()'): try: kernal.send('exit') except StopIteration: return assert False if command == '': continue if command == '\x12': #^R command = 'restart()' if command == 'help': print('Module `console`:') print(__doc__) history.append(command.split('\n')[-1]) result = kernal.send(command) next(kernal) if result is not None: print(result)
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
''' For an NYU person, convert their netID to profile. ''' import webbrowser from interactive import inputChin # MAGIC = 'https://globalhome.nyu.edu/group/people/profile?user=%s' MAGIC = 'https://globalhome.nyu.edu/people/search/%s' def netid2profile(netid): webbrowser.open(MAGIC % netid, new=2) if __name__ == '__main__': print(__doc__) netid = inputChin('netid = ', 'mc7214') netid2profile(netid)
def main(): global release_state, mixer pa = pyaudio.PyAudio() mixer = np.zeros((len(CHORD), PAGE_LEN), DTYPE[0]) 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, ) streamIn.start_stream() kb.hook(onKey) print('go...') try: while streamIn.is_active(): sleep(1) # relay(stream, streamOut) except KeyboardInterrupt: print('Ctrl+C received. Shutting down. ') finally: lock.acquire() release_state = 1 lock.acquire() lock.release() streamOutContainer[0].stop_stream() streamOutContainer[0].close() sleep(.4) # not perfect streamIn.stop_stream() streamIn.close() pa.terminate() print('Resources released. ') kb.unhook_all()
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. ')