示例#1
0
    def on_enter_alter_definitions(self):
        click.echo('\n')

        _alter_resources = confirm(
            ANSI(
                click.style(self._TEXT_ASKALTERRESOURCES,
                            fg=self.CLICK_PROMPT_FG_COLOR)))
        if _alter_resources:
            # open editor
            self._edit_file_with_editor(self.settings.resources_path)
            self._read_resources_file()
            self._parse_resources()
            self.settings.solver.set_resources(self.settings.resources)

        _alter_deployments = confirm(
            ANSI(
                click.style(self._TEXT_ASKALTERWORKLOADS,
                            fg=self.CLICK_PROMPT_FG_COLOR)))
        if _alter_deployments:
            # open editor
            self.settings.dsl_content = self._edit_content_with_editor(
                self.settings.dsl_content)
            self.settings.dsl_importer.reset_app_modules()
            self._parse_dsl()
            self.settings.solver.set_deployment_entities(
                self.settings.deployment_entities)

        self.start_matching()
示例#2
0
def prompt() -> Optional[booklog_api.AuthorWithWorks]:
    name = None

    while name is None:
        name = ask.prompt("Author: ")

    authors = booklog_api.search_authors(name)

    options: list[AuthorOption] = build_author_options(authors)

    selected_author = None

    while selected_author is None:

        selected_author = radio_list.prompt(
            title="Select author:",
            options=options,
        )

        if selected_author is None:
            break

    if not selected_author:
        return None

    if confirm("{0}?".format(selected_author.name)):
        return selected_author

    return prompt()
示例#3
0
    def set_range(self, path: str, from_id: int, to_id: int):
        """
        This updates the log id range for the LogGroup under
        a specific directory path in the LogsConfig tree.
        This only works if the tier has LogsConfigManager enabled.
        """
        try:
            c = _get_client()
            current_log_group = c.get_log_group_by_name(str(path))
            if not context.get_context().args.yes and not confirm(
                    "Are you sure you want to set"
                    " the log range at "
                    '"{}" to be ({}..{}) instead of({}..{})? (y/n)'.format(
                        path,
                        from_id,
                        to_id,
                        current_log_group.range[0],
                        current_log_group.range[1],
                    )):
                return
            version = c.set_log_group_range(str(path), from_id, to_id)
            cprint("Log group '{}' has been updated in version {}!".format(
                path, version))

        except LogDeviceError as e:
            cprint("Cannot update range for '{}': {}".format(path, e), "red")
示例#4
0
def ask_for_work() -> Optional[str]:
    author_with_works = ask_for_author.prompt()

    if not author_with_works:
        return None

    options: list[WorkOption] = build_work_options(author_with_works.works)

    selected_work = None

    while selected_work is None:

        selected_work = radio_list.prompt(
            title="Select work:",
            options=options,
        )

        if selected_work is None:
            break

    if not selected_work:
        return None

    if confirm("{0}?".format(selected_work.title)):
        return selected_work.slug

    return ask_for_work()
示例#5
0
 def quit(self, *args):
     """ exit from terminal without killing services and components"""
     print(
         "Quitting this way will not kill all the services and components")
     if confirm(message="Are you sure you want to quit?"):
         self.exit = False
         exit()
示例#6
0
文件: main_cli.py 项目: zhan849/argo
 def _handle_command(cmd):
     _m = {
         "install": InstallPrompts,
         "uninstall": UninstallPrompts,
         "pause": PausePrompts,
         "resume": ResumePrompts
     }
     if cmd in _m:
         prompter = _m[cmd]()
         prompter.run_cli()
         command = prompter.get_argocluster_command()
         print "Running the following command. It will take some time\n\n{}\n\n".format(
             command)
         answer = confirm(
             u'Are you sure you want to perform the action? (y/n) ')
         if answer:
             try:
                 subprocess.check_call(command.split(" "))
             except Exception as e:
                 traceback.print_exc()
                 print "Got the following exception {} when trying to run command {}.".format(
                     e, command)
                 print "\nYou can drop into the advanced shell by typing 'advanced' and add more options to the command"
     elif cmd == "help":
         print(HELP)
     elif cmd == "advanced":
         print(
             "\n\nDropping you to a bash shell where you can type 'argocluster help' for info. Type 'exit' when done\n\n"
         )
         subprocess.call(['bash'])
     elif cmd == "exit":
         raise EOFError("Pressed exit")
     return cmd, True
