def start(self): path = get_file(self.config.path) lines = [ line.strip() for line in File(path).read().splitlines() if line ] random.shuffle(lines) lines = lines[:self.config.num] while True: q.clear() self.miss = set() self.okay = set() for num, line in enumerate(lines, 1): q.echo("%s of %s" % (num, len(lines))) self._ask(line) q.hrule() fmiss = File(self.config.path, MISSED_VOCAB) for miss in self.miss: fmiss.append(miss + "\n") q.echo("Results:") q.echo(f"Correct = {len(self.okay)}") q.echo(f"Missed = {len(self.miss)}") q.hrule() if not q.ask_yesno("Retry?", default=False): break if self.miss and q.ask_yesno("Missed only?", default=True): lines = list(self.miss) if q.ask_yesno("Shuffle?", default=True): random.shuffle(lines) lines = lines[:self.config.num]
def build(config): global BUILD BUILD = "release" if not qprompt.ask_yesno("Build release (else debug)?", dft=config['release']): BUILD = "debug" # Build application. call("uic mainwindow.ui >> ui_mainwindow.h") call("qmake") if not os.path.exists(BUILD): os.makedir(BUILD) status = call("make %s" % (BUILD)) try: # Copy over Qt DLLs. for dll in config['qt_dlls']: src = os.path.join(config['qt_bin_dir'], dll) shutil.copy(src, BUILD) # Copy over assets. for ast in config['assets']: shutil.copy(ast, BUILD) # Remove unnecessary files from build dir. for f in os.listdir(BUILD): if any([f.endswith(e) for e in config['build_dir_ext_rm']]): os.remove(os.path.join(BUILD, f)) except: qprompt.alert("File copy failed! Try killing app.") status = 1 # Run app. if status == 0: if qprompt.ask_yesno("Run app?", dft=True): run() else: qprompt.alert("ERROR: Build failed!")
def _add_word_by_close_words(self, new_word_couple): """Add the new word by its close words. The function checks if there are any close words to the current word, and in case there are it asks the user if the new word should be extended as part of them. :new_word_couple: The new word couple to try to add. :returns: True if the word was added to one of its closed words, False otherwise. """ for current_word in self.words: if current_word.is_word_close(new_word_couple): print("The current word is close to the word {}.".format( current_word)) if qprompt.ask_yesno( "Do you want to add this as the same word? [Y/n]", dft=True): is_primary = qprompt.ask_yesno( "is this the primary spelling of the word? [y/N]", dft=False) current_word.extend_word(new_word_couple, is_primary) return True return False
def addPass(): global pragma_input print("This will add a new set of credentials to the database.") website = qprompt.ask_str("Website") username = qprompt.ask_str("Username") password = qprompt.ask_str("Password") print("Here is what will be entered into the database:") print("Website: " + website) #display information so user can confirm that it's correct print("Username: "******"Password: "******"y") #yes/no to confirm if confirm == False: retry = qprompt.ask_yesno("Would you like to retry?") if retry == False: mainMenu() else: addPass() else: conn = sqlcipher.connect('.passman.db') cur = conn.cursor() cur.execute(pragma_input) #add the users input into the database as a new set of credentials cur.execute( "INSERT INTO passwords (WEBSITE, USERNAME, PASSWORD) values ('{}', '{}', '{}')" .format(website, username, password)) conn.commit() cur.close() print("Credentials added successfully!") qprompt.pause() mainMenu()
def test_yesno_1(test): setinput("yes") result = ask_yesno() test.assertTrue(result) setinput("y") result = ask_yesno() test.assertTrue(result) setinput("YES") result = ask_yesno() test.assertTrue(result) setinput("Y") result = ask_yesno() test.assertTrue(result) setinput("n") result = ask_yesno() test.assertFalse(result) setinput("no") result = ask_yesno() test.assertFalse(result) setinput("N") result = ask_yesno() test.assertFalse(result) setinput("NO") result = ask_yesno() test.assertFalse(result)
def update_value(self, value): """ Prompt the user to input a new value, then save the updated config and return to menu. Determines how to prompt the user by finding the value name passed as argument in one of the lists in the type map. :param value: value name to be updated e.g. minwidth """ desc_str = "Enter new {} (currently {})".format(value, self.config['user'][value]) if value in self.type_map[int]: self.config['user'][value] = str(qprompt.ask_int(desc_str)) elif value in self.type_map[float]: self.config['user'][value] = str(qprompt.ask_float(desc_str)) elif value in self.type_map[str]: self.config['user'][value] = qprompt.ask_str(desc_str) elif value in self.type_map[bool]: desc_str += " y/n" if qprompt.ask_yesno(desc_str): self.config['user'][value] = "yes" else: self.config['user'][value] = "no" self.save_config() self.clear_screen() print('Config saved...')
def run_command(self, menu_context): """Run the command that will delete a word from the dictionary. :menu_context: The context of the menu to add the dictionary to. """ if menu_context.get("dictionary", None) is None: print("Menu does not have a dictionary") qprompt.pause() return dictionary = menu_context["dictionary"] word_index_to_remove = safe_ask.safe_ask( qprompt.ask_int, "Insert the index of the word to remove") word_to_remove = dictionary.get_word_by_index(word_index_to_remove) if qprompt.ask_yesno( f"Do you want to remove the word \"{word_to_remove}?\"", dft=False): dictionary.delete_word(word_index_to_remove) print("Word removed") else: print("Word not removed") qprompt.pause()
def scan(scandir, picdirname, overwrite, shrink): """Scan scandir and all subdirectories for pics. Note text will be extracted and a notes file will be created under scandir.""" dirpath = auxly.filesys.Path(scandir) if not dirpath.isdir(): qprompt.fatal("Given path must be existing directory!") if picdirname != dirpath.name: if not qprompt.ask_yesno("Directory not named `pics`, continue?"): sys.exit() create_picnotes(dirpath, confirm=not overwrite, shrink=shrink)
def show_prompt(verchk, pause=True): """Shows the standard prompt for handling version numbers in a project.""" import qprompt verchk.run() if qprompt.ask_yesno("Update version?", dft="n"): newver = qprompt.ask_str("New version string") if newver: verchk.update(newver) verchk.run() if pause: qprompt.pause()
def create_picnotes(dirpath, confirm=True, shrink=False): """Attempts to extract notes from all pics found under the given directory and write them to a file.""" dirpath = op.abspath(dirpath) titlepath = os.sep.join(dirpath.split(os.sep)[-2:]) pics = list(auxly.filesys.walkfiles(dirpath, ".(png|jpg)", recurse=True)) if not pics: qprompt.warn("No pics found under directory!") return pics = sort_pics(pics) qprompt.alert(f"Found {len(pics)} pics found under directory.") doc = auxly.filesys.File(dirpath, "pic_notes.adoc") existing_notes = {} if doc.exists(): existing_notes = parse_picnotes(doc) if confirm: if not qprompt.ask_yesno( f"The `pic_notes.adoc` file already exists with {len(existing_notes)} pic notes found, overwrite it?" ): return doc.empty() qprompt.alert(f"Initialized file `{doc.path}`") doc.appendline(f"= PIC NOTES: `{titlepath}`") doc.appendline(":date: " + datetime.now().strftime("%d %B %Y %I:%M%p")) doc.appendline(":toc:") doc.appendline("") doc.appendline("NOTE: Entries sorted by base filename.") doc.appendline("") count = {'reused': 0, 'scanned': 0} for idx, picpath in enumerate(pics, 1): relpath = op.relpath(picpath, dirpath) msg = f"({idx} of {len(pics)})" if relpath in existing_notes.keys() and auxly.filesys.checksum( picpath) == existing_notes[relpath]['md5']: qprompt.alert(f"{msg} Reusing `{picpath}`.") notes = existing_notes[relpath]['note'] if shrink: attempt_shrink(picpath, notes) line = format_adoc_line(relpath, picpath, notes) count['reused'] += 1 else: notes = qprompt.status(f"{msg} Scanning `{picpath}`...", scan_notes, [picpath]) or "NA" if shrink: attempt_shrink(picpath, notes) line = format_adoc_line(relpath, picpath, notes) count['scanned'] += 1 doc.appendline(line) return count
def delPass(): global pragma_input conn = sqlcipher.connect('.passman.db') cur = conn.cursor() cur.execute(pragma_input) print(pd.read_sql_query("SELECT * FROM passwords", conn)) print("Select the ID of the credentials you wish to DELETE.") selection = qprompt.ask_int("ID") confirm = qprompt.ask_yesno(default="y") if confirm == False: print("Credential removal has been CANCELLED!") print() retry = qprompt.ask_yesno("Retry?", default="y") if retry == True: delPass() else: mainMenu() else: cur.execute("DELETE FROM passwords WHERE ID = '{}'".format(selection)) print("Credentials deleted successfully!") conn.commit() cur.close() qprompt.pause() mainMenu()
def makeissue(repository, fragment, html_url, lineinfo): print Fore.RED + fragment print(Style.RESET_ALL) body = """ %s %s %s """ % (fragment, html_url, lineinfo) if qprompt.ask_yesno("Is this a valid result?", dft="n"): resulttext.append(body) qprompt.pause() qprompt.clear() qprompt.clear()
def makeissue(repository, fragment, html_url, lineinfo): f = open("findings.txt", "a+") print fragment print "\n" body = """ Code Fragment: %s\n Code Location:\n %s Lines:\n %s """ % (fragment, html_url, lineinfo) if qprompt.ask_yesno("Is this a valid result?", dft="n"): f.write(body) qprompt.clear() f.close() qprompt.clear() f.close()
def updatePass(): global pragma_input conn = sqlcipher.connect('.passman.db') cur = conn.cursor() cur.execute(pragma_input) print(pd.read_sql_query( "SELECT * FROM passwords", conn)) #display all passwords so user can easily see its ID print("Select the ID of the credentials you wish to EDIT") try: ID = qprompt.ask_int("ID") #ask user for ID of credential to edit except: qprompt.error("ID NOT FOUND") #error if ID is not found retry = qprompt.ask_yesno( "Retry?") #prompt user to retry or exit to main menu if retry == False: mainMenu() else: updatePass() print( "Credential set selected! What would you like to change?" ) #ask user what about the chosen set of credentials they would like to change qprompt.alert("HINT: Use '?' for a list of options") selection = qprompt.ask_str("Edit", valid=["website", "username", "password"]) if selection.lower() == "website": new = qprompt.ask_str("Enter new value") cur.execute( "UPDATE passwords SET WEBSITE = '{}' WHERE ID = '{}'".format( new, ID)) #updates record with new info elif selection.lower() == "username": new = qprompt.ask_str("Enter new value") cur.execute( "UPDATE passwords SET USERNAME = '******' WHERE ID = '{}'".format( new, ID)) elif selection.lower() == "password": new = qprompt.ask_str("Enter new value") cur.execute( "UPDATE passwords SET PASSWORD = '******' WHERE ID = '{}'".format( new, ID)) conn.commit() cur.close() mainMenu()
def menu(self): """Run the configurator menu allowing user to edit config""" menu = self.create_menu() selection = menu.show(returns="desc") if selection == "Reset config": answer = qprompt.ask_yesno("Are you sure you want to reset your config? y/n") if answer: self.create_default_config() print("Config reset.") else: print('Reset canceled') elif selection == "List settings": self.list_settings() self.clear_screen() self.menu() elif selection == "Exit": pass else: self.update_value(selection) self.menu()
##==============================================================# ## SECTION: Imports # ##==============================================================# import os import subprocess import sys import qprompt sys.path.append("..") sys.dont_write_bytecode = True from _Check_Versions import VERCHK from _Install_Package import generate_readme, cleanup_readme ##==============================================================# ## SECTION: Main Body # ##==============================================================# if __name__ == '__main__': ver = VERCHK.run() if not ver: qprompt.alert("Issue with version info!") exit() if qprompt.ask_yesno("Upload version `%s`?" % (ver)): generate_readme() subprocess.call("python setup.py sdist upload", shell=True) cleanup_readme()
import qprompt sys.path.append("..") sys.dont_write_bytecode = True from _Check_Versions import VERCHK from _Install_Package import generate_readme, cleanup_readme ##==============================================================# ## SECTION: Main Body # ##==============================================================# if __name__ == '__main__': pause = True if len(sys.argv) > 1 and "nopause" == sys.argv[1]: pause = False ver = VERCHK.run() if not ver: qprompt.alert("Issue with version info!") sys.exit(1) if 0 != qprompt.status("Running tests...", sh.silent, [r"..\tests\_Run_Tests.py nopause"]): qprompt.alert("Issue running tests!") sys.exit(1) if qprompt.ask_yesno("Upload version `%s`?" % (ver)): generate_readme() sh.call("python setup.py sdist upload") cleanup_readme() if pause: qprompt.pause() sys.exit(0)
def main(): """ Entry point """ working_directory = getcwd() parser = ArgumentParser(description='') parser.add_argument('-i', '--input_folder', dest='input', metavar='INPUT_DIRECTORY', required=False, default=working_directory, help='Source directory for files renaming. ' 'Current directory by default') args = parser.parse_args() files = [ join(args.input, file) for file in listdir(args.input) if isfile(join(args.input, file)) ] images_files = [file for file in files if is_image(file)] video_files = [file for file in files if is_video(file)] total_files = len(images_files) + len(video_files) widgets = [ FormatLabel('Extracting info'), ' ', Percentage(), ' ', Bar(), ' ', ETA() ] progress_bar = ProgressBar(maxval=total_files, redirect_stdout=True, widgets=widgets) progress_bar.start() images_info_map = {} file_counter = 0 for file in images_files: file_counter += 1 progress_bar.update(file_counter) images_info_map[file] = exif_time_else_creation_time(file) video_files_map = {} for file in video_files: file_counter += 1 progress_bar.update(file_counter) video_files_map[file] = creation_time(file) progress_bar.finish() image_renamings = calculate_renamings(images_info_map) video_renamings = calculate_renamings(video_files_map) image_renamings = dump_renamings(image_renamings) video_renamings = dump_renamings(video_renamings) if ask_yesno(msg='Confirm renaming', dft='y'): rename_files(image_renamings, label='Renaming image files') rename_files(video_renamings, label='Renaming video files')
def edit_scale(pad, verbose): global config rbank = int((pad - 1) / _PADS) rsubpad = pad - (_PADS * rbank) - 1 menu = qprompt.Menu() menu.add("0", "Note") menu.add("1", "Midi-CC") menu.add("2", "Program") ptype = menu.show(msg="Apply Scale to:", returns="desc", dft="0") menu = qprompt.Menu() x = 0 for y in Scale._SCALE_PATTERNS: menu.add(str(x), y) x = x + 1 stype = menu.show(hdr="Pad %d (Bank %s-%d):" % (pad, chr(65 + rbank), rsubpad + 1), msg="Scale", returns="desc") same = None if ptype == "Note": root = qprompt.ask_int("Note", vld=list(range(0, 128)), dft=config[1][rbank][rsubpad]['note']) same = qprompt.ask_yesno(msg="Config all as per Pad %d?" % pad, dft='N') elif ptype == "Midi-CC": root = qprompt.ask_int("Midi-CC Value", vld=list(range(0, 128)), dft=config[1][rbank][rsubpad]['midicc']) else: root = qprompt.ask_int("Program Value", vld=list(range(0, 128)), dft=config[1][rbank][rsubpad]['prog']) count = qprompt.ask_int("Count", vld=[0] + list(range(1, _PTOTAL + 2 - pad)), dft=0) scale = Scale.build_scale(Note.from_midi_num(root), stype) scale_lst = [] for note in scale: scale_lst.append(note.midi_note_number()) if count: while len(scale_lst) < count: root = scale_lst.pop() scale = Scale.build_scale(Note.from_midi_num(root), stype) for note in scale: scale_lst.append(note.midi_note_number()) else: count = len(scale_lst) if pad + count > _PTOTAL: count = _PTOTAL + 1 - pad for note in scale_lst[:count]: bank = int((pad - 1) / _PADS) subpad = pad - (_PADS * bank) - 1 if same and ptype == "Note": config[1][bank][subpad]['trigger'] = config[1][rbank][rsubpad][ 'trigger'] if ptype == "Note": config[1][bank][subpad]['note'] = note elif ptype == "Midi-CC": config[1][bank][subpad]['midicc'] = note else: config[1][bank][subpad]['prog'] = note if verbose: print("Setting Pad %d (Bank %s-%d) to %d (%s)" % (pad, chr(65 + bank), subpad + 1, note, Note.from_midi_num(note))) pad = pad + 1
from qprompt import MenuEntry, show_menu, ask_yesno def foo(): print("foo") def bar(a): print("bar %r" % (a)) val = {'a': 42} entries = [MenuEntry("1", "Item A", foo, None, None)] entries.append(MenuEntry("2", "Item B", bar, None, val)) entries.append(MenuEntry("q", "Quit", None, None, None)) compact = ask_yesno("Use compact menu?") while "q" != show_menu(entries, compact=compact): pass
def edit_scale(pad, verbose): global config rbank = int((pad - 1) / _PADS) rsubpad = pad - (_PADS * rbank) - 1 ptype = config[1][rbank][rsubpad]['type'] if ptype == "BANK": qprompt.error("Pad %d (Bank %s-%d) is configured as a BANK" % (pad, chr(65 + rbank), rsubpad + 1)) return menu = qprompt.Menu() x = 0 for y in Scale._SCALE_PATTERNS: menu.add(str(x), y) x = x + 1 stype = menu.show(hdr="Pad %d (Bank %s-%d):" % (pad, chr(65 + rbank), rsubpad + 1), msg="Scale", returns="desc") root = qprompt.ask_int("Note", vld=list(range(0, 128)), dft=config[1][rbank][rsubpad]['note']) count = qprompt.ask_int("Count", vld=[0] + list(range(1, _PTOTAL + 2 - pad)), dft=0) same = qprompt.ask_yesno(msg="Config all as per Pad %d?" % pad, dft='N') scale = Scale.build_scale(Note.from_midi_num(root), stype) scale_lst = [] for note in scale: scale_lst.append(note.midi_note_number()) if count: while len(scale_lst) < count: root = scale_lst.pop() scale = Scale.build_scale(Note.from_midi_num(root), stype) for note in scale: scale_lst.append(note.midi_note_number()) else: count = len(scale_lst) if pad + count > _PTOTAL: count = _PTOTAL + 1 - pad for note in scale_lst[:count]: bank = int((pad - 1) / _PADS) subpad = pad - (_PADS * bank) - 1 if same and ptype == "NOTE": config[1][bank][subpad]['type'] = config[1][rbank][rsubpad]['type'] config[1][bank][subpad]['channel'] = config[1][rbank][rsubpad][ 'channel'] config[1][bank][subpad]['trigger'] = config[1][rbank][rsubpad][ 'trigger'] config[1][bank][subpad]['aftertouch'] = config[1][rbank][rsubpad][ 'aftertouch'] if same and ptype == "PROG": config[1][bank][subpad]['type'] = config[1][rbank][rsubpad]['type'] config[1][bank][subpad]['channel'] = config[1][rbank][rsubpad][ 'channel'] if ptype == "NOTE": config[1][bank][subpad]['note'] = note else: config[1][bank][subpad]['program'] = note if verbose: print("Setting Pad %d (Bank %s-%d) to %d (%s)" % (pad, chr(65 + bank), subpad + 1, note, Note.from_midi_num(note))) pad = pad + 1
"""This example deletes all PYC files in the project.""" import auxly import qprompt delfunc = lambda is_test: auxly.filesys.delete("..", "\.pyc$", recurse=True, test=is_test) delfiles = delfunc(True) if len(delfiles): print("Files to delete:") print("\n".join([" " + i for i in delfiles])) if qprompt.ask_yesno("OK to delete?"): if delfunc(False) == delfiles: qprompt.alert("Files deleted.") else: qprompt.warn("Some files not deleted!") else: qprompt.alert("No files to delete.") qprompt.pause()
from qprompt import MenuEntry, show_menu, ask_yesno def foo(): print("foo") def bar(a): print("bar %r" % (a)) val = {'a':42} entries = [] entries.append(MenuEntry("1", "Item A", foo, None, None)) entries.append(MenuEntry("2", "Item B", bar, None, val)) entries.append(MenuEntry("q", "Quit", None, None, None)) compact = ask_yesno("Use compact menu?") while "q" != show_menu(entries, compact=compact): pass