Example #1
0
 def cli_generate():
     do_create = inquirer.confirm("Do you want to create the project file right now?")
     if do_create:
         # questions to prompt the user
         project_queries = [
             inquirer.Text("name", "Enter the name of the project"),
             inquirer.List("type", "Enter the type of project", [e.value for e in ProjectType]),
         ]
         # ask questions and get answers
         answer = inquirer.prompt(project_queries)
         # create an author from CLI prompt
         author: Author = Author.create_author()
         # subprojects list, which is empty presently
         subprojects = []
         spcreateprompt = inquirer.Text("name", "Enter the name of the new subproject")
         # add any generated projects here, for each generated project, create
         # an empty directory also
         while True:
             if subprojects == []:
                 if inquirer.confirm("No subprojects created. Create one?"):
                     spname = inquirer.prompt([spcreateprompt])["name"]
                     if inquirer.confirm(f"Do you want to continue creating '{spname}'?"):
                         sp_pathname = os.path.join(os.getcwd(), spname)
                         if not os.path.exists(sp_pathname):
                             os.makedirs(spname)
                         subprojects.append(spname)
                         Subproject.generate_subproject(spname, answer["name"], author.name)
                 else:
                     break
             else:
                 if inquirer.confirm("Do you want to create more subprojects?"):
                     spname = inquirer.prompt([spcreateprompt])["name"]
                     if inquirer.confirm(f"Do you want to continue creating {spname}?"):
                         os.makedirs(os.path.join(os.getcwd(), spname))
                         subprojects.append(spname)
                         Subproject.generate_subproject(spname, answer["name"], author.name)
                 else:
                     break
         # return the generated project
         try:
             project_config = Project(
                 {
                     Project.AUTHOR: author.to_dict(),
                     Project.NAME: spname,
                     Project.TYPE_OF_PROJECT: answer["type"],
                     Project.SUBPROJECTS: subprojects,
                 }
             )
             print(project_config.to_yaml())
             with open(os.path.join(os.getcwd(), Project.PROJECT_FILE), "w") as project_out:
                 project_out.write(project_config.to_yaml())
                 print("Project configuration written")
         except TypeError as te:
             print(te)
             return None
Example #2
0
def main():
    """main method"""
    try:
        utils.clear()
        print(color('    ┌──────────────────────────────────────────┐', fg='#b61042'))
        print(color('    │       ', fg='#b61042') +
              color(f'π-hole 5 list tool  v{__version__}', '#FFF') + color('         │', fg='#b61042'))
        print(color('    └──────────────────────────────────────────┘', fg='#b61042'))
        utils.info('    https://github.com/jessedp/pihole5-list-tool\n')
        utils.danger('    Do not hit ENTER or Y if a step seems to hang!')
        utils.danger("    Use CTRL+C if you're sure it's hung and report it.\n")

        db_file = ''
        use_docker = False
        docker = utils.find_docker()

        if docker[0] is True:
            utils.success(f'Found Running Docker config: {docker[1]}')
            use_docker = inquirer.confirm('Use Docker-ized config?', 'n')
            if use_docker:
                db_file = docker[1]

        if not use_docker:
            db_file = inquirer.ask_db()

        list_type = inquirer.ask_list_type()

        if list_type == constants.BLACKLIST:
            process_blacklists(db_file)

        if list_type == constants.WHITELIST:
            process_whitelists(db_file)

        if inquirer.confirm('Update Gravity for immediate effect?'):
            print()
            if use_docker:
                os.system('docker exec pihole bash "/usr/local/bin/pihole" "-g"')
            else:
                os.system('pihole -g')
        else:
            if use_docker:
                utils.info('Update Gravity through the web interface or by running:\n\t' +
                           '# docker exec pihole bash "/usr/local/bin/pihole" "-g"')

            else:
                utils.info(
                    'Update Gravity through the web interface or by running:\n\t# pihole -g')

            utils.info('\n\tBye!')

    except (KeyboardInterrupt, KeyError):
        sys.exit(0)