示例#7
0
    def remove(self, path: str, recursive: bool = False):
        """
        Removes a directory or a log-group under a specific directory path in
        the LogsConfig tree. This will NOT delete the directory if it is not
        empty by default, you need to use --recursive (recursive=True).
        """

        try:
            c = _get_client()
            if not context.get_context().args.yes and not confirm(
                    "Are you sure you want to REMOVE "
                    "'{}'? (y/n)".format(path)):
                return
            try:
                version = c.remove_log_group(str(path))
            except LogDeviceError as e:
                if e.args[0] == ErrorStatus.NOTFOUND:
                    version = c.remove_directory(str(path), recursive)
            cprint("'{}' has been removed in version {}".format(path, version))

        except LogDeviceError as e:
            cprint("Cannot remove '{}'. Reason: {}".format(path, e.args[2]),
                   "red")

            return 1
示例#8
0
def prompt() -> Optional[booklog_api.WorkWithAuthors]:
    title = None

    while title is None:
        title = ask.prompt("Title: ")

    works = booklog_api.search_works(title)

    options: list[WorkOption] = build_work_options(works)

    selected_work = None

    while selected_work is None:

        selected_work = radio_list.prompt(
            title="Select work:",
            options=options,
        )

        if selected_work is None:
            break

    if not selected_work:
        return None

    if confirm("{0}?".format(selected_work.title)):
        return selected_work

    return prompt()
示例#9
0
def extract_data(space,
                 datafile=None,
                 working_info=None,
                 verbose=0,
                 force=False):
    if verbose >= 1:
        print(
            "As a list of spaces has been specified, analysis will take place\n"
        )

    if not working_info:
        working_info = {'wd': [os.getcwd()], 'hostname': [os.uname()[1]]}
    data = explore(space, working_info)

    if len(data) > 0:
        print("\n{} entries ({} parsed by Hachoir)".format(
            len(data), count_hachoir))

        ph = pd.DataFrame(data,
                          columns=[
                              'folder', 'name', 'datetime', 'make', 'model',
                              'digest', 'mime', 'code', 'size', 'atime',
                              'mtime', 'ctime', 'has_json'
                          ])
        # split into OK and ERROR files
        ph_ok, ph_error = ph[ph.code == CODE_OK].copy(), ph[
            ph.code != CODE_OK].copy()
        print("{} ok / {} error".format(len(ph_ok), len(ph_error)))

        # Add dummy time to 'timeless' timestamps. Tag those entries as well.
        dates_with_no_time = ~ph_ok.datetime.str.match("^\d{4}:\d{2}:\d{2} ")
        full_datetimes = ph_ok.loc[dates_with_no_time].datetime + " 08:00:00"
        ph_ok['timeless'] = False
        ph_ok.loc[dates_with_no_time, 'timeless'] = True
        ph_ok.loc[dates_with_no_time, 'datetime'] = full_datetimes
        ph_ok.loc[:, 'datetime'] = pd.to_datetime(ph_ok['datetime'],
                                                  format="%Y:%m:%d %H:%M:%S")

        # Save data
        if datafile:
            datafilename = storage.normalize(datafile)
            create_file = True
            if os.path.isfile(datafilename):
                create_file = force or confirm(
                    suffix="(y/N)",
                    message="Do you want to overwrite existing datafile '{}'?".
                    format(datafilename))
                if not create_file:
                    print("NOT overwritting '{}{}{}'".format(
                        Fore.YELLOW, datafilename, Fore.RESET))
                else:
                    print("overwritting '{}{}{}'".format(
                        Fore.GREEN, datafilename, Fore.RESET))
            if create_file:
                ph_ok.to_hdf(datafilename, key='ok', format="table")
                ph_error.to_hdf(datafilename, key='error', format="table")
                pd.DataFrame(working_info).to_hdf(datafilename,
                                                  key='info',
                                                  format="table")
