Exemplo n.º 1
0
def find_the_description(patterns, *, num_of_questions=10, num_of_answers=4):

    question_text = 'What is the description of {} pattern?'
    result = 0
    all_patterns = list(patterns.keys())

    if num_of_questions > len(patterns):
        num_of_questions = len(patterns)

    for i in range(num_of_questions):

        question_pattern = choice(all_patterns)
        all_patterns.remove(question_pattern)
        current_patterns = _get_patterns_for_question(patterns,
                                                      question_pattern,
                                                      num_of_answers)

        print_question(i + 1, question_text.format(question_pattern), [
            patterns[name]['description'].replace(name, '*' * 5)
            for name in current_patterns
        ])

        answer = validate_input(len(current_patterns))
        answer = patterns[current_patterns[answer - 1]]

        result += check_answer(answer['description'],
                               patterns[question_pattern]['description'])

    print_result(result, num_of_questions)
Exemplo n.º 2
0
def existing_vault() -> Vault:
    """
    Open an existing vault.

    :return:
    """

    print("Found an existing vault.")
    print("Please input the password for that vault.")
    vault_key = validate_input(
        ": ",
        lambda x: 8 <= len(x) <= 32 and x.isprintable(),
        err_text=
        "Has to be at least 8 characters long, max 32. No weird characters.\n")

    # Key is provided for existing vault. Try to open it.
    vault = Vault(vault_key.encode("utf-8"))
    try:
        vault.unlock_vault()
        vault.lock_vault()
    except ValueError:
        print("\nInvalid vault key provided.")
        exit(0)

    # Remove vault key from memory for security.
    del vault_key

    return vault
Exemplo n.º 3
0
def add_item():
    user_id = websession.get('user_id')
    if not authed_user(user_id):
        # websession['auth_redir'] = 'add_item'
        return redirect(url_for('signin'))

    if request.method == 'GET':
        categories = session.query(Category).order_by(Category.name).all()

        return render_template('item-cud.html', cud_type='Add', categories=categories,
                               item={'picture': DEFAULT_PHOTO, 'category': {}})
    elif request.method == 'POST':
        # Retrieve form data - use .get to avoid 400 status
        item_name = request.form.get('name')
        item_description = request.form.get('description')
        picture_file = request.files.get('file')
        category_name = request.form.get('category')

        # Input validation
        status, error = validate_input(item_name, item_description, category_name)

        # Deal with picture
        if picture_file:
            try:
                # filename is the path to the image
                filename = DEFAULT_PHOTO_STORE + uploaded_photos.save(picture_file)
                flash('Photo Successfully Uploaded')
            except UploadNotAllowed:
                error['file_error'] = "The picture file upload wasn't allowed."
                filename = None
                status = False

        if not status:
            categories = session.query(Category).order_by(Category.name).all()
            return render_template('item-cud.html', cud_type='Add', categories=categories,
                                   item={'name': item_name, 'description': item_description,
                                         'category': {'name': category_name}},
                                   title_error=error.get('title_error'),
                                   file_error=error.get('file_error'),
                                   category_error=error.get('category_error'))

        # If no picture supplied, use default
        if not picture_file or not filename:
            filename = DEFAULT_PHOTO

        user = session.query(User).filter_by(uid=user_id).one()
        category = session.query(Category).filter_by(name=category_name).one()
        item = Item(name=item_name, picture=filename, description=item_description,
                    category_id=category.cid, user_id=user.uid)
        session.add(item)
        session.commit()
        # Add flashing...
        flash('New Item Created')

        return redirect(url_for('show_item', iid=item.iid))
Exemplo n.º 4
0
def create_item_api():
    # Allow creation of one or multiple items through a single POST
    # Content:
    # * Single: {'item': {'name': 'item-name', 'description': 'item-description',
    #                     'category_name': 'item-category'}}
    # * Multiple: {'items': [{'name': 'item-name', 'description': 'item-description',
    #                         'category_name': 'item-category'},
    #                        {<next-item...>}]}
    if valid_json(request.headers.get('content-type')):
        data = request.get_json()
    else:
        return jsonify(
            error="Unsupported content-type - expecting application/json."
        ), 400

    # Determine if single or multiple items
    new_item = data.get('item')
    new_items = data.get('items')

    # Single item?
    if new_item:
        name = new_item.get('name')
        description = new_item.get('description')
        category_name = new_item.get('category_name')

        status, error = validate_input(name, description, category_name)
        # True means item not in database - this is what we want
        if status:
            user = g.user
            category = session.query(Category).filter_by(
                name=category_name).one()
            filename = DEFAULT_PHOTO

            item = Item(name=name,
                        description=description,
                        picture=filename,
                        category_id=category.cid,
                        user_id=user['uid'])
            session.add(item)
            session.commit()

            return jsonify(item=item.serialize), 201
        # Problems
        else:
            return jsonify(error=error), 406
    # Multiple items?
    elif new_items:
        # Parse through each item, validate, and add if good
        # Need to keep track of successes and failures and report on at the end
        # This last part could be tricky...

        return jsonify(error='Not implemented...')
    # Didn't receive valid data
    else:
        return jsonify(error="Couldn't find item/items in JSON data."), 400