Example #3
0
def get_channel_id(token: str,
                   name: str,
                   session: Optional[Session] = None) -> str:
    # Strip off # prefix if specified
    if name.startswith('#'):
        name = name[1:]

    client = get_client(token, session=session)
    start_query = True
    cursor = None
    while start_query or cursor:
        start_query = False
        try:
            # Query 1000 at a time (the max supported) to keep the number of requests lower
            response = client.conversations.list(
                types=['public_channel', 'private_channel'],
                cursor=cursor,
                limit=1000)
        except Exception as e:
            if inquirer.confirm(
                    f'Encountered error while retrieving channel ID for {name} ({e}), retry?',
                    default=True):
                return get_channel_id(token, name, session=session)
            raise
        channels = response.body['channels']
        for channel in channels:
            if channel['name'] == name:
                return channel['id']
        cursor = response.body.get('response_metadata', {}).get('next_cursor')
    raise Exception(
        f'Could not find channel {name} in list of channels for this user')
Example #4
0
    def confirmation_yesno(self, question, default=False, exit_on_false=True):
        reply = inquirer.confirm(question, default=default)

        if reply is False and exit_on_false is True:
            self.exit()

        return reply
Example #5
0
    def create(self):
        config = ConfigParser()
        print("Looks like this is the first time you are running wrap.")

        _continue = inquirer.confirm(
            "Would you like to go through an interactive configuration wizard?", default=True)

        if not _continue:
            print("The configuration is incomplete. Manually fill in the ~/.wraprc with the required values")
            return

        print("Please provide the path to the script folder:")
        script_folder_prompt = \
            inquirer.Path('script_folder', normalize_to_absolute_path=True,
                          path_type=inquirer.Path.DIRECTORY, exists=True)

        prompt = inquirer.prompt([script_folder_prompt])

        config["Main"] = {
            "ScriptFolder": prompt.get("script_folder")
        }
        with open(self._path, "w") as fp:
            config.write(fp)

        print("Configuration has been successfully created.")
Example #6
0
 def sub_interactive_loop_make_a_guess(self, name):
     guess = ""
     while len(guess) == 0 or len(guess) > 1:
         guess = inquirer.text(message="Type a letter to guess...")
     link = self.send_post_message(name, "guess", guess)
     if link:
         status = "PENDING"
         counter = 0
         while status == "PENDING":
             ret_json = self.send_get_message(link)
             status = ret_json["data"][0]["status"]
             counter += 1
             sleep(1)
             if counter >= 10:
                 break
     state = self.send_get_message(
         VALIDATOR_ENDPOINT_STATE.format(_make_hm_address(name)))
     decoded_state = self.decode(state["data"])
     game = loads(decoded_state)
     current_game = game[-1]
     self.print_game(current_game)
     if current_game["state"] == 1:
         again = inquirer.confirm("Guess again?", default=True)
         if again:
             self.sub_interactive_loop_make_a_guess(name)
Example #7
0
def put(name):
    if name in get_builds():
        if not inquirer.confirm(
                "There is already a build with that name. Do you want to replace it?",
                default=False):
            return

    upload_build(name)
Example #8
0
def delete(name):
    if name is None:
        name = inquirer.list_input('Which model would you like to delete?',
                                   choices=get_builds())

    if inquirer.confirm(
            "This will permanently delete your model. Do you want to continue?",
            default=False):
        delete_build(name)
Example #9
0
async def menu_new_action(api):
    rests = await print_rests(api)
    prepared_lots = await prepare_lots(rests)
    print(Fore.MAGENTA + '-----')
    if len(prepared_lots):
        print_prepared_lots(prepared_lots)
        if console.confirm('Sell prepared lots?', default=True):
            await sell_prepared_lots(api, prepared_lots)
    else:
        print(Fore.YELLOW + 'You did not prepared any lots.')
Example #10
0
    def should_continue():
        question = [inquirer.confirm("continue",
                                     message="¿Debería continuar?")]

        answers = inquirer.prompt(question)

        if answers is True:
            pass

        else:
            sys.exit(0)
Example #11
0
def change_text(property: str, value: str) -> Tuple[bool, str]:
    text_modify_question = inquirer.Text(
        name="property",
        message=f"Modify {colorama.Fore.BLUE}{property}{colorama.Fore.RESET}",
        default=value,
    )
    answer = inquirer.prompt([text_modify_question])["property"].strip()
    if inquirer.confirm(
            f"Are you sure you want to change {colorama.Fore.BLUE}{property}{colorama.Fore.RESET} to {colorama.Fore.YELLOW}{answer}{colorama.Fore.RESET}?"  # noqa: E501
    ):
        return (True, answer)
    return (False, None)