示例#10
0
 def shutdown(self, *args):
     """ exit from terminal killing all services and components"""
     if confirm(message="Are you sure you want to shutdown?"):
         self.robot.shutdown()
         try:
             os.kill(self.pid, 9)
         except:
             print("Error: no PID available")
         exit()
示例#11
0
 def c_force_update(self, args):
     if args:
         self.c_update(args, False, True, True)
     else:
         # noinspection PyTypeChecker
         answer = confirm(HTML('<ansibrightred>Execute a forced update of all addons and overwrite ALL local '
                               'changes?</ansibrightred>'))
         if answer:
             self.c_update(False, False, True, True)
def _get_user_confirmation(question, default=False):
    '''
    Ask a question and return True if user agrees or False if a user disagrees
    question: string - question that will be shown to a user
    default: bool - consider this value as a default if user does not provide an answer
    '''
    suffix = "[Y/n]" if default is True else "[y/N]"
    answer = confirm(question, suffix) or default
    return answer
示例#13
0
 def exit_program(self):
     answer = confirm("Are you sure you want to exit?")
     if answer:
         if self._poisoner:
             set_ip_forwarding(0)
             Interface._print_info("Stopping the arp spoofer")
             self._poisoner.stop()
         print("\nBye Bye! See you soon!")
         sys.exit()
示例#14
0
def ask_for_year() -> Optional[str]:
    year = ask.prompt("Year First Published: ")

    if not year:
        return None

    if confirm(year):  # noqa: WPS323
        return year

    return ask_for_year()
示例#15
0
def ask_for_name() -> Optional[str]:
    name = ask.prompt("Name: ")

    if not name:
        return None

    if confirm(name):  # noqa: WPS323
        return name

    return ask_for_name()
示例#16
0
def ask_for_title() -> Optional[str]:
    title = ask.prompt("Title: ")

    if not title:
        return None

    if confirm(title):  # noqa: WPS323
        return title

    return ask_for_title()
示例#17
0
def ask_for_subtitle() -> Optional[str]:
    subtitle = ask.prompt("Sub-title: ")

    if not subtitle:
        return None

    if confirm(subtitle):  # noqa: WPS323
        return subtitle

    return ask_for_subtitle()
示例#18
0
    def on_enter_check_results(self):

        _placement_ok = confirm(
            ANSI(
                click.style(self._TEXT_ASKPLACEMENTOK,
                            fg=self.CLICK_PROMPT_FG_COLOR)))
        if _placement_ok:
            self.export()
        else:
            self.ask_alter()
示例#19
0
def ask_for_works() -> list[str]:
    works: list[str] = []

    while True:
        work = ask_for_work.prompt()

        if work:
            works.append(work.slug)

        if not confirm("Add more?"):
            return works
示例#20
0
文件: config.py 项目: kalleroska/poi
def create_poi_config(root='', configpath=''):
    """
    Create a poi configuration file.
    """
    config = {}

    # Path to poi's directory:
    if root:
        config['root'] = root
    else:
        config['root'] = os.path.join(os.path.expanduser('~'), 'poi')

    # Command to use to launch an editor:
    config['editor_cmd'] = 'open -a /Applications/TextEdit.app'

    # File extension to use for notes:
    config['file_ext'] = '.txt'

    # Colors for displaying note on the terminal
    config['color'] = {}
    config['color']['title'] = '#ff0066 bold'
    config['color']['link'] = '#00ff66 bold'
    config['color']['highlight'] = [
                                    '#0000ff bold',  # blue
                                    '#ffff00 bold',  # yellow
                                    '#00ffff bold',  # gray
                                    ]
    config['color']['tag'] = '#808080 bold'

    # Markers for highlighting text in a note:
    config['highlight_markers'] = [':::', '___', '`']

    if not configpath:
        _ = os.path.expanduser('~')
        configpath = os.path.join(_, '.poiconfig.json')

    # If poiconfig file alredy exists, back it up:
    if os.path.exists(configpath):
        ans = confirm('Config file already exists. Replace it with a new ome (y/n): ')
        if ans:
            dirname = os.path.dirname(configpath)
            filename = os.path.basename(configpath)
            root, ext = os.path.splitext(filename)
            backup = os.path.join(dirname, root + '_' + datetime.datetime.today().strftime('%Y%m%d') + ext)
            shutil.move(configpath, backup)
            print('poi: a copy of an existing configuration file has been created: {}'.format(backup))
        else:
            print('poi: initialization interrupted')
            return None

    with open(configpath, 'wt') as f:
            json.dump(config, f, indent=2)

    print('poi: a new configuration has been created at {}'.format(configpath))
