Exemple #1
0
def update_parameters():
    if current_user.role != Role.admin:
        abort(401, 'User needs to be an admin to access this route')

    data = request.get_json()
    Question.update_question_weights(data['question_weights'])
    Answer.set_unique_answer_weights(data["answer_weights"])

    Action.log_action(ActionType.configure_weights, current_user.id)

    return Response('Updated scores', 200)
Exemple #2
0
 def new_question(from_user, questions_text):
     with DataManager.session() as session:
         new_question = Question(from_user=from_user,
                                 questions_text=questions_text)
         print(new_question)
         session.add(new_question)
         session.commit()
         return DataManager.get_question_by_id(new_question.id)
Exemple #3
0
def configure_parameters():
    if current_user.role != Role.admin:
        abort(401, 'User needs to be an admin to access this route')

    res = {}
    res["question_weights"] = Question.get_question_weights()
    res["answer_weights"] = Answer.get_unique_answer_weights()

    return jsonify(Serializer.serialize_value(res))
Exemple #4
0
def reload():
    """Reload applications from CSV file."""
    if current_user.role != Role.admin:
        abort(401, 'User needs to be an admin to access this route')

    if 'applicants' not in request.files:
        abort(400, 'No file submitted')

    file = request.files['applicants']
    # if user does not select file, browser also
    # submit an empty part without filename
    if file.filename == '':
        abort(400, 'Invalid file name')

    filename = secure_filename(file.filename)

    path = os.path.join(Config.UPLOAD_FOLDER, filename)

    file.save(path)

    with open(path, encoding='utf-8') as csv_file:
        # drop rows
        Action.drop_rows()
        Answer.drop_rows()
        Application.drop_rows()
        Question.drop_rows()

        # load new rows
        try:
            start = time.perf_counter()

            question_rows = Question.insert(csv_file)
            Application.insert(csv_file, question_rows, False)

            op_time = time.perf_counter()
            print("Total insert time", op_time - start)

            Action.log_action(ActionType.reload, current_user.id)

            return Response('Reloaded applications from CSV file', 200)
        except ValueError as e:
            abort(400, str(e))
Exemple #5
0
def load_file(filename):
    questions = []
    with open(os.path.abspath(filename), 'r', encoding='utf-8-sig') as f:
        file = DictReader(f)
        for row in file:
            question = Question(question=row['question'],
                                answer=row['answer'],
                                color=row['color'],
                                category=row['category'])
            questions.append(question)
        return questions