Example #12
0
def process_blocklists(db_file):
    """ prompt for and process blocklists """
    source = inquirer.ask_blocklist()

    import_list = []

    if source in blockLists:
        url_source = blockLists[source]
        resp = requests.get(url_source["url"])
        import_list = utils.process_lines(resp.text, url_source["comment"])

    if source == constants.FILE:
        fname = inquirer.ask_import_file()
        import_file = open(fname)
        import_list = utils.process_lines(import_file, f"File: {fname}")

    if source == constants.PASTE:
        import_list = inquirer.ask_paste()
        import_list = utils.process_lines(import_list, "Pasted content")

    if len(import_list) == 0:
        utils.die("No valid urls found, try again")

    if not inquirer.confirm(
            f"Add {len(import_list)} block lists to {db_file}?"):
        utils.warn("Nothing changed. Bye!")
        sys.exit(0)

    conn = sqlite3.connect(db_file)
    sqldb = conn.cursor()
    added = 0
    exists = 0
    for item in import_list:
        sqldb.execute("SELECT COUNT(*) FROM adlist WHERE address = ?",
                      (item["url"], ))

        cnt = sqldb.fetchone()

        if cnt[0] > 0:
            exists += 1
        else:
            added += 1
            vals = (item["url"], item["comment"])
            sqldb.execute(
                "INSERT OR IGNORE INTO adlist (address, comment) VALUES (?,?)",
                vals)
            conn.commit()

    sqldb.close()
    conn.close()

    utils.success(f"{added} block lists added! {exists} already existed.")
Example #13
0
    def edit_contact(cls, contact: dict, contacts_dict: dict,
                     groups_dict: dict) -> None:
        if len(groups_dict) > 0:
            field = inquirer.List(
                'field',
                message='Choose field to edit',
                choices=['name', 'email', 'phone', 'groups', 'Remove Contact'])
            edit = inquirer.prompt([field])
        else:
            field = inquirer.List(
                'field',
                message='Choose field to edit',
                choices=['name', 'email', 'phone', 'Remove Contact'])
            edit = inquirer.prompt([field])

        if edit['field'] == 'name':
            edit = inquirer.prompt([
                inquirer.Text('first', message='Enter New First Name'),
                inquirer.Text('last', message='Enter New Last Name')
            ])
            new_name = (edit['first'] + " " + edit['last']).title()
            contacts_dict[new_name] = contacts_dict.pop(contact['name'])
            contacts_dict[new_name]['name'] = new_name
        elif edit['field'] == 'email':
            edit = inquirer.prompt([
                inquirer.Text('email',
                              message='Enter New Email',
                              validate=cls.email_validation)
            ])
            contacts_dict[contact['name']]['email'] = edit['email']
        elif edit['field'] == 'phone':
            edit = inquirer.prompt([
                inquirer.Text('phone',
                              message='Enter new phone number ##########',
                              validate=cls.phone_validation)
            ])
            contacts_dict[contact['name']]['phone'] = edit['phone']
        elif edit['field'] == 'groups':
            message = 'Choose groups \033[3m(select using > arrow key)\033[0m'
            edit = inquirer.prompt([
                inquirer.Checkbox('groups',
                                  message=message,
                                  choices=groups_dict.keys())
            ])
            contacts_dict[contact['name']]['groups'] = edit['groups']
        elif edit['field'] == 'Remove Contact':
            check = inquirer.confirm("Are you sure you want to delete?",
                                     default=False)
            if check:
                del contacts_dict[contact['name']]
        return contact
Example #14
0
def get_phone_number():
    try:
        with open('config.json', 'r') as f:
            phone_number = json.load(f)['number']
        correct = console.confirm(
            f'Old config file found. Your number is {phone_number}, correct?',
            default=True)
        if correct:
            return phone_number
    except FileNotFoundError:
        print(Fore.RED + 'Config file not found')
    except json.decoder.JSONDecodeError:
        print(Fore.RED + 'Bad config file')
    phone_number = input_phone_number()
    return phone_number