示例#21
0
 def clear_all(self):
     print(f"You are about to remove {colored(len(self.components),'red')} from {colored(len(self.workspace_paths), 'red')} workspaces.")
     print(f"This action only remove the references to this workspaces and components for rccommands.")
     print(colored("NO actual folders nor files are going to be removed.", 'red'))
     answer = confirm(f"Are you sure that you want to do this?")
     if answer:
         self.components = []
         self.workspace_paths = []
         print("All workspaces have been removed.")
     else:
         print("No workspaces have been deleted.")
     self.save_workspace()
示例#22
0
文件: ui.py 项目: kalleroska/poi
def delete_note(args):
    """
    Delete a given note.
    """
    notepath = parse_index(args)
    if notepath is None:
        return None
    note = parse_note(notepath)
    print(note.creation_date, '   ', note.title)
    ans = confirm('delete? (y/n) ')
    if ans:
        nm.delete_note(notepath)
 def evaluate_node(node: Node):
     print("-------------------------")
     print("Evaluating node {} {}".format(str(node.ev_id),node.name))
     # print("Name: {}".format(node.name))
     # print("Evaluation_id: {}".format(node.ev_id))
     # print("Code_component_id: {}".format(node.code_component_id))
     print("Parameters: name | value ")
     for p in node.params:
         print (" {} | {} ".format(p.name, p.value))
     print("Returns: {}".format(node.retrn))
     answer = confirm('Is correct? ')
     return answer
示例#24
0
    def add_workspace(self, initial=None, accept_all=False):
        if initial is None:
            initial = os.getcwd()
        else:
            initial = os.path.abspath(initial)
        existing_workspace = self.search_parent_in_workspaces(initial)
        if not existing_workspace:
            if accept_all:
                response = initial
            else:
                session = PromptSession(u"> ",
                                        completer=FuzzyCompleter(
                                            PathCompleter()))
                response = session.prompt(
                    "Path to find new components\n> ",
                    complete_while_typing=True,
                    default=initial,
                    pre_run=session.default_buffer.start_completion,
                    validator=dir_validator)
            # Check the final '/' characters
            if response in self.workspace_paths:
                print(f"{response} already exist in workspaces")
                return

            new_components = self.get_recursive_components_in_dir(response)

            print("%s\n%d components found in %s" %
                  (colored('\n'.join(new_components),
                           'green'), len(new_components), response))
            if len(new_components) == 0:
                print(
                    f"No component found in {response}. Workspaces not updated."
                )
                return

            if accept_all:
                answer = True
            else:
                answer = confirm(
                    f'Do you want to add {response} to workspaces?')

            if answer:
                print(f"{response} added to workspaces")
                self.components += new_components
                self.workspace_paths.append(response)
                self.save_workspace()
            else:
                print("Workspaces not updated.")
        else:
            print(
                f"{initial} is already part of an existing workspace ({existing_workspace})"
            )
            self.update_components_in_workspaces(existing_workspace)
示例#25
0
def write_ssh_file(ssh_path, filename, data):
   file_path = os.path.join(ssh_path, filename)
   file_exist = os.path.isfile(file_path)
   create_file = True
   if file_exist:
      create_file = confirm(f"{file_path} already exists. Overwrite?")
   if create_file:
      print(f"Writing {file_path}")
      f = open(file_path, 'wb')
      f.write(data)
      f.close()
      os.chmod(file_path,0o400)
   return file_exist
