def AddAdvice(): clear() Add = SlidePrompt([ Input("Marca del teléfono: ", default="", word_color=colors.foreground["yellow"]), Bullet("Sistema operativo:", choices=["Android", "IOS"], margin=2, background_on_switch=colors.background["white"], word_on_switch=colors.foreground["black"]), Numbers("RAM: ", word_color=colors.foreground["yellow"], type=int), Input("CPU: ", default="", word_color=colors.foreground["yellow"]), Numbers("Números de ventas en el año: ", word_color=colors.foreground["yellow"], type=int) ]) actualDevice = Add.launch() deviceDic = { 'brand': actualDevice[0][1], 'os': actualDevice[1][1], 'ram': actualDevice[2][1], 'cpu': actualDevice[3][1], 'sales': actualDevice[4][1] } devices.append(deviceDic)
def __init__(self, fileName): self.ing_reader = ING_Reader(fileName) operator = ParticipantsOperator('categories.csv') participants = operator.get_participants() for transaction in self.ing_reader.getTransactions(): if transaction.category == 'unknown': if transaction.party in participants: transaction.set_category(participants[transaction.party]) else: print(transaction) #print(transaction.get_meta()) choices = list(operator.get_categories()) choices.append('NEW*') if os.name == 'nt': category = None while category not in choices: if category is not None: print ("Incorrect Category! Use NEW* to add a new category!") category = input("Set category [{}]:".format(sorted(choices))) if category == 'NEW*': category = input("Set new category: ") break else: cli = Bullet(prompt = "Choose category: ", choices = sorted(choices)) # Create a Bullet or Check object category = cli.launch() # Launch a prompt if category == 'NEW*': new_cli = Input(prompt = "Add new category: " ) # Create a Bullet or Check object category = new_cli.launch() # Launch a prompt transaction.set_category(category) operator.add_participant(transaction.party, category) operator.save() self.ing_reader.save()
def create_module(node): """ Create a new module and return (module data, name) """ (loras, hackrfs, unknowns) = node_get_moduleinfo(node) names_in_use = [*loras.keys(), *hackrfs.keys(), *unknowns.keys()] modulename = "" while modulename == "" or modulename in names_in_use: if modulename in names_in_use: print("Module %s already exists." % modulename) modulename = Input("🏷️ Name of the module: ").launch() mtype = Bullet(prompt="Module Type", choices=["LoRa", "HackRF"], **default_props).launch() if mtype == "LoRa": conntype = prompt_conntype() return ({ **conntype, "module": "LoRa", }, modulename) else: print(''' You need to specify a temporary directory to store your capture files. Note that the directory will not be cleaned automatically. So you may either use a local path (like tmp/hackrf) to keep your files or the global temprorary directory to remove them if space is low (/tmp/) ''') capture_dir = Input("📁 Directory for capture files: ").launch() return ({ "capture_dir": capture_dir, "module": "HackRF", }, modulename)
def main(): account_input = Input('请输入你的学号:') password_input = Password('请输入你的密码:') slide = SlidePrompt([account_input, password_input]) res = slide.launch() account = res[0][1] password = res[1][1] student = Student(account, password) port_confirm_input = YesNo('是否自定义教务系统端口?') slide = SlidePrompt([port_confirm_input]) res = slide.launch() port_confirm = res[0][1] if port_confirm: port_input = Input('请输入你要自定义的端口:') slide = SlidePrompt([port_input]) res = slide.launch() student.urp.port = res[0][1] while True: choices_list = ['成绩导出', '一键评教', '退出'] choice_input = Bullet('请选择你要进行操作:', choices=choices_list, margin=1) slide = SlidePrompt([choice_input]) res = slide.launch() choice = res[0][1] if choice == choices_list[0]: student.export_grade() elif choice == choices_list[1]: student.judge_all() elif choice == choices_list[2]: exit_confirm_input = YesNo('确认退出?') slide = SlidePrompt([exit_confirm_input]) res = slide.launch() if res[0][1]: sys.exit()
def take_action(self, parsed_args): se = self.app.secrets se.requires_environment() se.read_secrets_and_descriptions() group = parsed_args.group groups = se.get_groups() # Default to using a group with the same name as the environment, # for projects that require a group of "global" variables. if group is None: group = str(self.app.secrets) if group not in groups: raise RuntimeError((f"[!] group '{group}' does not exist in " f"environment '{str(se)}'" ) if parsed_args.group is not None else "[!] please specify a group with '--group'") descriptions = se.read_descriptions(group=group) variables = [item['Variable'] for item in descriptions] args = parsed_args.arg for arg in args: if arg not in variables: raise RuntimeError( f"[!] variable '{arg}' does not exist in group '{group}'") if not parsed_args.force: if not stdin.isatty(): raise RuntimeError( "[-] must use '--force' flag to delete a secret") else: prompt = f"Type the name '{arg}' to confirm: " cli = Input(prompt, default="", word_color=colors.foreground["yellow"]) confirm = cli.launch() if confirm != arg: self.logger.info('[-] cancelled deleting secret') return descriptions = [ item for item in descriptions if item['Variable'] != arg ] se.delete_secret(arg) if len(descriptions) == 0: paths = [se.get_descriptions_path(group=group)] if parsed_args.mirror_locally: paths.append( se.get_descriptions_path( root=os.getcwd(), group=group, )) for path in paths: safe_delete_file(path) self.logger.info("[+] deleted empty group '%s' (%s)", group, path) else: se.write_descriptions( data=descriptions, group=group, mirror_to=os.getcwd() if parsed_args.mirror_locally else None) se.write_secrets()
def prompt_conntype(): """ Prompts for a connection type of a LoRa module """ conntype = Bullet(prompt="How is the module connected?", choices=["Serial (UART)", "SPI"], **default_props).launch() if conntype == "SPI": print(''' Select the SPI device to use. If you have for example a Raspberry Pi, this will usually be /dev/spidev0.0 or /dev/spidev0.1 depending on the CS pin you use. (Have a look at the pinout for that ''') dev = Input("🔌 SPI device to use: ").launch() print(''' Select the variant for the hardware configuration. Analog to the firmware for external MCUs, this variant must match the node's architecture (eg. arm or x86) and the wiring of the LoRa module to the node. ''') firmwares = { "Raspberry Pi with Dragino LoRa/GPS HAT": "native-raspi", } firmware = Bullet(prompt="Which firmware variant should be used?", choices=list(firmwares.keys()), **default_props).launch() return {"conntype": "spi", "dev": dev, "firmware": firmwares[firmware]} else: print(''' Select the UART device to use. For a USB-to-Serial adapter, this is usually something like /dev/ttyUSB0, for an MCU with integrated USB support, you might see something like /dev/ttyACM0, and for a physical serial interface of your host (serial port on the Raspberry Pi GPIO header) it's often /dev/ttyS0. ''') dev = Input("🔌 UART device to use: ").launch() print(''' Select the firmware to use on the external MCU. Connect all external devices before you run "chirpotle.sh deploy", then the framework will take care of flashing the firmware automatically. If you want to do that manually, select "None". ''') firmwares = { "LoPy 4 via UART": "lopy4-uart", "LoRa Feather M0": "lora-feather-m0", } firmware = Bullet( prompt="Which firmware should be flashed to the MCU?", choices=[*firmwares.keys(), "None"], **default_props).launch() mod = {"conntype": "uart", "dev": dev} if firmware in firmwares.keys(): mod["firmware"] = firmwares[firmware] return mod
def main(): default_aws_dir = pathlib.Path().home() / '.aws' default_aws_config = default_aws_dir / 'config' default_aws_creds = default_aws_dir / 'credentials' current_mfa_prompt = Input(prompt='Please input your current mfa code: ') current_mfa = current_mfa_prompt.launch() profile_config = get_profile(default_aws_config) aws_session = get_session(mfa_serial_str=profile_config['mfa_serial'], mfa_code=current_mfa) write_setup(aws_cred_path=default_aws_creds, temp_creds=aws_session, provisioning_profile=profile_config)
def launch(self): subprocess.run(["clear"]) print_message(f"Variable Name: {self.setting_name}\n", fg="bright_magenta", bold=True) print_message(f"Current Value: {self.current_setting}\n", fg="bright_yellow", bold=True) if not yes_no_prompt(prompt="\nChange current setting?"): return Result.Ok(self.exit_menu) user_confirmed, new_value = False, None while not user_confirmed: subprocess.run(["clear"]) prompt = f"Enter a new value for {self.setting_name}:\n" new_value = Input( prompt, word_color=colors.foreground["default"]).launch() result = self.confirm_new_value(new_value) if result.failure: return Result.Ok(self.exit_menu) user_confirmed = result.value result = self.dotenv.change_value(self.setting_name, new_value) if not self.restart_required: return result print_message(RESTART_WARNING, fg="bright_magenta", bold=True) pause(message="Press any key to continue...") exit(0)
def run_install(app_path=None, jetzt_metadata=None, jetzt_metadata_file='jetzt_metadata.json'): prompt_pkg_name = 'What package from PyPI would you like to install (single pkg)? ' prompt_dep_type = 'PROD or DEV dependency? ' cli = SlidePrompt( [ Input(prompt_pkg_name, word_color=colors.foreground["yellow"]), Bullet(prompt_dep_type, choices=["PROD", "DEV"], bullet=" >", margin=2, bullet_color=colors.bright(colors.foreground["cyan"]), background_on_switch=colors.background["black"], word_color=colors.foreground["white"], word_on_switch=colors.foreground["white"]), ] ) result = cli.launch() cli.summarize() pkg_name = '' dep_type = 'PROD' for result_item in result: key, value = result_item if key == prompt_pkg_name: pkg_name = value elif key == prompt_dep_type: dep_type = value if (len(pkg_name) < 1): sys.exit(Fore.RED + 'The PyPI package name to be installed should contain at least one character.') subprocess.call(f'source {app_path}/bin/install_pypi_pkg.sh "{pkg_name}" "{dep_type}" "{app_path}"', shell=True) sys.exit()
def run_cli() -> Options: """ Run CLI and return options """ cli = VerticalPrompt( [ Input("Project Name? ", default="latex_project", strip=True), Bullet( "Which template to use?", choices=[ t for t in os.listdir("./latex_up/templates") if "." not in t ], ), Check( "Include lists? (Press Space to check/uncheck)", ["Enumerate", "Itemize", "Description"], ), Check( "Choose other latex structures to include. (Press Space to check/uncheck)", ["Graphic", "Bibtex", "Equation"], ), ], spacing=1, ) result = cli.launch() return Options.from_args(result[0][1], result[1][1], *result[2][1], *result[3][1])
def get_builder_aws_ebs() -> packer_builder: ''' build the aws builder section ''' section_meta('starting', getframeinfo(currentframe()).function) variable_dictionary = { 'source_ami': "{{ user `kali_aws_ami` }}", 'region': "{{ user `aws_region` }}", 'ssh_username': "******", 'instance_type': "t2.medium", 'ami_name': "Kali Linux (Standard)", "ami_users": [""], "force_deregister": "true", "force_delete_snapshot": "true" } auth_prompt = Bullet(prompt='Choose from the items below: ', choices=['AWS Profile', 'AWS Access Key']) auth_type = auth_prompt.launch() if auth_type == 'AWS Profile': profile_prompt = Input( prompt='Please input the profile you would like to use: ') current_profile = profile_prompt.launch() variable_dictionary.update({'profile': "{}".format(current_profile)}) elif auth_type == 'AWS Access Key': variable_dictionary.update({ 'access_key': "{{ user `aws_access_key` }}", 'secret_key': "{{ user `aws_secret_key` }}" }) else: print('unknown auth type: {}'.format(auth_type)) aws_ebs_builder = packer_builder.AmazonEbs().from_dict( 'AmazonEBS', d=variable_dictionary) # TODO: fixin base package to accept string aws_ebs_builder_dict = aws_ebs_builder.to_dict() aws_ebs_builder_dict['ami_users'] = "{{user `ami_users`}}" section_meta('exiting', getframeinfo(currentframe()).function) return aws_ebs_builder_dict
def node_edit(conf, ctrl, nodename): """ Edit a node within a controller config :param conf: The overall configuration (used to retrieve node profiles) :param ctrl: The controller config :param nodename: The node name to edit """ origname = nodename try: nodedata = {k: v for (k, v) in ctrl[nodename].items()} running = True while running: print_header("Edit Node") print(''' You can edit the node configuration here. The name is a local name to refer to the node within scripts, the hostname is used to find the node in the network and the profile defines which hardware is connected to the remote node. ''') choices = [ "🏷️ Name: %s" % nodename, "⚙️ Profile: %s" % nodedata['conf'].replace( "/opt/chirpotle/nodeconf/", "").replace(".conf", ""), "🖥️ Host: %s" % nodedata['host'], "Delete Node", "Go back" ] res = Bullet(choices=choices, **default_props).launch() if res == choices[-1]: # go back return (nodename, nodedata) elif res == choices[-2]: # delete node ctrl.remove_section(origname) return (None, None) elif res == choices[0]: # name name = "" while name == "" or (name != origname and name in ctrl.sections()): if name != "": print("Name %s already exists in config") name = Input("🏷️ Enter new node name: ").launch() nodename = name elif res == choices[1]: # profile nodedata['conf'] = select_node_config( conf, "⚙️ Select new profile:") elif res == choices[2]: # host nodedata['host'] = Input( "🖥️ Enter new hostname or IP: ").launch() except KeyboardInterrupt: return (None, None)
def main(): print("Let's create a Module!") cli = VerticalPrompt( [Input("Module Name (with spaces): "), Input("First Command: ")]) result = cli.launch() name = "".join([word.capitalize() for word in result[0][1].split(' ')]) command = result[1][1] # Create module folder path = os.path.join("iota", "modules", name) os.mkdir(path) # Create init Path(os.path.join(path, '__init__.py')).touch() # Create basic config file build_config(name, command, path) # Create Module Class file build_module(name, path)
def continue_user(): user_input = VerticalPrompt([ Input("username: "******"password: "******"*", indent=0), ], spacing=0) user_login = user_input.launch() print(user_login[0][1])
def run_scaffold(jetzt_home=None, app_path=None, jetzt_metadata=None, jetzt_metadata_file='jetzt_metadata.json'): cli = SlidePrompt( [ Input("What is the name of your project? ", word_color=colors.foreground["yellow"]), Bullet("What kind of project would you like to scaffold? ", choices=["Python - [Blank]", "Python - Flask", "Python - Jupyter"], bullet=" >", margin=2, bullet_color=colors.bright(colors.foreground["cyan"]), # background_color=colors.background["black"], background_on_switch=colors.background["black"], word_color=colors.foreground["white"], word_on_switch=colors.foreground["white"]), ] ) result = cli.launch() cli.summarize() project_name = '' project_type = '' for result_item in result: key, value = result_item if key == 'What is the name of your project? ': project_name = value elif key == 'What kind of project would you like to scaffold? ': project_type = value # Make project_name safe project_name = "".join([c for c in project_name if c.isalpha() or c.isdigit() or c == '_' or c == '-']).rstrip() ''' There should be at least one character in the project (directory) name. ''' if (len(project_name) < 1): sys.exit(Fore.RED + 'The project_name should contain at least one character.') ''' Let's validate paths. ''' if os.path.exists(jetzt_home) and os.path.isdir(jetzt_home): os.chdir(jetzt_home) ''' Again, let's make sure we do not try to create a project dir, which already exists. ''' if os.path.exists(project_name): sys.exit(Fore.RED + 'The project directory already exists.') # Create project root os.mkdir(project_name) jetzt_metadata['project_name'] = project_name jetzt_metadata['project_type'] = project_type dump_jetzt_metadata(jetzt_metadata, f"{project_name}/{jetzt_metadata_file}") ''' Call a shell script to install packages etc. ''' subprocess.call(f'source {app_path}/bin/jetzt_scaffold.sh {jetzt_home} {project_name} "{project_type}" "{app_path}"', shell=True) print(Fore.GREEN + 'Scaffold complete.') print('To jump in the new environment, run:') print(Fore.GREEN + f'cd {jetzt_home}/{project_name} && source venv/bin/activate') sys.exit()
def get_description(name=None, defaults=None): """Prompt user for description fields and return results.""" new_description = dict() # Variable name is required (obviously) new_description['Variable'] = defaults['Variable'] # Variable type is required (obviously) original_type = defaults.get('Type', None) type_hint = "" if original_type is None else f" [was '{original_type}']" new_description['Type'] = psec.utils.prompt_options_list( prompt=f"Variable type{type_hint}: ", default=original_type, options=[item['Type'] for item in SECRET_TYPES]) # Prompt (also serves as description) is required prompt = ("Descriptive string to prompt user when " "setting value: ") cli = Input(prompt, default=defaults.get('Prompt'), word_color=colors.foreground["yellow"]) result = cli.launch() new_description['Prompt'] = result # Alternative option set is (no pun intended) optional if new_description['Type'] in ['string']: prompt = "Acceptable options from which to chose: " cli = Input(prompt, default=defaults.get('Options'), word_color=colors.foreground["yellow"]) result = cli.launch() # TODO(dittrich): BUG or ISSUE in waiting. # Items in an Options list can't end in '.*' without # causing confusion with ',*' wildcard feature. # Maybe switch to using '|' for alternaives instead? if '.*' in result: if result == '.*': msg = "[-] '.*' is not valid: did you mean '*'?" else: msg = ("[-] options list items can't have '.*' " "wildcards: did you mean to end with ',*'?") raise RuntimeError(msg) new_description['Options'] = result # Environment variable export alternative optional prompt = "Environment variable to export: " cli = Input(prompt, default=defaults.get('Export', ' '), word_color=colors.foreground["yellow"]) result = cli.launch() if result not in [' ', '', None]: new_description['Export'] = result print('') return new_description
def take_action(self, parsed_args): se = self.app.secrets se.requires_environment() se.read_secrets_descriptions() group = parsed_args.group groups = se.get_groups() choice = None if parsed_args.group is not None: choice = parsed_args.group elif not (stdin.isatty() and 'Bullet' in globals()): # Can't involve user in getting a choice. raise RuntimeError('[-] no group specified to delete') else: # Give user a chance to choose. choices = ['<CANCEL>'] + sorted(groups) cli = Bullet(prompt="\nSelect group to delete:", choices=choices, indent=0, align=2, margin=1, shift=0, bullet="→", pad_right=5) choice = cli.launch() if choice == "<CANCEL>": self.logger.info('[-] cancelled deleting group') return # Group chosen. Now do we need to confirm? if not parsed_args.force: if not stdin.isatty(): raise RuntimeError( '[-] must use "--force" flag to delete a group.') else: prompt = f"Type the name '{choice}' to confirm: " cli = Input(prompt, default="", word_color=colors.foreground["yellow"]) confirm = cli.launch() if confirm != choice: self.logger.info('[-] cancelled deleting group') return group_file = se.get_descriptions_path(group=group) if not os.path.exists(group_file): raise RuntimeError(f"[-] group file '{group_file}' does not exist") # Delete secrets from group. secrets = se.get_items_from_group(choice) for secret in secrets: se.delete_secret(secret) # Delete group descriptions. safe_delete_file(group_file) self.logger.info("[+] deleted secrets group '%s' (%s)", choice, group_file)
def take_action(self, parsed_args): self.LOG.debug('deleting group') self.app.secrets.requires_environment() self.app.secrets.read_secrets_descriptions() groups = self.app.secrets.get_groups() choice = None if parsed_args.group is not None: choice = parsed_args.group elif not (stdin.isatty() and 'Bullet' in dir()): # Can't involve user in getting a choice. raise RuntimeError('[-] no group specified to delete') else: # Give user a chance to choose. choices = ['<CANCEL>'] + sorted(groups) cli = Bullet(prompt="\nSelect group to delete:", choices=choices, indent=0, align=2, margin=1, shift=0, bullet="→", pad_right=5) choice = cli.launch() if choice == "<CANCEL>": self.LOG.info('cancelled deleting group') return # Group chosen. Now do we need to confirm? if not parsed_args.force: if not stdin.isatty(): raise RuntimeError( '[-] must use "--force" flag to delete a group.') else: prompt = 'Type the name "{}" to confirm: '.format(choice) cli = Input(prompt, default="", word_color=colors.foreground["yellow"]) confirm = cli.launch() if confirm != choice: self.LOG.info('cancelled deleting group') return descriptions_path = self.app.secrets.descriptions_path() group_file = os.path.join(descriptions_path, '{0}.yml'.format(choice)) if not os.path.exists(group_file): raise RuntimeError(('Group file "{}" does not ' 'exist').format(group_file)) # Delete secrets from group. secrets = self.app.secrets.get_items_from_group(choice) for secret in secrets: self.app.secrets.delete_secret(secret) # Delete group descriptions. os.unlink(group_file) self.LOG.info('[+] deleted secrets group "{0}"'.format(choice))
def get_string(prompt, default_string=" "): cli = SlidePrompt([ Input(prompt, default=default_string, word_color=colors.foreground["yellow"]), ]) result = cli.launch() for p, ans in result: if p == prompt: if ans == default_string: return False return ans
def node_list(conf): """ List node configurations and pick one for edit """ running = True icon = "⚙️ Node Profile: " while running: try: choices = [ *[icon + c for c in conf['node'].keys()], "➕ Create new node profile", "Go back" ] print_header("Node Profiles") print(''' Here you see the currently available node profiles. A node profile describes the hardware that is attached to a single node, i.e. which external MCUs are connected to the node, which ports and firmware they use etc. Within a configuration, multiple nodes can use the same profile, and node profiles can be shared between configurations (e.g. if you want to have configs with a subset of your nodes). ''') res = Bullet(choices=choices, **default_props).launch() if res == choices[-2]: # New config name = "" while name == "" or name in conf['node'].keys(): if name != "": print("Node profile %s already exists." % name) name = Input( "\nEnter a name for the node profile: ").launch() new_conf = configparser.ConfigParser() new_conf["TPyNode"] = { "module_path": "/opt/chirpotle/modules/", "logfile": "/var/log/tpynode.log", "pidfile": "/var/run/tpynode.pid", "host": "0.0.0.0", "port": "42337", } edited_conf, edited_name = node_edit(conf, new_conf, name) if edited_conf is not None: conf['node'][name] = edited_conf elif res == choices[-1]: # go back running = False else: confname = res[len(icon):] (editres, newname) = node_edit(conf, copy_conf(conf['node'][confname]), confname) if editres is not None: del conf['node'][confname] if newname is not None: conf['node'][newname] = editres except KeyboardInterrupt: running = False
def take_action(self, parsed_args): self.LOG.debug('[*] deleting environment') choice = None if parsed_args.environment is not None: choice = parsed_args.environment elif not (stdin.isatty() and 'Bullet' in globals()): # Can't involve user in getting a choice. raise RuntimeError('[-] no environment specified to delete') else: # Give user a chance to choose. environments = os.listdir(self.app.secrets.secrets_basedir()) choices = ['<CANCEL>'] + sorted(environments) cli = Bullet(prompt="\nSelect environment to delete:", choices=choices, indent=0, align=2, margin=1, shift=0, bullet="→", pad_right=5) choice = cli.launch() if choice == "<CANCEL>": self.LOG.info('[-] cancelled deleting environment') return # Environment chosen. Now do we need to confirm? e = psec.secrets.SecretsEnvironment(choice) env_path = e.environment_path() if not parsed_args.force: if not stdin.isatty(): output = psec.utils.atree(env_path, outfile=None, print_files=True) raise RuntimeError( "[-] must use '--force' flag to delete an environment.\n" "[-] the following will be deleted: \n" f"{''.join([line for line in output])}" ) else: prompt = f"Type the name '{choice}' to confirm: " cli = Input(prompt, default="", word_color=colors.foreground["yellow"]) confirm = cli.launch() if confirm != choice: self.LOG.info('[-] cancelled deleting environment') return # We have confirmation or --force. Now safe to delete. # TODO(dittrich): Use safe_delete_file over file list shutil.rmtree(env_path) self.LOG.info(f"[+] deleted directory path '{env_path}")
def launch(self): for section in self.configuration["config_sections"]: utils.cprint("We are now configuring {} section".format(section), color=colors.foreground["default"]) self.results[section] = self.rlaunch(section, 1) utils.cprint("You finish all the configurations, here is your full configurations", color=colors.foreground["default"]) utils.cprint(json.dumps(self.results, indent=2), color=colors.foreground["default"]) while True: ui = Input("Where are you going to save the configuration? ", word_color=colors.foreground["yellow"], default="configurations/default.json") path = ui.launch() if path: path_dir = os.path.dirname(path) if os.path.exists(path_dir): with open(path, 'w') as fout: fout.write(json.dumps(self.results, indent=2)) break else: utils.cprint("The dir `{}` does not exist".format(path_dir)) else: utils.cprint("Invalid input") utils.cprint("Done!")
def gif_path_option(image_filepath): path = Path(image_filepath) default_choice = YesNo( # Prompt for the user to see prompt="Do you want to use the default folder {0} ? ".format( path.parent), ) default = default_choice.launch() if default: return str(path.parent) else: while True: folder_choices = Input( # Prompt for the user to see prompt="What is the folder you want to use for the ASCII gif? ", strip=True) menu = folder_choices.launch() if os.path.exists(menu): return menu else: msg = f'Error: The folder \'{menu}\' doesnt seem to exists' print(color.error(msg))
def ctrl_list(conf): """ List controller configurations and pick one for edit """ running = True icon = "📝 Configuration: " while running: try: choices = [ *[icon + c for c in conf['ctrl'].keys()], "➕ Create new configuration", "Go back" ] print_header("Controller Configurations") print(''' This list shows all available configurations. Configurations are used to specify which nodes are available in ChirpOTLE scripts or the interactive shell. You can use the --conf parameter for various chirpotle commands to select which configuration should be used. ''') res = Bullet(choices=choices, **default_props).launch() if res == choices[-2]: # New config name = "" while name == "" or name in conf['ctrl'].keys(): if name != "": print("Configuration %s already exists." % name) name = Input( "\nEnter a name for the new configuration: ").launch() new_conf = configparser.ConfigParser() new_conf["DEFAULT"] = { "port": 42337, "tmpdir": "/tmp", } edited_conf, edited_name = ctrl_edit(conf, new_conf, name) if edited_conf is not None: conf['ctrl'][name] = edited_conf elif res == choices[-1]: # go back running = False else: confname = res[len(icon):] (editres, newname) = ctrl_edit(conf, copy_conf(conf['ctrl'][confname]), confname) if editres is not None: del conf['ctrl'][confname] if newname is not None: conf['ctrl'][newname] = editres except KeyboardInterrupt: running = False
def new_user(): user_input = VerticalPrompt([ Input("username: "******"password: "******"*", indent=0), Password("repeat password: "******"*", indent=0), ], spacing=0) new_login = user_input.launch() if new_login[1][1] == new_login[2][1]: add_user(new_login[0][1], new_login[1][1]) else: print(Fore.RED + "\nPasswords do not match!" + Fore.WHITE) time.sleep(2) clearConsoleUp(5) clearLine() new_user()
def do_task(self): cli = Input(prompt="What task? 📝 >", strip=False) task = cli.launch() cli = Input(prompt="How long? ⏰ >", strip=False) # Set timer duration = int(cli.launch()) try: print("Press CTRL+C to cancel timer and log time.") time.sleep(duration) self.alert_finished(task, duration) except KeyboardInterrupt: print("\nTimer cancelled and time logged!") # TODO: duration passed should time executed before cancelled self.alert_finished(task, duration)
def enter_game_id(self): subprocess.run(["clear"]) print_heading("Scraped Data Viewer - Enter a BBRef Game ID", fg="bright_yellow") check_game_id = Input("Enter a BBRef Game ID: ").launch() try: result = validate_bbref_game_id(check_game_id) except ValueError: error = f"\n'{check_game_id}' is NOT a valid BBRef Game ID, please try again." print_error(error) pause(message="Press any key to continue...") return Result.Fail("") self.game_id = result.value["game_id"] game_date = result.value["game_date"] all_valid_game_ids = self.app.audit_report[ game_date.year]["successful"] if self.game_id not in all_valid_game_ids: error = f"\nRequirements to show data for {check_game_id} have not been met" print_error(error) pause(message="Press any key to continue...") return Result.Fail("") view_game_data = ViewGameData(self.app, self.game_id) view_game_data.launch() return Result.Fail("")
from pptx import Presentation from pptx.enum.shapes import MSO_SHAPE from pptx.util import Inches, Pt from pptx.dml.color import ColorFormat, RGBColor from pptx.enum.text import PP_ALIGN import sys TITLE_LAYOUT = 0 BLANK = 10 FONT = "Calibri" FILE_LOC = "" SERMON_SERIES = "Signs of Life Series in John’s Gospel" cli = VerticalPrompt( [ Input("What is the reference for Call to Worship?"), Input("Filename?"), Input("What is the reference for Confession of Sin?"), Input("Filename?"), Input("What is the reference for Assurance of Worship?"), Input("Filename?"), YesNo("Is it prayers of the people? "), Input("Sermon title?"), Input("Sermon reference?"), #Bullet("What is your favorite programming language? ", # choices = ["C++", "Python", "Javascript", "Not here!"]), ], spacing=1) result = cli.launch()
def rlaunch(self, key, depth): results = {} section_config = self.configuration[key] if section_config["prompt_type"] == "Check": ui = Check(section_config["prompt"], choices=section_config["choices"], check=" √", margin=2, check_color=colors.bright(colors.foreground["red"]), check_on_switch=colors.bright(colors.foreground["red"]), background_color=colors.background["black"], background_on_switch=colors.background["white"], word_color=colors.foreground["white"], word_on_switch=colors.foreground["black"], indent=depth * 2) choices = ui.launch() branching = section_config.get("branching") if branching is not None: for sub_key in choices: branching_key = branching.get(sub_key) if branching_key is not None: if branching_key.startswith("."): results[sub_key] = self.rlaunch("{}{}".format(key, branching_key), depth) else: results[sub_key] = self.rlaunch(branching_key, depth) else: raise ValueError("the key {} is not in branching {}".format(sub_key, branching.keys())) return results else: return results if section_config["prompt_type"] == "ListInput": ui = ListInput(section_config["prompt"], word_color=colors.foreground["yellow"], indent=depth * 2) results = ui.launch() return results if section_config["prompt_type"] == "Input": ui = Input(section_config["prompt"], word_color=colors.foreground["yellow"], indent=depth * 2) results = ui.launch() return results if section_config["prompt_type"] == "YesNo": ui = YesNo(section_config["prompt"], word_color=colors.foreground["yellow"], default=section_config["default"] if "default" in section_config else 'y', indent=depth * 2) results = ui.launch() return results if section_config["prompt_type"] == "Bullet": ui = Bullet(section_config["prompt"], choices=section_config["choices"], bullet=" >", margin=2, bullet_color=colors.bright(colors.foreground["cyan"]), background_color=colors.background["black"], background_on_switch=colors.background["black"], word_color=colors.foreground["white"], word_on_switch=colors.foreground["white"], indent=depth * 2) results = ui.launch() return results if section_config["prompt_type"] == "GoTo": for sub_key in section_config["goto"]: if sub_key.startswith("."): sub_value = self.rlaunch("{}{}".format(key, sub_key), depth) sub_key = sub_key[1:] else: sub_value = self.rlaunch(sub_key, depth) if isinstance(sub_value, bool) or sub_value: # If True/False or other non-empty data (! "", [], {}) results[sub_key] = sub_value return results
from bullet import Bullet, SlidePrompt, Check, Input, YesNo, Numbers from bullet import styles from bullet import colors cli = SlidePrompt( [ YesNo("Are you a student? ", word_color = colors.foreground["yellow"]), YesNo("Are you a good student? ", default = 'y', word_color = colors.foreground["yellow"]), Input("Who are you? ", default = "Batman", word_color = colors.foreground["yellow"]), Input("Really? ", word_color = colors.foreground["yellow"]), Numbers("How old are you? ", word_color = colors.foreground["yellow"], type = int), Bullet("What is your favorite programming language? ", choices = ["C++", "Python", "Javascript", "Not here!"], bullet = " >", margin = 2, bullet_color = colors.bright(colors.foreground["cyan"]), background_color = colors.background["black"], background_on_switch = colors.background["black"], word_color = colors.foreground["white"], word_on_switch = colors.foreground["white"] ), Check("What food do you like? ", choices = ["🍣 Sushi",