Example #15
0
def aStcWrap(pth):
    """Advanced mode is pretty trash
    """
    print('\nAdvanced Stitch\n---------------')
    print('Leaving fields blank will result in defaults being used')
    print('WARNING: The entry fields are finicky, and capture ALL input. ' +
          'If you try to use backspace, the value will be rejected.')
    print(f'Drawing from {pth}\n')

    cF = text('Desired Crop Factor (num 0.01 - 1, def 0.75)')
    if not cF:
        cF = 0.75
    try:
        cF = float(cF)
    except ValueError:
        print('Value entered is not a number, using default')
        cF = 0.75
    if cF > 1 or cF < 0.01:
        print('Value entered is outside acceptable range, using default')
        cF = 0.75
    print(f'Crop Factor is {cF}\n')

    fF = text('Desired Feather Radius (num 0.01 - 1, def 0.15)')
    if not fF:
        fF = 0.15
    try:
        fF = float(fF)
    except ValueError:
        print('Value entered is not a number, using default')
        fF = 0.15
    if fF > 1 or fF < 0.01:
        print('Value entered is outside acceptable range, using default')
        fF = 0.15
    print(f'Feather Radius is {fF}\n')

    icon = confirm('Mark player position?', default=True)
    print(f'Mark Player = {icon}\n')

    try:
        return stitch.stitch2(pth,
                              '',
                              cF,
                              fF,
                              icon)
    except FileNotFoundError:
        print(errstr)
        print(f'Bad Path: {pth}\n')
        return 0
Example #16
0
    def send_email(cls, current_user, contacts_dict, groups_dict):
        to = ManageContacts.select_contact(contacts_dict)
        subject = inquirer.text(message="Enter email subject")
        message_text = FollowUp.get_email_contents()

        os.system('clear')
        print(f"\nSubject: {subject}\n\n{message_text}\n")
        message = "Are you sure you want to send?"
        send = inquirer.confirm(message, default=False)
        if send:
            EmailSetup.send_message(
                EmailSetup.create_message(to['email'], subject, message_text),
                current_user)
            FollowUp.set_dates(to, groups_dict)
        else:
            print("Message deleted.")
Example #17
0
def change_int(property: str, value: int) -> Tuple[bool, int]:
    int_modify_question = inquirer.Text(
        name="property",
        message=f"Modify {colorama.Fore.BLUE}{property}{colorama.Fore.RESET}",
        default=value,
        validate=lambda _, x: match("^\d[\d]+$", x),  # noqa: W605
        # ^^^ is a legitimate use of '\d', don't remove the warning.
    )
    try:
        answer = int(inquirer.prompt(int_modify_question)["property"].strip())
        if inquirer.confirm(
                f"Are you sure you want to change {colorama.Fore.BLUE}{property}{colorama.Fore.RESET} to {colorama.Fore.YELLOW}{answer}{colorama.Fore.RESET}"  # noqa: E501
        ):
            return (True, answer)
        return (False, None)
    except ValueError as ve:
        raise ve
Example #18
0
    def __confirm_delete(self, name: str):
        """
        Asks user (in terminal) to confirm deletion of a given profile.

        If confirmation is received, profile name is passed to remove_player()
        method to delete from roster.

        Args:
            name (str): Name of player profile to be deleted.
        """
        self.clear_screen()
        self.print_logo()
        delete = inquirer.confirm(
                f"Do you want to remove '{name}'?", default=True
                )
        if delete:
            self.__remove_player(name)
            input(f"'{name}' removed. Press ENTER to continue.")
Example #19
0
    def edit_groups(cls, selected_group, groups_dict, contacts_dict):
        def group_validation(answers, current):
            if current in groups_dict.keys():
                message = "Group name in use."
                raise inquirer.errors.ValidationError('', reason=message)
            return True

        os.system('clear')
        edit = inquirer.prompt([
            inquirer.List(
                'field',
                message='Choose field to edit',
                choices=['Group Name', 'Days Between Contact', 'Remove Group'])
        ])

        os.system('clear')
        if edit['field'] == 'Group Name':
            edit = inquirer.prompt([
                inquirer.Text('name',
                              message='Enter new group name',
                              validate=group_validation)
            ])
            edit['name'] = edit['name'].lower()
            groups_dict[edit['name']] = groups_dict.pop(selected_group)
            for contact in contacts_dict:
                if selected_group in contacts_dict[contact]['groups']:
                    contacts_dict[contact]['groups'].remove(selected_group)
                    contacts_dict[contact]['groups'].append(edit['name'])
        elif edit['field'] == 'Days Between Contact':
            edit = inquirer.prompt([
                inquirer.Text('days',
                              message='Enter new days between contact',
                              validate=Groups.day_validation)
            ])
            groups_dict[selected_group] = edit['days']
        elif edit['field'] == 'Remove Group':
            message = "Are you sure you want to delete?"
            check = inquirer.confirm(message, default=False)
            if check:
                del groups_dict[selected_group]
                print("Deleted.")
                for person in contacts_dict:
                    if selected_group in contacts_dict[person]['groups']:
                        contacts_dict[person]['groups'].remove(selected_group)