示例#26
0
def configure_ssh_key(pub_key):
   print("You need to add the contents of your public key to GitHub.")
   print("For instructions on how to do this, please visit:")
   print("\thttps://bit.ly/gh-ssh")
   print("Once you have done this, come back to this terminal, and type y")
   print("##################################")
   print("###START FILE#####################")
   print(pub_key.decode("utf-8").strip('\n'))
   print("###END FILE#######################")
   print("##################################")
   copy = False
   while not(copy):
      copy = confirm(f"Have you copied the contents of the file to GitHub?")
示例#27
0
 def find_components(self, searched_component):
     if not self.components:
         #TODO: add options to interactive search (interactive_workspace_init) or add (add_workspace)
         print('rccd needs to have components dir configured.')
         answer = confirm('Do you want to configure it now?')
         if answer:
             new_path = prompt('Parent dir for components? ', completer=PathCompleter(), complete_while_typing=True,
                               default=os.getenv('ROBOCOMP'))
             if new_path:
                 self.interactive_workspace_init(new_path)
     if self.components:
         options = list(filter(lambda x: searched_component.lower() in x.lower(), self.components))
         return options
     return None
示例#28
0
def ask_for_grade() -> Optional[str]:
    validator = Validator.from_callable(
        is_grade,
        error_message="Must be a valid grade.",
        move_cursor_to_end=True,
    )

    review_grade = ask.prompt("Grade: ", validator=validator, default="")

    if not review_grade:
        return None

    if confirm(review_grade):  # noqa: WPS323
        return review_grade

    return ask_for_grade()
示例#29
0
def ask_for_authors() -> list[booklog_api.WorkAuthor]:
    work_authors: list[booklog_api.WorkAuthor] = []

    while True:
        author = ask_for_author.prompt()

        if author:
            author_notes = ask.prompt("Notes: ")

            if not author_notes:
                author_notes = None

            work_authors.append(
                booklog_api.WorkAuthor(slug=author.slug, notes=author_notes))

        if not confirm("Add more?"):
            return work_authors
示例#30
0
def sendTUI(pwd):
    os.system('clear')

    session = PromptSession(history=FileHistory(functions.HOME +
                                                '/.sendmail_mailinglist'))

    print_formatted_text(HTML(
        'Please enter your receiver (if you get suggested adresses, just press <wbg>→ </wbg>:'
    ),
                         style=style)
    receiver = session.prompt("> ",
                              validator=functions.validateEmail(),
                              auto_suggest=AutoSuggestFromHistory())
    print("Please enter your subject:")
    subject = input("> ")
    print_formatted_text(HTML(
        'Please enter your message content. If you have finished your text press <wbg>ALT</wbg> + <wbg>ENTER</wbg>:'
    ),
                         style=style)
    print("")

    text = prompt('> ',
                  multiline=True,
                  prompt_continuation=functions.prompt_continuation,
                  mouse_support=True)
    attachment = confirm("Do you want to add one attachment to the email?")
    if attachment:
        print_formatted_text(
            HTML(
                "Please enter the whole filepath to your attachment file. For example: <ansigreen>/home/lolo/documents/test.pdf</ansigreen>"
            ))
        filepath = prompt("> ",
                          validator=functions.validateFilePath(),
                          completer=PathCompleter())
    else:
        filepath = None

    send(addr_to=receiver,
         subject=subject,
         message=text,
         password=pwd,
         filename=filepath)

    os.system('clear')
    return
示例#31
0
    def prompt_item_attributes(self, manual_attributes, completion_dict):
        '''Prompts user to input attributes defined in MANUAL_ATTRIBUTES'''
        # TODO: UPDATE DOC STRING
        inp_dict = dict()
        for attrib, question in manual_attributes.items():
            inp_dict[attrib] = prompt('{}: '.format(question),
                                      completer=completion_dict[attrib],
                                      complete_while_typing=True)
            if inp_dict[attrib] not in completion_dict[attrib].words:
                if inp_dict[attrib] != '':
                    completion_dict[attrib].words.append(inp_dict[attrib])
        answer = confirm('\nAre these details correct? (y/n) ')
        if answer:
            self.set_attributes(inp_dict)
        else:
            completion_dict = self.prompt_item_attributes(
                manual_attributes, completion_dict)

        return completion_dict
