def playListMode(self): """ Method for downloading songs from PlayList. Uses youtube-dl under the hood. """ print("[b blue]PlayList mode[/]") while True: url = qr.text( "Enter the URL for the PlayList:", qmark="*", multiline=True ).ask() try: requests.get(url) # resp.status_code except requests.ConnectionError as e: print(e) return else: print("URL validated successfully!") break pathForSong = qr.path( "Select the Folder to which you want to download the songs:", only_directories=True, ).ask()
def get_path(): """Gets the path to the experiment you want to fix""" if len(sys.argv) > 1 and sys.argv[1] and os.path.exists(sys.argv[1]): set_up_logger(sys.argv[1]) logger.info(f"Using {sys.argv[1]}") return sys.argv[1] path = questionary.path("Please enter the top path (Tab Complete):").ask() set_up_logger(path) return path
def get_generated_config_path(): default_path = f"{os.path.dirname(__file__)}" generated_config_dir = questionary.path( message="Where do you want to save the generated config file?", default=default_path, only_directories=True, ).unsafe_ask() if not os.path.isdir(generated_config_dir): print( f"Invalid path provided, saving to default path instead: {default_path}" ) return default_path return generated_config_dir
def showMain(self): questionary.text("What's your first name").ask() questionary.password("What's your secret?").ask() questionary.confirm("Are you amazed?").ask() questionary.select( "What do you want to do?", choices=[ "Order a pizza", "Make a reservation", "Ask for opening hours" ], ).ask() questionary.rawselect( "What do you want to do?", choices=[ "Order a pizza", "Make a reservation", "Ask for opening hours" ], ).ask() questionary.checkbox("Select toppings", choices=["foo", "bar", "bazz"]).ask() questionary.path("Path to the projects version file").ask()
def main(): parser = ArgumentParser(description = 'Brainfuck input') group = parser.add_mutually_exclusive_group(required = True) group.add_argument('-g', '--gui', action='store_true') group.add_argument('-s', '--string', metavar='', type = str) group.add_argument('-f', '--file', metavar='', type = str) group.add_argument('-F', '--file-prompt', action='store_true') args = parser.parse_args() string = args.string file = args.file if not args.file_prompt else path('Brainfuck file').ask() if args.gui: from tkinter import Tk from tkinter.filedialog import askopenfilename Tk().withdraw() file = askopenfilename(filetypes = [("Brainfuck files", "*.b")]) if file is None: execute(string) else: execute(open(file).read()) print() # Newline
def singleMode(self): """ Method for downloading a single song. uses youtube-dl under the hood """ print("[b blue] Single Song Mode [/]") pathForSong = qr.path( "Select path for downloading songs:", only_directories=True, qmark=">>>", ).ask() # os.chdir(pathForSong) sp.run( [ "cd", f"{pathForSong}", ], shell=True, )
def launch_job_in_check_mode(path): """Launches a job in check mode""" expid = path.split("/")[-1] logger.info(f"Assumed expid: {expid}") expid_guess_correct = questionary.confirm("Is that correct?").ask() while not expid_guess_correct: expid = questionary.text("Please enter the expid...").ask() logger.info(f"Assumed expid: {expid}") expid_guess_correct = questionary.confirm("Is that correct?").ask() runscript_paths = [ f for f in os.listdir(f"{path}/scripts") if f.endswith(".yaml") ] if len(runscript_paths) == 0: logger.error("Couldn't find the runscript") runscript_path = questionary.path( "Please enter the runscript path (Tab-Complete)").ask() elif len(runscript_paths) == 1: runscript_path = runscript_paths[0] else: logger.info("Multiple possible runscripts found!") runscript_path = questionary.select("Which is the right one", choices=runscript_paths).ask() command = f"esm_runscripts {runscript_path} -e {expid} -c" logger.info("Launching in check mode like this:") logger.info(command) subprocess.run(command, shell=True, check=True, cwd=f"{path}/scripts") logger.info( "Note that it is normal for some of the missing files to be listed:") logger.info("* namelist: namelist.diag (in FESOM)") logger.info( "* restart: rad restart file (in ECHAM, if not using concurrent radiation)" ) logger.info("* restart: nitro restart file (in JSBACH)") logger.info("* restart: land restart file (in JSBACH)") return command
def main(): generator = questionary.autocomplete( "What do you want to generate?", choices=[ "Apache Config", "Windows Install", ], style=style, ).ask() if generator == "Apache Config": gen = ApacheConfigGenerator() apache_path: str = questionary.path( "Where is apache2 located?", default="/etc/apache2", style=style, ).ask() if apache_path == None: print("Failed to generate: missing apache path!") exit(1) domains: str = questionary.text( "What domains to you want to serve? (Seperated by commas)", default="example.com", style=style, ).ask() if domains == None: print("Failed to generate: missing domain(s)!") exit(1) web_loc = questionary.path( "What is the path of your website files? (Optional)", default="", style=style, ).ask() if web_loc == None: print("Failed to generate: missing webroot!") exit(1) uri_to_forward = questionary.text( "What URI do you want to proxy to? (Optional)", default="", style=style, ).ask() if uri_to_forward == None: print("Failed to generate: missing proxy URI!") exit(1) if apache_path != "" and domains != "": gen.generate( apache_path=apache_path, domains=domains, uri_to_forward=uri_to_forward, web_loc=web_loc, ) else: print("Failed to generate: missing answers!") elif generator == "Windows Apache2 Modifier Install": gen = Windowsa2Installer() gen.generate() else: print("Nothing to generate, exiting...")
def get_path(): """Gets the path to the experiment you want to fix""" return questionary.path("Please enter the top path (Tab Complete):").ask()
def cli(): print("Welcome to effmass 2.0.0 \U0001F388") ignore, seedname, fermi_level = None, None, None random_int = randint(10000, 99999) DFT_code = questionary.select( "Which DFT code have you used to generate the bandstructure?", choices=['Vasp', 'FHI-aims', 'Castep']).ask() pathname = questionary.path( "What's the path to your {} output files?".format(DFT_code), default="./", only_directories=True).ask() if DFT_code == 'Vasp': ignore = questionary.text( "How many k-points should I ignore at the start of the file? (useful for hybrid calculations)", default="0").ask() if DFT_code == 'Castep': seedname = questionary.text( "What's the seedname of your Castep files? (e.g. Si.bands and Si.castep have the seedname Si)", ).ask() fermi_level = questionary.text( "I will infer the position of the CBM and VBM from the calculated Fermi level." + " If you know this value to be incorrect, please input a more accurate value:", ).ask() extrema_search_depth = questionary.text( "How far (in eV) from the CBM (VBM) would you like me to search for minima (maxima)?", default="0.05").ask() energy_range = questionary.text( "What would you like the energy range (in eV) of each segment to be?", default="0.5").ask() which_values = questionary.checkbox( "Which values would you like me to calculate?", choices=[ questionary.Choice("parabolic m* (least squares)", checked=True), questionary.Choice("parabolic m* (finite difference)", checked=True) ]).ask() # need to select oe save_plot = questionary.confirm( "Would you like me to save a plot of the band segments?", default=True, auto_enter=False).ask() save_summary = questionary.confirm( "Would you like me to save a summary file?", default=True, auto_enter=False).ask() settings = inputs.Settings( extrema_search_depth=float(extrema_search_depth), energy_range=float(energy_range)) print("Reading in data...") if DFT_code == "Vasp": data = inputs.DataVasp(pathname + "/OUTCAR", pathname + "/PROCAR", ignore=int(ignore)) elif DFT_code == "FHI-aims": data = inputs.DataAims(pathname) else: data = inputs.DataCastep(pathname + "/", seedname) if fermi_level: data.fermi_level = fermi_level data.find_cbm_vbm() print("Finding extrema...") print("Generating segments...") segments = extrema.generate_segments(settings, data) print("Calculating effective masses...") table = outputs.make_table(segments, which_values) outputs.print_terminal_table(table) if save_plot: print("Plotting segments...") outputs.plot_segments(data, settings, segments, savefig=True, random_int=random_int) print("Plot of segments saved to effmass_{}.png".format(random_int)) if save_summary: print("Writing summary file...") outputs.print_summary_file(random_int, DFT_code, pathname, ignore, seedname, fermi_level, extrema_search_depth, energy_range, table) print("Summary file saved as effmass_{}.txt".format(random_int))
project_yaml = {} questionary.print("Welcome!", style="bold") questionary.print(WELCOME, style="italic") questionary.print(ORDER) title = questionary.text("What's the title of the project?").ask() project_yaml["title"] = title description = questionary.text( "Please provide a short description of the project." ).ask() project_yaml["description"] = description project_directory = questionary.path( "What's the path to the current project directory?", only_directories=True ).ask() questionary.print(f"Great, we'll be using: {project_directory}") add_directories = questionary.confirm( f"Would you like to add current subdirectories of {project_directory} as project directories? (To ensure they exist for future commands and workflows)" ).ask() if add_directories: directories = list( p.name for p in Path(project_directory).glob("*") if p.is_dir() and not p.name.startswith(".") ) project_yaml["directories"] = directories print(f"{len(directories)} directories added.")
def interactive_config() -> None: """ Prompt the user with a series of questions to configure pytoil interactively. """ printer.warn("No pytoil config file detected!") interactive: bool = questionary.confirm( "Interactively configure pytoil?", default=False, auto_enter=False ).ask() if not interactive: # User doesn't want to interactively walk through a config file # so just make a default and exit cleanly Config.helper().write() printer.good("I made a default file for you.") printer.note( f"It's here: {defaults.CONFIG_FILE}, you can edit it with `pytoil" " config edit``", exits=0, ) return # If we get here, the user wants to interactively make the config projects_dir: str = questionary.path( "Where do you keep your projects?", default=str(defaults.PROJECTS_DIR), only_directories=True, ).ask() token: str = questionary.text("GitHub personal access token?").ask() username: str = questionary.text("What's your GitHub username?").ask() use_editor: bool = questionary.confirm( "Auto open projects in an editor?", default=False, auto_enter=False ).ask() if use_editor: editor: str = questionary.text("Name of the editor binary to use?").ask() else: editor = "None" git: bool = questionary.confirm( "Make git repos when creating new projects?", default=True, auto_enter=False ).ask() conda_bin: str = questionary.select( "Use conda or mamba for conda environments?", choices=("conda", "mamba"), default="conda", ).ask() config = Config( projects_dir=Path(projects_dir).resolve(), token=token, username=username, editor=editor, conda_bin=conda_bin, git=git, ) config.write() printer.good("Config created") printer.note(f"It's available at {defaults.CONFIG_FILE}.", exits=0)
def main(): generator: str = questionary.select( "What do you want to generate?", choices=["Apache Config", "Nginx Config"], style=style, ).ask() gen: ConfigGenerator = None if generator == "Apache Config": apache_path: str = questionary.path( "Where is apache2 located?", default="/etc/apache2", style=style, ).ask() if apache_path is None: print("Failed to generate: missing apache path!") exit(1) domains: str = questionary.text( "What domains to you want to serve? (Seperated by commas)", default="example.com", style=style, ).ask() if domains is None: print("Failed to generate: missing domain(s)!") exit(1) web_loc = questionary.path( "What is the path of your website files? (Optional)", default="", style=style, ).ask() if web_loc is None: print("Failed to generate: missing webroot!") exit(1) uri_to_forward = questionary.text( "What URI do you want to proxy to? (Optional)", default="", style=style, ).ask() if uri_to_forward is None: print("Failed to generate: missing proxy URI!") exit(1) if apache_path != "" and domains != "": gen = ApacheConfigGenerator( apache_path=apache_path, domains=domains, uri_to_forward=uri_to_forward, web_root=web_loc, ) gen.generate() else: print("Failed to generate: missing answers!") elif generator == "Nginx Config": nginx_path: str = questionary.path( "Where is nginx located?", default="/etc/nginx", style=style, ).ask() if nginx_path is None: print("Failed to generate: missing apache path!") exit(1) domains: str = questionary.text( "What domains to you want to serve? (Seperated by commas)", default="example.com", style=style, ).ask() if domains is None: print("Failed to generate: missing domain(s)!") exit(1) web_loc = questionary.path( "What is the path of your website files? (Optional)", default="", style=style, ).ask() if web_loc is None: print("Failed to generate: missing webroot!") exit(1) uri_to_forward = questionary.text( "What URI do you want to proxy to? (Optional)", default="", style=style, ).ask() if uri_to_forward is None: print("Failed to generate: missing proxy URI!") exit(1) if nginx_path != "" and domains != "": gen = NginxConfigGenerator( nginx_path=nginx_path, domains=domains, uri_to_forward=uri_to_forward, web_root=web_loc, ) gen.generate() else: print("Failed to generate: missing answers!") elif generator == "UFW Firewall": # TODO: fix this """gen = UfwConfigGenerator() allowDeny = questionary.select( "Would you like to accept or deny a port?", choices=["Allow", "Deny"], style=style, ).ask() port = questionary.text( "What port would you like to allow/deny?", style=style ).ask() if allowDeny is None: print("Failed to generate: you did not choose to allow/deny a port.") exit(1) if port is None: print("Failed to generate: Missing port") exit(1) if allowDeny != "" and port != "": gen.generate(port, accept=True if allowDeny == "Allow" else False) else: print("Failed to generate: missing answers!")""" else: print("Nothing to generate, exiting...")
def launch_pipeline(self): # Prompt for pipeline if not supplied and no web launch ID if self.pipeline is None and self.web_id is None: launch_type = questionary.select( "Launch local pipeline or remote GitHub pipeline?", choices=["Remote pipeline", "Local path"], style=nf_core.utils.nfcore_question_style, ).unsafe_ask() if launch_type == "Remote pipeline": try: self.pipeline = nf_core.utils.prompt_remote_pipeline_name( self.wfs) except AssertionError as e: log.error(e.args[0]) return False else: self.pipeline = questionary.path( "Path to workflow:", style=nf_core.utils.nfcore_question_style).unsafe_ask() # Check if the output file exists already if os.path.exists(self.params_out): log.warning("Parameter output file already exists! {}".format( os.path.relpath(self.params_out))) if Confirm.ask("[yellow]Do you want to overwrite this file?"): os.remove(self.params_out) log.info("Deleted {}\n".format(self.params_out)) else: log.info( "Exiting. Use --params-out to specify a custom filename.") return False log.info( "NOTE: This tool ignores any pipeline parameter defaults overwritten by Nextflow config files or profiles\n" ) # Check if we have a web ID if self.web_id is not None: self.schema_obj = nf_core.schema.PipelineSchema() try: if not self.get_web_launch_response(): log.info( "Waiting for form to be completed in the browser. Remember to click Finished when you're done." ) log.info("URL: {}".format(self.web_schema_launch_web_url)) nf_core.utils.wait_cli_function( self.get_web_launch_response) except AssertionError as e: log.error(e.args[0]) return False # Load local params if supplied self.set_schema_inputs() # Load schema defaults self.schema_obj.get_schema_defaults() # No --id supplied, fetch parameter inputs else: # Build the schema and starting inputs if self.get_pipeline_schema() is False: return False self.set_schema_inputs() self.merge_nxf_flag_schema() # Collect user inputs via web or cli if self.prompt_web_gui(): try: self.launch_web_gui() except AssertionError as e: log.error(e.args[0]) return False else: # Kick off the interactive wizard to collect user inputs self.prompt_schema() # Validate the parameters that we now have if not self.schema_obj.validate_params(): return False # Strip out the defaults if not self.save_all: self.strip_default_params() # Build and launch the `nextflow run` command self.build_command() self.launch_workflow()
def ask_questions_mobile(mobile_os_name, mobile_os_version, device_name, app_package, app_activity, remote_flag, device_flag, testrail_flag, tesults_flag, app_name, app_path): """This module asks the users questions to fetch the options they wish to run the mobile test with and stores their choices""" clear() while True: questionary.print("\nUse up and down arrow keys to switch between options.\ \nUse Enter key to select an option", style="bold fg:yellow") mobile_display_options(mobile_os_name, mobile_os_version, device_name, app_package, app_activity, remote_flag, device_flag, testrail_flag, tesults_flag, app_name, app_path) questionary.print("**********",style="bold fg:green") response = get_user_response_mobile() clear() if response == "Mobile OS Name": mobile_os_name, mobile_os_version, device_name = get_mobile_os_name() if response == "Mobile OS Version": mobile_os_version = get_mobile_os_version(mobile_os_name) if response=="Device Name": if mobile_os_name == "Android": device_name = mobile_android_devices(mobile_os_version) if mobile_os_name == "iOS": device_name = mobile_ios_devices(mobile_os_version) if response == "App Package": app_package = questionary.text("Enter the app package name").ask() if response == "App Activity": app_package=questionary.text("Enter the App Activity").ask() if response == "Set Remote credentials": set_remote_credentials() if response == "Remote Flag status": remote_flag = get_remote_flag_status() if response == "Testrail Flag status": testrail_flag = get_testrailflag_status() if response == "Tesults Flag status": tesults_flag = get_tesultsflag_status() if response == "App Name": app_name = questionary.text("Enter App Name").ask() if response == "App Path": app_path = questionary.path("Enter the path to your app").ask() if response == "Revert back to default options": mobile_os_name, mobile_os_version, device_name, app_package, app_activity, remote_flag, device_flag, testrail_flag,tesults_flag, app_name, app_path = mobile_default_options() if response == "Run": if app_path is None: questionary.print("Please enter the app path before you run the test", style="bold fg:darkred") else: break if response == "Exit": sys.exit("Program interrupted by user, Exiting the program....") return (mobile_os_name, mobile_os_version, device_name, app_package, app_activity, remote_flag, device_flag, testrail_flag, tesults_flag, app_name,app_path)
"Export", "Edit", "Exit" ]) import_menu_questions = questionary.select( "What is your desired source of input?", choices=[ "URL", "String", "File", "Go back" ]) import_menu_questions2 = questionary.path( "Please enter the json in a single line or the source in a single line:" ) class IntegerValidator(questionary.Validator): """ Validator class which checks if the input is an integer. """ def validate(self, document): """ Validation function which does raise a ValidationError or does not return a value. :param document: The user input. Handed over by questionary. :raises ValidationError: In case the text could not be parsed to an integer. """ if len(document.text) == 0:
import questionary if __name__ == "__main__": path = questionary.path("Path to the projects version file").ask() if path: print(f"Found version file at {path} 🦄") else: print("No version file it is then!")
def prompt_use_singularity_cachedir(self): """Prompt about using $NXF_SINGULARITY_CACHEDIR if not already set""" if (self.container == "singularity" and os.environ.get("NXF_SINGULARITY_CACHEDIR") is None and stderr. is_interactive # Use rich auto-detection of interactive shells ): stderr.print( "\nNextflow and nf-core can use an environment variable called [blue]$NXF_SINGULARITY_CACHEDIR[/] that is a path to a directory where remote Singularity images are stored. " "This allows downloaded images to be cached in a central location." ) if rich.prompt.Confirm.ask( f"[blue bold]?[/] [bold]Define [blue not bold]$NXF_SINGULARITY_CACHEDIR[/] for a shared Singularity image download folder?[/]" ): # Prompt user for a cache directory path cachedir_path = None while cachedir_path is None: prompt_cachedir_path = questionary.path( "Specify the path:", only_directories=True, style=nf_core.utils.nfcore_question_style).unsafe_ask( ) cachedir_path = os.path.abspath( os.path.expanduser(prompt_cachedir_path)) if prompt_cachedir_path == "": log.error( f"Not using [blue]$NXF_SINGULARITY_CACHEDIR[/]") cachedir_path = False elif not os.path.isdir(cachedir_path): log.error(f"'{cachedir_path}' is not a directory.") cachedir_path = None if cachedir_path: os.environ["NXF_SINGULARITY_CACHEDIR"] = cachedir_path # Ask if user wants this set in their .bashrc bashrc_path = os.path.expanduser("~/.bashrc") if not os.path.isfile(bashrc_path): bashrc_path = os.path.expanduser("~/.bash_profile") if not os.path.isfile(bashrc_path): bashrc_path = False if bashrc_path: stderr.print( f"\nSo that [blue]$NXF_SINGULARITY_CACHEDIR[/] is always defined, you can add it to your [blue not bold]~/{os.path.basename(bashrc_path)}[/] file ." "This will then be autmoatically set every time you open a new terminal. We can add the following line to this file for you: \n" f'[blue]export NXF_SINGULARITY_CACHEDIR="{cachedir_path}"[/]' ) append_to_file = rich.prompt.Confirm.ask( f"[blue bold]?[/] [bold]Add to [blue not bold]~/{os.path.basename(bashrc_path)}[/] ?[/]" ) if append_to_file: with open(os.path.expanduser(bashrc_path), "a") as f: f.write( "\n\n#######################################\n" f"## Added by `nf-core download` v{nf_core.__version__} ##\n" + f'export NXF_SINGULARITY_CACHEDIR="{cachedir_path}"' + "\n#######################################\n" ) log.info( f"Successfully wrote to [blue]{bashrc_path}[/]" ) log.warning( "You will need reload your terminal after the download completes for this to take effect." )