Example #20
0
def get_messages(
    token: str,
    channel_id: str,
    start_timestamp: Optional[str],
    end_timestamp: Optional[str],
    direction: bool,
    batch_size: Optional[int],
    session: Optional[Session] = None
) -> Tuple[List[dict], Optional[str], Optional[str]]:
    """
    Retrieves a list of messages
    :return: Tuple of messages sorted according to the direction and the start/end timestamps
    """
    client = get_client(token, session=session)
    if direction == DIRECTION_OLDER:
        timestamp_args = {'latest': start_timestamp}
    else:
        timestamp_args = {'oldest': end_timestamp}
    try:
        response = client.conversations.history(channel_id,
                                                limit=batch_size,
                                                **timestamp_args)
    except Exception as e:
        if inquirer.confirm(
                f'Encountered error while retrieving messages ({e}), retry?',
                default=True):
            return get_messages(token,
                                channel_id,
                                start_timestamp,
                                end_timestamp,
                                direction,
                                batch_size,
                                session=session)
        # Return nothing since we did not retry
        return [], None, None
    # The messages are already in reverse age order, with the latest chronologically at the front of the list
    messages = response.body['messages']
    if direction == DIRECTION_OLDER:
        start_timestamp = messages[-1]['ts'] if len(messages) > 0 else None
    else:
        # If we want newer messages, reverse the order
        messages.reverse()
        end_timestamp = messages[-1]['ts'] if len(messages) > 0 else None
    return messages, start_timestamp, end_timestamp
Example #21
0
async def activate_timer_if_needed(api: Tele2Api):
    if console.confirm('Activate lot auto-selling timer?'):
        interval = input_auto_resell_interval()
        print(Fore.GREEN +
              f'Timer activated! Your lots will be relisted every '
              f'{interval} sec.')
        iteration = 1
        while True:
            print(Fore.WHITE + f'\nSleeping for {interval} sec...')
            time.sleep(interval)
            print(Fore.CYAN + f'Relisting (iteration #{iteration})...\n')
            deleted_lots = await delete_active_lots(api)
            if not len(deleted_lots):
                print(Fore.GREEN +
                      'All lots have been sold! Deactivating the timer...')
                await print_balance(api)
                break
            await menu_again_action(api, deleted_lots)
            iteration += 1
Example #22
0
def draw(mOps):
    global outPath
    getPathLists()

    targ = list_input(
        'Select which seed you want to map',
        choices=rawPaths+mOps)
    if targ == 'Exit' or targ == 'Main Menu':
        return targ
    pth = '.\\raws\\' + targ
    adv = confirm('Use Advanced Mode?', default=False)
    if adv:
        outPath = aStcWrap(pth)
        if not outPath:
            draw()
        else:
            naxt(pth)
    else:
        outPath = stcWrap(pth)
        if not outPath:
            draw()
        else:
            naxt(pth)
Example #23
0
def ciphertext_write_prompt(ciphertext: str):
    # Ask for ciphertext destination
    destination = inquirer.list_input("Choose result destination",
                                      choices=["Terminal Output", "File"])

    group_by_five = inquirer.confirm("Group result by 5 characters?",
                                     default=False)

    if group_by_five:
        temporary_ciphertext = ""

        for idx, elem in enumerate(ciphertext):
            temporary_ciphertext += elem
            if idx % 5 == 4:
                temporary_ciphertext += " "

        ciphertext = temporary_ciphertext

    if destination == "Terminal Output":
        print(ciphertext)

    elif destination == "File":
        question = [
            inquirer.Path(
                "file_path",
                message="path to ciphertext file",
                path_type=inquirer.Path.FILE,
            ),
        ]

        ciphertext_file_path = inquirer.prompt(question)

        hf.write_file_from_string(ciphertext,
                                  ciphertext_file_path['file_path'])

    else:
        raise NotImplementedError