示例#32
0
def init():
    if config.active_workspace():
        resp = confirm(
            "Config already has active workspace '{}'.\nContinue and overwrite? "
            .format(config.active_workspace()))
        if not resp:
            slacker_logger.error("Aborting!")
            return
        config.reset()

    (workspace, token) = workspace_token_prompt()

    config.add_workspace(workspace, token)
    config.set_active_workspace(workspace)
    config.save()

    slacker_logger.info(
        "Added new workspace '{}' to config and made it active.\n"
        "You can now run slacker normally.".format(workspace))
def main():
    with open('mockup_metadata.json', 'r') as mockup_metadata_file:
        existing_mockup_metadata_string = mockup_metadata_file.read()
    existing_mockup_metadata = load_existing_mockup_metadata(
        existing_mockup_metadata_string,
    )

    new_mockup_metadata = copy.deepcopy(existing_mockup_metadata)
    overlay_image = cv2.imread('screenshot.png')

    mockup_images = os.listdir('.')
    for image_filename in mockup_images:
        if image_filename in FILES_TO_IGNORE:
            continue
        filename_components = parse_filename_into_components(image_filename)
        if filename_components['mockup_name'] in existing_mockup_metadata:
            continue
        loaded_image = cv2.imread(image_filename)
        prepped_image = get_prepped_image(loaded_image)
        try:
            screen_contour = get_screen_contour(prepped_image)
        except Exception:
            print("Could not locate screen in {}".format(image_filename))
            continue

        screen_coords = get_screen_coord_from_contour(
            screen_contour,
            filename_components['orientation'],
        )

        screen_coords_for_overlay = [
            screen_coords['topLeft'],
            screen_coords['topRight'],
            screen_coords['bottomRight'],
            screen_coords['bottomLeft'],
        ]

        render_image(loaded_image.copy(), overlay_image, numpy.float32(screen_coords_for_overlay))
        acceptable_answer = confirm('Was the image acceptable? (y/n)')
        if acceptable_answer is False:
            should_rotate_answer = confirm('Do you want to try and rotate the image? (y/n)')
            if should_rotate_answer is False:
                continue
            for permutation in permutations(screen_coords_for_overlay):
                render_image(loaded_image.copy(), overlay_image, numpy.float32(permutation))
                answer = confirm('Was the image acceptable? (y/n)')
                # Coordinates should not be in the correct order such that they
                # can be as used top left, top right, bottom right, bottom left
                print('all permutations')
                print(permutation)
                if answer is True:
                    print('selected permutation')
                    print(permutation)
                    screen_coords = {
                        'topLeft': [permutation[0][0], permutation[0][1]],
                        'topRight': [permutation[1][0], permutation[1][1]],
                        'bottomRight': [permutation[2][0], permutation[2][1]],
                        'bottomLeft': [permutation[3][0], permutation[3][1]],
                    }
                    print('new screen coords')
                    print(screen_coords)
                    break

        print('actual screen coords')
        print(screen_coords)
        image_mockup_metadata = {
            'screenCoordinates': screen_coords,
            'device': filename_components['device'],
            # 'dimensions': image_dimensions,
            'file_extension': filename_components['file_extension'],
        }

        new_mockup_metadata[filename_components['mockup_name']] = image_mockup_metadata
        # os.rename(image_filename, 'processed/' + filename_components['mockup_name'] + '.' + filename_components['file_extension'])

    print(new_mockup_metadata)
    with open('mockup_metadata.json', 'w') as mockup_metadata_file:
        mockup_metadata_file.write(json.dumps(new_mockup_metadata))

    print("Wrote new metadata to mockup_metadata.json")
#!/usr/bin/env python
"""
Example of a confirmation prompt.
"""
from __future__ import unicode_literals

from prompt_toolkit.shortcuts import confirm

if __name__ == '__main__':
    answer = confirm('Should we do that? (y/n) ')
    print('You said: %s' % answer)
#!/usr/bin/env python
"""
Example of a confirmation prompt.
"""
from __future__ import unicode_literals

from prompt_toolkit.shortcuts import confirm

if __name__ == '__main__':
    answer = confirm('Should we do that?')
    print('You said: %s' % answer)