Exemplo n.º 5
0
def update_item_api(iid):
    # Content:  {'item': {'name': 'new--name', 'description': 'new-description',
    #                     'category_name': 'new-category'}}
    # Note - cannot change picture through this view
    if valid_json(request.headers.get('content-type')):
        data = request.get_json()
        update_item = data.get('item')
    else:
        return jsonify(
            error="Unsupported content-type - expecting application/json."
        ), 400

    if update_item:
        try:
            item = session.query(Item).filter_by(iid=iid).one()
        except NoResultFound as e:
            item = None

        if item:
            if g.user['uid'] != item.user_id:
                return jsonify(error='Not authorized'), 403

            name = update_item.get('name')
            description = update_item.get('description')
            category_name = update_item.get('category_name')

            status, error = validate_input(name, description, category_name)
            if not status:
                # Check if only problem is non-unique name/title (OK since updating):
                valid_set = {'title_error', 'title_problem'}
                # Where overwriting existing item, make sure item.name (looked up from passed
                # iid) matches item_name or we'll get a database error!
                if not (error.get('title_problem') == 'nonunique'
                        and item.name == name and valid_set == set(error)):
                    return jsonify(error=error), 406

            category = session.query(Category).filter_by(
                name=category_name).one()

            # Update
            item.name = name
            item.description = description
            item.category_id = category.cid
            session.add(item)
            session.commit()

            return jsonify(item=item.serialize)
        # Category doesn't exist
        else:
            return jsonify(error="Category ID doesn't exist."), 422
    # Didn't receive valid data
    else:
        return jsonify(error="Couldn't find item in JSON data."), 400
Exemplo n.º 6
0
def new_vault() -> Vault:
    """
    Generate a new vault.

    :return:
    """

    print("No existing vault detected.")
    print("To create a new vault, create a password below.")
    vault_key = validate_input(
        "Password for new vault: ",
        lambda x: 8 <= len(x) <= 32 and x.isprintable(),
        err_text=
        "It needs to be at least 8 characters, max 32. (no weird characters).\n"
    )

    # Make a new vault object.
    vault = Vault(vault_key.encode("utf-8"))

    # Remove vault key from memory for security.
    del vault_key

    return vault
Exemplo n.º 7
0
def edit_item(iid):
    user_id = websession.get('user_id')
    if not authed_user(user_id):
        # websession['auth_redir'] = 'edit_item'
        return redirect(url_for('signin'))

    # This could return none - use one_or_none instead!
    item = session.query(Item).filter_by(iid=iid).one()

    # Authorization Check
    if item.user_id != user_id:
        print('item.user_id ({}) != user_id ({})'.format(item.user_id, user_id))
        abort(403)

    if request.method == 'GET':
        categories = session.query(Category).order_by(Category.name).all()

        return render_template('item-cud.html', cud_type='Edit', categories=categories,
                               item=item)
    elif request.method == 'POST':
        # Retrieve form data - use .get to avoid 400 status
        item_name = request.form.get('name')
        item_description = request.form.get('description')
        picture_file = request.files.get('file')
        category_name = request.form.get('category')

        # Input validation
        status, error = validate_input(item_name, item_description, category_name)

        # Deal with picture
        if picture_file:
            try:
                # filename is the path to the image
                filename = DEFAULT_PHOTO_STORE + uploaded_photos.save(picture_file)
                flash('Photo Successfully Uploaded')
            except UploadNotAllowed:
                error['file_error'] = "The picture file upload wasn't allowed."
                filename = None
                status = False

        if not status:
            # Check if only problem is non-unique name/title (OK since updating):
            valid_set = {'title_error', 'title_problem'}
            # Where overwriting existing item, make sure item.name (looked up from passed
            # iid) matches item_name or we'll get a database error!
            if not (error.get('title_problem') == 'nonunique' and item.name == item_name
                    and valid_set == set(error)):
                categories = session.query(Category).order_by(Category.name).all()
                return render_template('item-cud.html', cud_type='Edit', categories=categories,
                                       item={'name': item_name, 'description': item_description,
                                             'category': {'name': category_name}},
                                       title_error=error.get('title_error'),
                                       file_error=error.get('file_error'),
                                       category_error=error.get('category_error'))

        category = session.query(Category).filter_by(name=category_name).one()

        # Only change picture if new one supplied
        if not picture_file or not filename:
            filename = item.picture

        # Update
        item.name = item_name
        item.picture = filename
        item.description = item_description
        item.category_id = category.cid
        item.user_id = user_id
        session.add(item)
        session.commit()
        # Add flashing...
        flash('Item Updated')

        return redirect(url_for('show_item', iid=item.iid))