Example #24
0
    def __add_players(self):
        """Asks records player names.

        Args:
            self (Console): an instance of Console.
        """
        players_list = []
        players_list.extend([("NEW PLAYER", "**new**")])
        players_list.extend(self._roster.get_roster())
        players_list.extend([("BACK TO MENU", "**menu**")])

        players = [
            inquirer.List(
                'selection',
                message="ADD/REMOVE (Use ↑ and ↓ to select, ENTER to confirm)",
                choices=players_list,
                default="NEW PLAYER",
                carousel=True)
        ]

        self.clear_screen()
        self.__print_logo()
        selection = inquirer.prompt(players)['selection']

        if selection == "**menu**":
            pass
        elif selection == "**new**":
            name = self.__prompt_name()
            if name:
                self._roster.add_player(name)
        else:
            delete = inquirer.confirm(f"Do you want to remove '{selection}'?",
                                      default=True)
            if delete:
                self._roster.remove_player(selection)
            input(f"'{selection}' removed. Press ENTER to continue.")
Example #25
0
import os
import sys

sys.path.append(os.path.realpath("."))
import inquirer  # noqa

text = inquirer.text(message="Enter your username")
print(text)
password = (inquirer.password(message="Please enter your password"),)
print(password)
checkbox = inquirer.checkbox(message="Please define your type of project?", choices=["common", "backend", "frontend"])
print(checkbox)
choice = inquirer.list_input("Public or private?", choices=["public", "private"])
print(choice)
correct = inquirer.confirm(
    "This will delete all your current labels and " "create a new ones. Continue?", default=False
)
print(correct)
Example #26
0
def process_whitelists(db_file):
    """ prompt for and process blacklists """
    source = inquirer.ask_whitelist()

    import_list = []

    if source in whiteLists:
        url_source = whiteLists[source]
        resp = requests.get(url_source['url'])
        import_list = utils.process_lines(resp.text, url_source['comment'], False)
        # This breaks if we add a new whitelist setup
        if source != ANUDEEP_WHITELIST:
            resp = requests.get(ANUDEEP_WHITELIST)
            import_list += utils.process_lines(resp.text, url_source['comment'], False)

    if source == constants.FILE:
        fname = inquirer.ask_import_file()
        import_file = open(fname)
        import_list = utils.process_lines(import_file.read(), f'File: {fname}', False)

    if source == constants.PASTE:
        import_list = inquirer.ask_paste()
        import_list = utils.process_lines(import_list, 'Pasted content', utils.validate_host)

    if len(import_list) == 0:
        utils.die('No valid urls found, try again')

    if not inquirer.confirm(f'Add {len(import_list)} white lists to {db_file}?'):
        utils.warn('Nothing changed. Bye!')
        sys.exit(0)

    conn = sqlite3.connect(db_file)
    sqldb = conn.cursor()
    added = 0
    exists = 0
    for item in import_list:
        sqldb.execute(
            "SELECT COUNT(*) FROM domainlist WHERE domain = ?",
            (item['url'],))

        cnt = sqldb.fetchone()

        if cnt[0] > 0:
            exists += 1
        else:
            # 0 = exact whitelist
            # 2 = regex whitelist
            domain_type = 0
            if item['type'] == constants.REGEX:
                domain_type = 2

            vals = (item['url'], domain_type, item['comment'])
            sqldb.execute(
                'INSERT OR IGNORE INTO domainlist (domain, type, comment) VALUES (?,?,?)', vals)
            conn.commit()
            added += 1

    sqldb.close()
    conn.close()

    utils.success(f'{added} whitelists added! {exists} already existed.')
Example #27
0
import bcrypt,getpass
import setup,dal,menu

sys.path.append(os.path.realpath("."))

import inquirer
from inquirer import errors

""" Creates a database connection if it does not exist 
"""
database = "./database.db"
con = setup.create_connection(database)

""" Checks if the user has an account, if not it promts them to create one
"""
login = inquirer.confirm(message= "Do you have an account", default=True)

if (login):
    pass
else:
    username = inquirer.text(message="Enter your username")
    foundUsername = dal.get_user(con,username)
    if(foundUsername != None):
        print("The username is already taken")
    else:
        email = inquirer.text( message="Enter your email")
        pwd = getpass.getpass()
        dal.add_user(con,username,email,pwd.encode())

