def choose_location(option_list): """Presents the user with a set of previous locations and an option to enter a custom location. Returns the location as (lat, long), or errors""" options = [ '{0}, {1} ({2}, {3})'.format(elem[1]['city'], elem[1]['region_name'], elem[1]['latitude'], elem[1]['longitude']) for elem in option_list ] questions = [ inquirer.List('location', message='Choose location or enter custom location', choices=options + ['custom']), ] answers = inquirer.prompt(questions) loc = (answers['location']) if loc == 'custom': loc = input('Enter custom location as: `(latitude, longitude)`:\n') try: latlon = literal_eval((loc[loc.find("("):loc.find(")") + 1])) return (str(latlon[0]), str(latlon[1])) except (SyntaxError, ValueError): print('ERROR: Invalid custom location entry') sys.exit(1)
def importAllOrSomething(): ''' All or something ''' chooseAllImportsOrSomething = [ inquirer.List( 'chooseAllImportsOrSomething', message= "{}Do you want to Import Everything or Handpick some things?{}". format(config.BOLD, config.END), choices=[ 'Import Everything', 'Handpick by Content Types and/or Languages', 'Cancel' ], ), ] allOrSomething = inquirer.prompt( chooseAllImportsOrSomething)['chooseAllImportsOrSomething'] if allOrSomething == 'Import Everything': return 'ALL' if 'Handpick' in allOrSomething: return 'HANDPICK' return None
def ask_ffj(): """ Returns a dict with the answers """ l = _list_inputfiles() questions = None if not l: questions = [ inquirer.Path( "ffjfile", message="FFJ input file (absolute path)", path_type=inquirer.Path.FILE, exists=True, ) ] else: questions = [ inquirer.List( "ffjfile", message=".ffj file to use (absolute path)", choices=_list_inputfiles(), ) ] return inquirer.prompt(questions)
def crack(): global user global pwd while True: choices = [] for user, hashdpwd in users.iteritems(): print(user + " : " + hashdpwd) choices.append(user) # user = raw_input("\nWhose password do you want to find ?\n") question = [ inquirer.List('action', message='Whose password do you want to find ?', choices=choices) ] user = inquirer.prompt(question)['action'] try: fileHash = users[user].split('$')[2] except: print("User not found.\n") else: break brut(fileHash)
def associate_main_menu(msg, emp_id, branch_id): display_header(msg, 'ASSOCIATE MENU', 40) sel_op = 11 * ' ' + 'SELECT OPTION' new_o = 12 * ' ' + 'NEW ORDER' view_o = 12 * ' ' + 'VIEW ORDERS' view_inv = 12 * ' ' + 'VIEW INVENTORY' log_o = 12 * ' ' + 'LOG OUT' questions = [ inquirer.List('option', message=sel_op, choices=[new_o, view_o, view_inv, log_o]) ] answers = inquirer.prompt(questions)['option'] if answers == new_o: new_order(None, emp_id) elif answers == view_o: view_orders(None, emp_id, branch_id) elif answers == view_inv: inventory(None, emp_id, branch_id) else: sign_in(None)
def main(): # Enter shares shares = [raw_input('Enter your share: ')] while True: questions = [ inquirer.List( 'share', message='Enter next share', choices=['OK', 'I don\'t have another one'], ), ] answer = inquirer.prompt(questions)['share'] if answer != 'OK': break shares.append(raw_input('Enter your share: ')) # Recover wait = animation.Wait('spinner', 'Generating randomness.. It may take a while.. ') wait.start() message = PlaintextToHexSecretSharer.recover_secret(shares) wait.stop() print('Original message:\n' + message)
def add_item(msg, emp_id, branch_id): logging.debug('Adding an item') press = 11 * ' ' + 'PRESS' done = 12 * ' ' + 'DONE' type = 11 * ' ' + 'ENTER TYPE' count = 11 * ' ' + 'ENTER COUNT' price = 11 * ' ' + 'ENTER PRICE' questions = [ inquirer.Text('type', message=type), inquirer.Text('count', message=count), inquirer.Text('price', message=price) ] answers = inquirer.prompt(questions) row_vals = [answers['type'], answers['count'], answers['price'], branch_id] sjtrophy.insert_item(row_vals) questions = [inquirer.List('done', message=press, choices=[done])] answers = inquirer.prompt(questions) if answers['done'] == done: return
def main(): parser = argparse.ArgumentParser(description='ML dataset management tool') parser.add_argument('--version', action='version', version=('%%(prog)s %s' % VERSION), help='get version') parser.add_argument('install', nargs='*', help='install ML dataset') args = parser.parse_args() if args.install: questions = [ inquirer.List( 'repository', message='what dataset type do you want?', choices=['caltech'], ), ] answers = inquirer.prompt(questions) dataset = DataSet(repository=answers['repository']) dataset.download() else: parser.print_help()
def pay_training_premium(self): training_premium = self.fighter.salary // 6 * self.training_factor if not self.money - training_premium < 0: question = [ inquirer.List('pay_premium', message=f"Would you like to pay ${training_premium:,} to continue training?", choices=['Yes', 'No'], default='Yes', ), ] answer = inquirer.prompt(question) choice = answer['pay_premium'] if choice == 'Yes': self.money -= training_premium self.training_flag = True self.train_fighter() self.training_factor += 1 self.check_money() else: print("--- YOU ARE ALMOST BROKE! ---".center(40)) print("Careful, not enough money left for the training.") print(f"Money in the bank: ${self.money:,}") print("--- YOU ARE ALMOST BROKE! ---\n".center(40))
def main(): """ MAKE SURE YOU RUN THIS IN A TERMINAL. It will break (for example) using PyCharms' default running instance. (If using PyCharm) you can set 'Emulate Terminal' to true. """ options = { 'PNG Everything': png_all, 'Grayscale': store_func(color.convert, color.ColorPresets.grayscale.value), 'Invert': store_func(color.convert, color.ColorPresets.invert.value), 'Custom Color': custom, 'One for All': one_for_all, 'Pixel Blocks': pixel_blocks, 'Copy .mcmeta': rp.copy_mcmeta, 'Shuffle': store_func(color.convert, color.ColorPresets.shuffle.value) } questions = [ inquirer.List("action", message="What do you want to do?", choices=options.keys()), inquirer.Path("to_convert", path_type=inquirer.Path.DIRECTORY, message="What folder do you want to convert?", default="assets/convert/"), inquirer.Path("to_save", path_type=inquirer.Path.DIRECTORY, message="What folder do you want the results to be?", default="assets/done/"), ] answers = inquirer.prompt(questions) rp.to_save = Path(answers['to_save']) rp.to_convert = Path(answers['to_convert']) func = answers['action'] options[func](to_save=rp.to_save, to_convert=rp.to_convert)
def action_create_app(): print(create_app) docker_image_names = get_docker_images_based_on_settings() questions = [ inquirer.Text('app_name', message='Welchen Namen soll die App erhalten?', validate=True) ] if (len(docker_image_names) > 1): questions.append( inquirer.List( 'image', message='Welches Image soll zur Ausführung verwendet werden?', choices=docker_image_names, default=docker_image_names[0])) answers = inquirer.prompt(questions, raise_keyboard_interrupt=True) app_name = answers['app_name'] image = answers['image'] write_content_to_local_settings('App', 'name', app_name) os.makedirs(app_name, exist_ok=True) local_volume = os.path.join(os.getcwd(), app_name) cmd = 'docker run --rm -v {}:/myApp -v /etc/passwd:/etc/passwd:ro -v /etc/group:/etc/group:ro -v /etc/shadow:/etc/shadow:ro -w /myApp -it -u {}:{} {} bash -c \'ionic start {} --no-git\''.format( local_volume, os.getuid(), os.getgid(), image, app_name) print(Fore.CYAN + 'call: ' + cmd) completed = subprocess.run(cmd, shell=True, check=True) # move all created files to the parent directory and remove the temp one tmp_src_path = os.path.join(local_volume, app_name) move_all_files(tmp_src_path, local_volume) os.rmdir(tmp_src_path)
def main(): # search for street questions = [ inquirer.Text("street", message="Enter search string for street") ] answers = inquirer.prompt(questions) # retrieve suggestions for street r = requests.get( "https://service.stuttgart.de/lhs-services/aws/strassennamen", params=answers) data = json.loads(r.text) street_choices = [] for d in data["suggestions"]: street_choices.append((d["value"], d["data"])) # select street questions = [ inquirer.List("street", choices=street_choices, message="Select street") ] results = inquirer.prompt(questions) # search for house number questions = [inquirer.Text("streetnr", message="Enter house number")] results.update(inquirer.prompt(questions)) print("Copy the following statements into your configuration.yaml:\n") print("# waste_collection_schedule source configuration") print("waste_collection_schedule:") print(" sources:") print(" - name: stuttgart_de") print(" args:") for key, value in results.items(): print(f" {key}: {value}")
def remove_plugin(): # Fetch list of installed plugins plugins = PluginsHandler() order = [{ "column": 'name', "dir": 'asc', }] plugin_results = plugins.get_plugin_list_filtered_and_sorted( order=order, start=0, length=None) # Build choice selection list from installed plugins table_ids = {} choices = [] for plugin in plugin_results: choices.append(plugin.get('plugin_id')) table_ids[plugin.get('plugin_id')] = plugin.get('id') # Append a "return" option choices.append('Return') # Generate menu menu remove_plugin_inquirer = inquirer.List( 'cli_action', message="Which Plugin would you like to remove?", choices=choices, ) # Prompt for selection of Plugin by ID selection = inquirer.prompt([remove_plugin_inquirer]) # If the 'Return' option was given, just return to previous menu if selection.get('cli_action') == "Return": return # Remove the selected Plugin by ID plugin_table_id = table_ids[selection.get('cli_action')] plugins.uninstall_plugins_by_db_table_id([plugin_table_id]) print()
def menu(con, foundUser, password): """ The internal menu after the user logs in. The user can choose to see, add or delete passwords. :param con, foundUser, password: db connection, the logged in user, their password :return: None """ q = [ inquirer.List( 'commands', message='What are you interested in?', choices=[ 'see all passwords', 'add a new password', 'delete a password', 'quit' ], ) ] while (True): print("\n") a = inquirer.prompt(q) if a['commands'] == 'see all passwords': dal.get_all_passwords(con, foundUser['id'], password) elif a['commands'] == 'add a new password': site = inquirer.text(message="Enter the name of the website") foundSite = dal.get_site(con, foundUser['id'], site) if (foundSite != None): print("You have already created a password for this website") else: user = inquirer.text(message="Enter username/email") new = dal.add_password(con, site, user, foundUser['id'], password) print("\n", new) elif a['commands'] == 'delete a password': dal.get_all_passwords(con, foundUser['id'], password) to_delete = inquirer.text(message="Enter password id") dal.delete_pass(con, to_delete) elif a['commands'] == 'quit': break
def choose_single_run(clis, fpath, run_id): """ clis are a list of flags provided in the config overrides file. Args: clis: List of clis from the txt file run_id: If known which model to run locally, the run_id of that sweep """ # Check if this has been run before, then we can pick the overrides from # the .hydra folder. Else, will have to manually construct potential # combinations that will be run by hydra run_id_param_dicts = get_sweep_param_from_runs(fpath) if len(run_id_param_dicts) == 0: run_id_param_dicts = get_sweep_param_from_combinations(clis) if len(run_id_param_dicts) == 1: final_run_id, param_dict = run_id_param_dicts[0] assert run_id is None or run_id == final_run_id elif run_id is not None: final_run_id = run_id param_dicts = [el[1] for el in run_id_param_dicts if el[0] == run_id] assert len(param_dicts) == 1, 'run_id not found, or multiple found' param_dict = param_dicts[0] else: # Show options to the user and let her pick run_id_param_dicts_diff = subselect_dict_keys_diff(run_id_param_dicts) print('Choose from: \n' + '\n'.join([str(el) for el in run_id_param_dicts_diff])) qst = [ inquirer.List( 'r', message='Which sweep config to use?', choices=range(len(run_id_param_dicts)), carousel=True, ), ] final_run_id, param_dict = run_id_param_dicts[inquirer.prompt(qst) ['r']] return final_run_id, [f'{key}={val}' for key, val in param_dict.items()]
def play_a_round(dealer, gambler, wagered_amount): """ Play a round of blackjack """ gambler.hand.append(dealer.deck.cards.pop()) dealer.hand.append(dealer.deck.cards.pop()) gambler.hand.append(dealer.deck.cards.pop()) dealer.hand.append(dealer.deck.cards.pop()) gambler_value = count_values(gambler) print("Dealer: " + str(dealer.hand)) while gambler_value < 21: # Player draws print("Gambler: " + str(gambler.hand)) answer = inquirer.prompt([inquirer.List('draw', message='Hit or Stay?', choices=['Hit', 'Stay'])]) if answer["draw"] == "Hit": gambler.hand.append(dealer.deck.cards.pop()) if answer["draw"] == "Stay" or count_values(gambler) > 21: break gambler_value = count_values(gambler) dealer_value = count_values(dealer) # calculate whether to draw while dealer_value < 17 and gambler_value < 21: # Dealer draws dealer.hand.append(dealer.deck.cards.pop()) dealer_value = count_values(dealer) # recalculate print("Dealer: " + str(dealer.hand)) print("Gambler: " + str(gambler.hand)) print(f"gamblers_hand: {gambler_value}, dealers_hand: {dealer_value}") if dealer_value < gambler_value < 22 or dealer_value > 21 >= gambler_value: gambler.money += wagered_amount print(f"You won! You now have ${gambler.money}") elif gambler_value > 21 or gambler_value < dealer_value: gambler.money -= wagered_amount print(f"You lost. You now have ${gambler.money}") if gambler_value == dealer_value: print(f"No one wins. You still have ${gambler.money}")
def where_is_dataset(directory): """ where_is_dataset asks the user where the dataset is located. """ try: folders = [] for root, dirs, files in os.walk(directory): for d in dirs: if d not in IGNORED_FOLDERS_AND_FILES: folders.append(os.path.relpath(os.path.join(root, d), ".")) except Exception as e: logger.error("Can not get a list of folders in current directory.") folders = [] folders = [i for i in folders if not i.startswith(".")] if folders: questions = [ inquirer.List( "dataset_folder", message="Which folder contains the data file?", choices=folders, ) ] else: questions = [ inquirer.Path( "dataset_folder", message="Which folder will you place the data files?", path_type=inquirer.Path.DIRECTORY, ) ] answers = inquirer.prompt(questions) dataset_folder = answers.get("dataset_folder") return dataset_folder
def main(): questions = [ inquirer.List( 'action_tag', message="Choose the VM for restoration: ", choices=opts, ), ] answers = inquirer.prompt(questions) action = answers["action_tag"] if action == "Exit": answer = None while answer not in ("yes", "no"): #answer = input("Enter yes or no: ") answer = raw_input("Enter yes or no to continue [Y/N]? ").lower() if answer == "y": print("%s\n" % action) break elif answer == "n": print("do nothing ...quit ...") break else: print("Please enter yes or no.") else: vm = vm2(action) val = "vm=%s vm2=%s rg=%s rsv=%s loc=%s" % (action, vm, rg, rsv, loc) cmd = "time ansible-playbook -i hosts playbook.yml -e '%s'" % val with open('test.log', 'w') as f: # replace 'w' with 'wb' for Python 3 process = subprocess.Popen(str(cmd), stdout=subprocess.PIPE, shell=True) for c in iter(lambda: process.stdout.read(1), ''): # replace '' with b'' for Python 3 sys.stdout.write(c) f.write(c)
def main(): """ Main() calls the main menu. """ inquire = [ inquirer.List( "Listings", message="Which option do you need?", choices=[ "Newest", "Cheapest", "Zipcode Info", "Deep Search", "SQL Reset", "Quit" ], ), ] inquire = inquirer.prompt(inquire) if inquire["Listings"] == "Newest": newzip = search() filtered = "newest" request(newzip, filtered) main() elif inquire["Listings"] == "Cheapest": cheapzip = search() filtered = "cheapest" request(cheapzip, filtered) main() elif inquire["Listings"] == "Zipcode Info": lookup() main() elif inquire["Listings"] == "Deep Search": deep_search() main() elif inquire["Listings"] == "SQL Reset": truncate() main() elif inquire["Listings"] == "Quit": sys.exit()
def run_tw(): q = [ inquirer.List('which_tw', message='What do you want to find?', choices=['user', 'tweets', 'quit']) ] a = inquirer.prompt(q)['which_tw'] if a == 'quit': print('OK, bye!') quit() elif a == 'user': q_s = [inquirer.Text('username_tw', 'enter the user\'s username: '******'username_tw'] tw = Twitter(TW_BEARER_TOKEN) tw_r = tw.get_user(a_s) print(tw_r) run_tw() elif a == 'tweets': q_s = [inquirer.Text('user_id_tw', 'enter the user\'s ID: ')] a_s = inquirer.prompt(q_s)['user_id_tw'] tw = Twitter(TW_BEARER_TOKEN) tw_r = tw.get_tweets(a_s) print(tw_r) run_tw()
def run_program(): """Run program if usr executes RedList without any option""" while True: af.auto_fin() mode = [ inquirer.List('mode', message="Choose what you ganna do", choices=['Add todo', 'List todo', 'Modify todo', 'Delete todo', 'Show category', 'Quit'], ), ] answers = inquirer.prompt(mode) if answers['mode'] == 'Add todo': at.add_todo() elif answers['mode'] == 'List todo': li.list_main() elif answers['mode'] == 'Modify todo': md.modify_todo() elif answers['mode'] == 'Delete todo': dl.del_todo() elif answers['mode'] == 'Show category': ctg.show_category() elif answers['mode'] == 'Quit': break af.auto_fin()
def professorBirch(): print( "\nYou walk to the Professor's lab, when you get there he isn't here. You see his assitant to the left\n" ) print( "\nProfessor's Assistant: The Professor isn't here, he went into the feild to study wild pokemon. If you are looking for him he is on route 115.\n" ) answer = [ inquirer.List( 'choice', message="Do you want to go looking for the professor?", choices=['Yes', 'No'], ), ] choice = inquirer.prompt(answer)['choice'] if choice == 'Yes': print('You walk out the door and head to the edge of town.') wildPokemon = 'Zigzagoon' wildBattle(wildPokemon) else: print('\nInvalid response\n') professorBirch()
async def get_url(name): """Get URL of the specific event :name: Name of the CTF entered by user :return: A url of to the tasks of the CTF eg: https://ctftime.org/event/683/tasks/ """ spinner = Halo(text="Finding the URL", spinner="moon", color="red") spinner.start() past_ctfs = await past_events() ctfs = get_event(past_ctfs, name) if not ctfs: spinner.fail(colors("No CTF found", "32")) return if len(ctfs) != 1: spinner.stop() tables = [i["name"] for i in ctfs] question = [ inquirer.List("choice", message="Choose one from below?", choices=tables) ] answer = inquirer.prompt(question) # Compare answer with name of CTF to get a link choice = list(filter(lambda ctf: ctf["name"] == answer["choice"], ctfs)) url = ROOT_URL + choice[0]["link"] + "/tasks/" return url spinner.succeed("Got it") return ROOT_URL + ctfs[0]["link"] + "/tasks/"
def training_camp(self): """At the end of the season the manager can boost one stat""" menu = ['Punching', 'Kicking', 'Grappling', 'Speed', 'Endurance'] question = [ inquirer.List('Training Camp', message=f'Choose one stat to boost in training camp ', choices=menu, carousel=True, ), ] answer = inquirer.prompt(question) choice = answer['Training Camp'] improvement = 10 + random.randint(5, 15) if choice == 'Punching': self.fighter.punch += improvement elif choice == 'Kicking': self.fighter.kick += improvement elif choice == 'Grappling': self.fighter.grappling += improvement elif choice == 'Speed': self.fighter.speed += improvement elif choice == 'Endurance': self.fighter.endurance += improvement print(f'Training camp improved {choice} by {improvement}\n')
def play(): global userCan, zombiCan questions = [ inquirer.List( "guess", message="Try to stay alive! Guess a number between [1-5]", choices=["1", "2", "3", "4", "5"]) ] answers = inquirer.prompt(questions) if userCan > 0 or zombiCan > 0: zombiNum = random.randint(1, 5) print("\nZombie rolled " + str(zombiNum)) if zombiNum == int(answers['guess']): zombiCan -= int(answers['guess']) print("YOU HIT " + answers['guess'] + " damage") print("You have " + str(userCan) + " health left. The Zombie has " + str(zombiCan) + " health left.") check() else: userCan -= zombiNum print("OH NO! The zombie slashed you with " + str(zombiNum) + " damage") print("You have " + str(userCan) + " health left. The Zombie has " + str(zombiCan) + " health left.") check()
def edit_inventory(msg, emp_id, branch_id): logging.info('Editing inventory') display_header(msg, 'INVENTORY', 40) sel_op = 11 * ' ' + 'SELECT OPTION' upd_itm = 12 * ' ' + 'UPDATE ITEM' add_itm = 12 * ' ' + 'ADD ITEM' rmv_itm = 12 * ' ' + 'REMOVE ITEM' back = 12 * ' ' + 'BACK' questions = [ inquirer.List('option', message=sel_op, choices=[upd_itm, add_itm, rmv_itm, back]) ] answers = inquirer.prompt(questions)['option'] if answers == upd_itm: update_item(None, emp_id, branch_id) elif answers == add_itm: add_item(None, emp_id, branch_id) elif answers == rmv_itm: remove_item(None, emp_id, branch_id) else: inventory(msg, emp_id, branch_id)
def select_multiple_from(query_message, options): """ Have the user select multiple entries from an Array of Strings. Args: query_message - A query message to display to the user when selecting options - The options to select from """ exit = ' ** Done ** ' selected = [] while True: display_options = [exit] for op in options: if op not in selected: display_options.append(op) questions = [ inquirer.List('s', message=query_message, choices=display_options) ] just_selected = inquirer.prompt(questions)['s'] if just_selected == exit: break else: selected.append(just_selected) return selected
def get_subgroup_from_user(): import inquirer questions = [ inquirer.List( 'subcat', message="Pick a subcategory", choices=[ 'All Quizzes', 'Personality', 'Disney', 'Can We Guess', 'Food', 'Would You Rather', 'Love', 'Trivia' ], ), ] answers = inquirer.prompt(questions) answerdict = { 'All Quizzes': '?page=', 'Personality': '-personality?page=', 'Disney': '-disney?page=', 'Can We Guess': '-can-we-guess?page=', 'Food': '-food?page=', 'Would You Rather': '-would-you-rather?page=', 'Love': '-love?page=', 'Trivia': '-trivia?page=' } return [answers['subcat'], answerdict[answers['subcat']]]
def videoDetail(videoUrl): try: itemPage = bs4(req.get(videoUrl).text, 'html.parser') except expression as e: # print(e) print('=====> request failed/ check network connection!') choices = [ i['aria-label'].split(' ')[-1] for i in itemPage.select('.menu-list .link a') ] downloadLinks = {} for itemLink in itemPage.select('.menu-list .link a'): downloadLinks[itemLink['aria-label'].split(' ')[-1]] = itemLink['href'] questions = [ inq.List( 'quality', message="\U0001F914 Select quality", choices=choices, ), ] answer = inq.prompt(questions) itemPageDownloadLink = downloadLinks[answer['quality']] itemTitle = f"{itemPage.select('#videoTitle')[0].text}-{answer['quality']}" return itemTitle, itemPageDownloadLink
def __add_players(self): """Asks records player names. Args: self (Console): an instance of Console. """ players_list = [] players_list.extend([("NEW PLAYER", "**new**")]) players_list.extend(self._roster.get_roster()) players_list.extend([("BACK TO MENU", "**menu**")]) players = [ inquirer.List( 'selection', message="ADD/REMOVE (Use ↑ and ↓ to select, ENTER to confirm)", choices=players_list, default="NEW PLAYER", carousel=True) ] self.clear_screen() self.__print_logo() selection = inquirer.prompt(players)['selection'] if selection == "**menu**": pass elif selection == "**new**": name = self.__prompt_name() if name: self._roster.add_player(name) else: delete = inquirer.confirm(f"Do you want to remove '{selection}'?", default=True) if delete: self._roster.remove_player(selection) input(f"'{selection}' removed. Press ENTER to continue.")