Exemple #6
0
    def __init__(self, title, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        helvetica_20 = Font(family='Helvetica', size=20, weight='bold')

        self.title(title)
        '''
        Create the main frame from the program that encapsulates the main view
        '''
        main_frame = tk.Frame(self,
                              bg=Color.LIGHT_GREEN.description,
                              bd=3,
                              relief=tk.RIDGE)
        main_frame.grid(sticky=tk.NSEW)
        main_frame.columnconfigure(0, weight=1)
        '''
        Create a frame from name entry section of the main view
        '''
        # create a frame for name entry
        frame_entry = tk.Frame(main_frame)
        frame_entry.grid(row=3, column=0, sticky=tk.NW)

        # add canvas to this name entry frame
        canvas_entry = tk.Canvas(frame_entry,
                                 bg=Color.LIGHT_GREEN.description,
                                 borderwidth=0,
                                 highlightthickness=0,
                                 width=700)
        canvas_entry.grid(row=0, column=0)

        entry_frame = tk.Frame(canvas_entry,
                               bg=Color.LIGHT_GREEN.description,
                               bd=1)

        # Create a frame for question view
        question_view = tk.Frame(main_frame)
        question_view.grid(row=3, column=1, sticky=tk.NW)

        # Add canvas to the question view frame
        question_view_canvas = tk.Canvas(question_view,
                                         bg=Color.LIGHT_GREEN.description,
                                         borderwidth=0,
                                         highlightthickness=0,
                                         width=500)
        question_view_canvas.grid(row=0, column=0)

        question_frame = tk.Frame(question_view_canvas,
                                  bg=Color.LIGHT_GREEN.description,
                                  bd=1)

        # Get player names and store them in variables
        player1 = tk.StringVar()
        player2 = tk.StringVar()
        player3 = tk.StringVar()
        player4 = tk.StringVar()

        player1_name = tk.Entry(entry_frame, textvariable=player1, bd=5)
        player1_name.grid(row=1, column=1, columnspan=8, sticky='w')
        player2_name = tk.Entry(entry_frame, textvariable=player2, bd=5)
        player2_name.grid(row=2, column=1, columnspan=8, sticky='w')
        player3_name = tk.Entry(entry_frame, textvariable=player3, bd=5)
        player3_name.grid(row=3, column=1, columnspan=8, sticky='w')
        player4_name = tk.Entry(entry_frame, textvariable=player4, bd=5)
        player4_name.grid(row=4, column=1, columnspan=8, sticky='w')

        player_entries = [
            player1_name, player2_name, player3_name, player4_name
        ]

        # Initiate game start
        start_game = tk.Button(
            entry_frame,
            text="Start Game",
            font=helvetica_20,
            bg=Color.LIGHT_GREEN.description,
            fg=Color.BLACK.description,
            command=lambda: begin_game(player_entries, players, names, turn))
        start_game.grid(row=5, column=1, sticky='e')

        # instantiate question bank, players, turn and player objects
        question_files = [
            config('CATEGORY1_FILE'),
            config('CATEGORY2_FILE'),
            config('CATEGORY3_FILE'),
            config('CATEGORY4_FILE')
        ]
        question_bank = load_question_files(question_files)

        turn = Turn()

        p1 = Player('player1')
        p2 = Player('player2')
        p3 = Player('player3')
        p4 = Player('player4')

        names = {1: player1, 2: player2, 3: player3, 4: player4}

        players = {1: p1, 2: p2, 3: p3, 4: p4}

        create_entry_view(
            tk=tk,
            entry_frame=entry_frame,
        )

        canvas_entry.create_window((0, 0), window=entry_frame, anchor=tk.NW)
        entry_frame.update_idletasks()

        question_label = create_question_view(tk=tk,
                                              question_frame=question_frame,
                                              question_obj=Question(),
                                              players=players,
                                              turn=turn,
                                              button_text='')[0]

        question_button = create_question_view(tk=tk,
                                               question_frame=question_frame,
                                               question_obj=Question(),
                                               players=players,
                                               turn=turn,
                                               button_text='')[1]

        question_view_canvas.create_window((0, 0),
                                           window=question_frame,
                                           anchor=tk.NW)
        question_frame.update_idletasks()
        '''
        Create frame for the die roll section of the main view
        '''
        # create frame for die roll
        frame_die_roll = tk.Frame(main_frame)
        frame_die_roll.grid(row=10, column=1, sticky=tk.NW)  # used to be row=4

        # add canvas to this frame
        canvas_die_roll = tk.Canvas(frame_die_roll,
                                    bg=Color.LIGHT_GREEN.description,
                                    borderwidth=0,
                                    highlightthickness=0)
        canvas_die_roll.grid(row=0, column=0)

        die_roll_frame = tk.Frame(canvas_die_roll,
                                  bg=Color.LIGHT_GREEN.description,
                                  bd=1)

        create_die_roll(tk=tk, frame=die_roll_frame)

        canvas_die_roll.create_window((0, 0),
                                      window=die_roll_frame,
                                      anchor=tk.NW)
        die_roll_frame.update_idletasks()

        # create frame for board game and scroll bar
        frame_board_game = tk.Frame(main_frame)
        frame_board_game.grid(row=10, column=0, sticky=tk.NW)

        # add canvas to the frame
        canvas_board_game = tk.Canvas(frame_board_game,
                                      bg=Color.WHITE.description)
        canvas_board_game.grid(row=10, column=0)

        # create vertical scroll bar
        vertical_scroll = tk.Scrollbar(frame_board_game,
                                       orient=tk.VERTICAL,
                                       command=canvas_board_game.yview)
        vertical_scroll.grid(row=10, column=1, sticky=tk.NS)
        canvas_board_game.configure(yscrollcommand=vertical_scroll.set)

        # create horizontal scroll bar
        horizontal_scroll = tk.Scrollbar(frame_board_game,
                                         orient=tk.HORIZONTAL,
                                         command=canvas_board_game.xview)
        horizontal_scroll.grid(row=1, column=0, sticky=tk.EW)
        canvas_board_game.configure(xscrollcommand=horizontal_scroll.set)

        # create a frame for the board game
        buttons_frame = tk.Frame(canvas_board_game,
                                 bg=Color.LIGHT_BLUE.description,
                                 bd=1)

        create_game_board(tk_button=tk.Button,
                          board_frame=buttons_frame,
                          question_label=question_label,
                          font_type=helvetica_20,
                          start_row=0,
                          sq_dim=7,
                          names=names,
                          players=players,
                          turn=turn,
                          question_button=question_button,
                          question_bank=question_bank)

        for child in buttons_frame.winfo_children():
            child.configure(state='disable')

        canvas_board_game.create_window((0, 0),
                                        window=buttons_frame,
                                        anchor=tk.NW)

        buttons_frame.update_idletasks()
        bbox = canvas_board_game.bbox(tk.ALL)

        # define the scrollable region
        w, h = bbox[2] - bbox[1], bbox[3] - bbox[1]
        dw, dh = int((w / COLUMNS) * DISPLAY_COLUMNS), int(
            (h / ROWS) * DISPLAY_ROWS)
        canvas_board_game.configure(scrollregion=bbox, width=dw, height=dh)
    def insert(csv_file, question_rows, check_for_duplicates):
        """Insert new rows extracted from csv_file"""
        start = time.perf_counter()

        applications = Application.get_applications_from_csv(csv_file)

        csv_file.seek(0)
        Question.get_questions_from_csv(csv_file)
        question_types = Question.get_question_types_from_csv(csv_file)

        email_index = None
        submit_date_index = None

        for i in range(len(question_types)):
            try:
                question_type = QuestionType[question_types[i]]
                if question_type == QuestionType.email:
                    email_index = i
                elif question_type == QuestionType.submitDate:
                    submit_date_index = i
            except KeyError as e:
                print(e)

        if email_index is None or submit_date_index is None:
            raise ValueError("Submitted time and/or email not provided")

        # save last submitted application at each email
        date_format = "%Y-%m-%d %H:%M:%S"
        sorted_applications = sorted(
            applications,
            key=lambda application: datetime.strptime(
                application[submit_date_index], date_format))
        email_application_map = {
            application[email_index]: application
            for application in sorted_applications
        }
        filtered_applications = [
            application
            for (email, application) in email_application_map.items()
        ]

        applications_to_insert = []
        rows_to_delete = []

        if check_for_duplicates:
            for application in filtered_applications:
                duplicate = Answer.check_duplicate_email(
                    application[email_index])
                if duplicate:
                    new_time = datetime.strptime(
                        application[submit_date_index], date_format)
                    duplicate_time = db.session.query(Answer).filter(
                        Answer.application_id == duplicate.application_id
                    ).join(Question).filter(Question.question_type ==
                                            QuestionType.submitDate).first()
                    old_time = datetime.strptime(duplicate_time.answer,
                                                 date_format)

                    if old_time >= new_time:
                        continue

                    rows_to_delete.append(duplicate.application)
                applications_to_insert.append(application)
        else:
            applications_to_insert = filtered_applications

        rows_to_insert = Application.convert_applications_to_rows(
            applications_to_insert, datetime.now())

        processing_done_time = time.perf_counter()
        print("Applications processing time: ", processing_done_time - start)

        start = time.perf_counter()

        for row in rows_to_delete:
            db.session.delete(row)

        try:
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            raise e

        deleting_done_time = time.perf_counter()
        print('Number of application rows deleted: ', len(rows_to_delete))
        print('Applications delete time: ', deleting_done_time - start)

        start = time.perf_counter()

        db.session.bulk_save_objects(rows_to_insert, return_defaults=True)

        inserting_done_time = time.perf_counter()
        print('Number of application rows inserted: ', len(rows_to_insert))
        print('Applications insert time: ', inserting_done_time - start)

        Answer.insert(question_rows, applications_to_insert, rows_to_insert)