""" Login into user's account and display the internal menu
"""
Example #28
0
 def cli_manage():
     project_path = os.path.join(os.getcwd(), Project.PROJECT_FILE)
     if not os.path.exists(project_path):
         Project.cli_generate()
     else:
         project_config = yaml.safe_load(open(project_path, "r"))
         project_config: "Project" = Project(project_config)
         print(project_config.to_dict())
         current_config = deepcopy(project_config)
         is_modified = False
         # CLI Loop
         while True:
             root_prompt = inquirer.List(
                 Project.CHOICE,
                 message=f"""Manage {
                         colorama.Fore.YELLOW
                     }Project {colorama.Fore.BLUE}{project_config.name} {
                         check_is_modified(is_modified, f'{colorama.Fore.GREEN}<modified>')
                     }{colorama.Fore.RESET}""",
                 choices=[
                     "Manage Subprojects",
                     "Modify Properties",
                     "Reset",
                     "View Configuration",
                     "Exit",
                 ],
             )
             try:
                 choice = inquirer.prompt([root_prompt])[Project.CHOICE]
             except TypeError:
                 continue
             if choice is None:
                 continue
             elif choice == "Exit":
                 if is_modified:
                     modify_write = inquirer.confirm(
                         "Project has been modified. Do you want to save changes?"
                     )
                     print(f"UMODIFIED:{current_config.to_dict()}")
                     print(f"MODIFIED: {project_config.to_dict()}")
                     if modify_write:
                         project_config.save_config()
                         print(
                             f"""{
                                 colorama.Fore.GREEN
                             } Configuration file saved in filepath {colorama.Fore.YELLOW}{
                                 os.path.join(os.getcwd(), Project.PROJECT_FILE)
                             }{colorama.Fore.RESET} ."""
                         )
                 break
             elif choice == "Reset":
                 project_config = deepcopy(current_config)
                 is_modified = False
             elif choice == "Manage Subprojects":
                 # SUBPROJECT LOOP
                 while True:
                     subproject_choices = list(project_config.subprojects) + [
                         "Create a subproject",
                         "Exit",
                     ]
                     subproject_prompt = inquirer.List(
                         "subproject_choice",
                         "Select Subproject to manage",
                         choices=subproject_choices,
                     )
                     subproject_choice = inquirer.prompt([subproject_prompt])[
                         "subproject_choice"
                     ]
                     if subproject_choice == "Exit":
                         break
                     elif subproject_choice == "Create a subproject":
                         # USE Subproject.generate_subproject to create a subproject here
                         # and add it to project_config.subprojects
                         spcreateprompt = inquirer.Text(
                             "subproject_name", "Enter the name for the subproject"
                         )
                         spname = inquirer.prompt([spcreateprompt])
                         if spname is not None:
                             spname = spname["subproject_name"]
                             if spname.strip() != "":
                                 os.makedirs(os.path.join(os.getcwd(), spname))
                                 project_config.subprojects.append(spname)
                                 Subproject.generate_subproject(
                                     spname, project_config.name, project_config.author.name
                                 )
                                 is_modified = True
                             else:
                                 print(
                                     f"""{
                                         colorama.Fore.RED
                                     } NO NAME GIVEN. IGNORING.{
                                         colorama.Fore.RESET
                                     }"""
                                 )
                                 break
                         else:
                             break
                     else:
                         subproject_name = subproject_choice
                         print(
                             f"""{
                                 colorama.Fore.BLUE
                             }Switching to subproject {colorama.Fore.YELLOW}{
                                 subproject_choice
                             }{colorama.Fore.RESET}"""
                         )
                         subproject_path = os.path.join(
                             os.path.dirname(project_path), subproject_name
                         )
                         print(subproject_path)
                         if os.path.exists(subproject_path):
                             sub_is_modified = Subproject.transfer_control(subproject_name)
                             if sub_is_modified:
                                 is_modified = True
                         else:
                             print(
                                 f"""{
                                     colorama.Fore.RED
                                 }PATH DOES NOT EXIST{
                                     colorama.Fore.RESET
                                 }"""
                             )
                             break
             elif choice == "Modify Properties":
                 # Choice for Project Properties
                 project_dict = project_config.to_dict()
                 keydictionary = {}
                 for var in [
                     Project.NAME,
                     Project.TYPE_OF_PROJECT,
                     # Project.AUTHOR
                 ]:
                     keydictionary[CLI_VARS_PRETTYPRINT.format(var, project_dict[var])] = var
                 keydictionary[
                     CLI_VARS_PRETTYPRINT.format(
                         Project.AUTHOR, project_dict[Project.AUTHOR][Author.NAME]
                     )
                 ] = Project.AUTHOR
                 choice_list = inquirer.List(
                     "project_key",
                     message="Select the property to modify",
                     choices=list(keydictionary.keys()),
                 )
                 try:
                     choice_property = keydictionary[
                         inquirer.prompt([choice_list])["project_key"]
                     ]
                 except TypeError:
                     continue
                 if choice_property is None:
                     continue
                 elif choice_property == Project.NAME:
                     result, answer = change_text(choice_property, project_dict[choice_property])
                     if result:
                         project_config.name = answer
                     else:
                         break
                 elif choice_property == Project.TYPE_OF_PROJECT:
                     # let user select the type of project the user needs
                     type_choices_prompt = inquirer.List(
                         "project_type",
                         "Select the property type you want to switch to",
                         choices=[ptype.value for ptype in ProjectType],
                         default=project_config.type,
                     )
                     try:
                         ptype_choice = inquirer.prompt([type_choices_prompt])["project_type"]
                         # project type changed here
                         project_config.type = ProjectType(ptype_choice)
                     except TypeError:
                         continue
                 elif choice_property == Project.AUTHOR:
                     # This is a difficult part of code, there's multiple exchange of
                     # key-value pairs, make sure to print 'keydictionary' and understand
                     # how it works.
                     author = project_config.author
                     author_dict = author.to_dict()
                     keydictionary = {}
                     keydictionary[
                         CLI_VARS_PRETTYPRINT.format(Author.NAME, author.name)
                     ] = Author.NAME
                     keydictionary[
                         CLI_VARS_PRETTYPRINT.format(Author.TYPE, author.type.value)
                     ] = Author.TYPE
                     # Select the author
                     author_choices_prompt = inquirer.List(
                         "author_prop",
                         "Select the property to modify",
                         choices=list(keydictionary.keys()),
                     )
                     answer = None
                     try:
                         answer = keydictionary[
                             inquirer.prompt([author_choices_prompt])["author_prop"]
                         ]
                     except KeyError:
                         continue
                     print(answer)
                     if answer is None:
                         continue
                     elif answer == Author.NAME:
                         result, answer = change_text(answer, author_dict[answer])
                         if result:
                             author.name = answer
                     elif answer == Author.TYPE:
                         author_type_choices = inquirer.List(
                             "author_type",
                             "Select the type of author to be changed to",
                             choices=[atype.value for atype in AuthorType],
                         )
                         try:
                             new_author_type = AuthorType(
                                 inquirer.prompt([author_type_choices])["author_type"]
                             )
                         except KeyError:
                             continue
                         author.type = new_author_type
                     project_config.author = author
                 is_modified = True
             elif choice == "View Configuration":
                 print(
                     f"{colorama.Fore.YELLOW}"
                     f"Configuration from "
                     f"{colorama.Fore.GREEN}{project_path}{colorama.Fore.RESET}"
                 )
                 print(f"{colorama.Fore.BLUE}-- START OF CONFIGURATION --{colorama.Fore.RESET}")
                 print(project_config.to_yaml())
                 print(f"{colorama.Fore.BLUE}-- END OF CONFIGURATION --{colorama.Fore.RESET}")