Exemplo n.º 8
0
from config import games
from helpers import get_patterns, validate_input


def print_games(games):
    print('\nEnter the number of game you want to play:\n')

    for game_num, game in enumerate(games):
        print('Game {}. {}\n'.format(game_num + 1, game.__name__.capitalize()))

    print('{}. Exit game'.format(len(games) + 1))


if __name__ == '__main__':
    patterns = get_patterns('patterns.json')

    games_num = len(games) + 1

    while True:
        print_games(games)
        game = validate_input(games_num)
        if game == games_num:
            break
        games[game - 1](patterns)
Exemplo n.º 9
0
        # Make the move.
        board_obj.make_move(move)

        # Notify the player of the new board.
        board_obj.print_grid()

    # Print the winner.
    print("\nThe game ended!")
    print(f"Player {board_obj.get_player_icon(board_obj.winner)} won!")


if __name__ == '__main__':
    try:
        # Ask the user for parameters.
        grid_size = int(
            validate_input("Size of the grid: ", lambda x: x.isnumeric()))
        amount_of_players = int(
            validate_input("Amount of players: ", lambda x: x.isnumeric()))
        player_symbols = validate_input(
            "Enter the symbols for the players, separated by space.\n",
            lambda x: len(set(x.split())) >= amount_of_players).split(
            )[:amount_of_players]
        player_symbols = [x[:1] for x in player_symbols
                          ]  # Only use the first character of each symbol.

        # Create the Board class
        board = TicTacToe(grid_size=grid_size,
                          players=amount_of_players,
                          player_symbols=player_symbols)

        # Run the main function.
Exemplo n.º 10
0
def main():
    print("Welcome to the Password Vault!")

    # Gather input.
    vault = get_vault()

    print()
    print("\nLogged into the vault.")

    # Run the menu.
    menu = True
    while menu:
        print("\nPlease choose what you want to do.")
        print("1: Store a new password.")
        print("2: Generate a new password.")
        print("3: Retrieve a password.")
        print("4: Delete a password.")
        print("5: Show the list of saved services.\n")
        print("0: Exit and lock the vault.\n")

        option = int(validate_input("> ", lambda x: 0 <= int(x) <= 5))

        # Exit.
        if option == 0:
            print("\nLocking vault...")
            vault.lock_vault()

            print("Thanks for using EyeDevelop's Vault!")
            menu = False

        # Store a password.
        elif option == 1:
            service = validate_input("Please enter the service name: ",
                                     lambda x: x.isprintable() and len(x) > 0)
            password = validate_input("Please enter the password: "******"Saved!")

        # Generate a password.
        elif option == 2:
            service = validate_input("Please enter the service name: ",
                                     lambda x: x.isprintable() and len(x) > 0)
            length = int(
                validate_input("Enter the length of the password: "******"\n\nIt's time to choose complexity.")
            print(
                "Complexity is built of three numbers. The letter complexity, number complexity and symbol complexity."
            )
            print("\nFirst up is letter complexity.")
            print(
                "0 = No letters, 1 = Only lowercase, 2 = Only uppercase, 3 = Mixed case."
            )
            letter_complexity = validate_input("> ",
                                               lambda x: 0 <= int(x) <= 3)

            print("\nNow the number complexity.")
            print("0 = No digits, 1 = Use digits.")
            digit_complexity = validate_input("> ", lambda x: 0 <= int(x) <= 1)

            print("\nFinally, the symbol complexity.")
            print("0 = No symbols, 1 = Use symbols.")
            symbol_complexity = validate_input("> ",
                                               lambda x: 0 <= int(x) <= 1)

            complexity = letter_complexity + digit_complexity + symbol_complexity

            password = vault.generate_password(service, length, complexity)
            print("Your generated password:"******"\nAlso stored in vault.")

        # Retrieve password for service.
        elif option == 3:
            service = validate_input("Please enter the service name: ",
                                     lambda x: x.isprintable() and len(x) > 0)

            if service in vault.get_services():
                print("Your password for {}: {}".format(
                    service, vault.get_password(service)))
            else:
                print("That service is not stored in the vault.")

        # Delete service.
        elif option == 4:
            service = validate_input("Please enter the service name: ",
                                     lambda x: x.isprintable() and len(x) > 0)

            vault.delete_service(service)

            print("Deleted {}.".format(service))

        # Print services.
        elif option == 5:
            services = vault.get_services()

            print("Your services ({}):\n".format(len(services)))
            for service in services:
                print(service)