Example #29
0
def remove():
    index, todo = select_todo()
    if prompt.confirm('Are you sure?'):
        page.children[index].remove()
Example #30
0
                    f"For source_value '{value}' .. Use one of these concepts? ",
                    choices=concepts)
            ]
            answers = inquirer.prompt(questions)

            if answers['concepts'] == "None of the above":
                continue
            elif answers['concepts'] == "Manually insert":
                questions = [
                    inquirer.Text(name='concept_id',
                                  message="Which concept do you want to use?",
                                  validate=lambda _, x: int(x))
                ]
                answers = inquirer.prompt(questions)
                concept_id = answers['concept_id']

                concept = get_concept(concept_id)
                concept_name = concept["concept_name"]
                print(json.dumps(concept, indent=6))
                correct = inquirer.confirm(
                    f"Sure you want to add {concept_id} ({concept_name})",
                    default=True)
                if not correct:
                    continue

            else:
                concept_id = answers['concepts']['concept_id']

            value_id = obj['id']
            insert_concept_id(value_id, concept_id)
Example #31
0
import os
import sys
sys.path.append(os.path.realpath('.'))

import inquirer  # flake8: noqa

text = inquirer.text(message="Enter your username")
print(text)
password = inquirer.password(message='Please enter your password'),
print(password)
checkbox = inquirer.checkbox(message='Please define your type of project?',
                             choices=['common', 'backend', 'frontend'])
print(checkbox)
choice = inquirer.list_input("Public or private?",
                             choices=['public', 'private'])
print(choice)
correct = inquirer.confirm("This will delete all your current labels and "
                           "create a new ones. Continue?", default=False)
print(correct)