Example #1
0
def quiz_map_edit(quiz_id):
    current_app.logger.debug("quiz_edit. quiz_id - " + str(quiz_id))

    quizes = Quiz.get_quizes_by_user_id(current_user.id)

    for q in quizes:
        q.quiz_results = QuizResult.get_quiz_results_only_by_quiz_id(q.qid)

    quiz = Quiz.get_quiz_by_id(quiz_id)

    quiz_results = QuizResult.get_quiz_results_only_by_quiz_id(quiz_id)

    def serialize_for_left_menu(q):
        return {
            "quiz_results": [qr.serialize_for_statistics for qr in q.quiz_results],
            "quiz": q.serialize_for_result
        }

    jsdata = {
              "quiz_results": [i.serialize_for_statistics for i in quiz_results],
              "quizes": [serialize_for_left_menu(q) for q in quizes]
              }

    if quiz:
        if current_user.id == quiz.user_id:
            return render_template("quiz_map_edit.html", quiz=quiz, quizes=quizes, \
                                   active_page='quiz_edit', jsdata=jsdata, showTour=(not current_user.isTrained()))
        else:
            return render_template("auth_failure.html")
    else:
        current_app.logger.warning("No quiz found")        
        return render_template("404.html")
Example #2
0
 def __init__(self):
     
     #Create a window and give it a title.
     self.window = Tk()
     self.window.title('Simple Quiz')
     
     #Create an instance of the quiz class.
     self.quiz = Quiz()
     
     #Labels for the question to appear on the screen.
     self.question_text = Text(self.window, font="arial 16", width = 40, height = 4, wrap = WORD)
     self.question_text.insert(1.0, self.quiz.ask_current_question())
     self.question_text.pack()
     
     #Variable and entry for the user to put in his or her answer.
     self.answer = StringVar()
     self.answerEntry = Entry (self.window, textvariable = self.answer)
     self.answerEntry.pack(side = LEFT)
     
     #Bind the return key to enter the answer in the entry.
     self.answerEntry.focus_set()
     self.answerEntry.bind("<Return>", self.check_answer)
     
     #Label for the instructions for the quiz.
     self.instructions = StringVar()
     self.instructions.set('\u21D0 Enter your answer here')
     self.instrLabel = Label(self.window, textvariable = self.instructions)
     self.instrLabel.pack(side = LEFT)
     
     #Main loop to loop through the initialization method.
     self.window.mainloop()
Example #3
0
    def __init__(self):
        self.window = Tk()
        self.window.title('Simple Quiz')

        self.quiz = Quiz()
        #setting the text box
        self.question_text = Text(self.window,
                                  font="arial 16",
                                  width=40,
                                  height=4,
                                  wrap=WORD)
        self.question_text.insert(1.0, self.quiz.ask_current_question())
        self.question_text.pack()
        #making the text entry and binding the 'enter' button to it
        self.answer = StringVar()
        self.answerEntry = Entry(self.window, textvariable=self.answer)
        self.answerEntry.pack(side=LEFT)
        self.answerEntry.focus_set()
        self.answerEntry.bind("<Return>", self.check_answer)
        #label
        self.instructions = StringVar()
        self.instructions.set('\u21D0 Enter your answer here')
        self.instrLabel = Label(self.window, textvariable=self.instructions)
        self.instrLabel.pack(side=LEFT)

        self.window.mainloop()
Example #4
0
    def test_init(self):
        with self.assertRaises(AssertionError):
            Quiz(["Player1"])

        players = ["Player1", "Player2"]
        quiz = Quiz(players)
        self.assertEqual(quiz.players, players)
        self.assertEqual(quiz.current_round, 1)
Example #5
0
def update_player_score(quiz: Quiz, player: str, round_num: int) -> None:
    """Updates the leaderboard with the score for a given player and round_number."""
    s = input(f"Enter {player}'s score for round {round_num}: ")
    try:
        score = int(s)
        quiz.add_score(player, score)
    except ValueError:
        print(f"Error adding score '{s}' for {player}. Please try again")
        update_player_score(quiz, player, round_num)
Example #6
0
def main():
    print(
        "Would you like to have the pokemon's type displayed? (makes the game easier)"
    )
    show_types = validate_input()
    print(
        "Would you like to have to guess all correct answers? (makes the game harder)"
    )
    all_answers = validate_input()
    quiz = Quiz(show_types, all_answers)
    quiz.run()
Example #7
0
def jupdate(quiz_id):
    current_app.logger.debug("jupdate. quiz_id - " + str(quiz_id))
    
    quiz = Quiz.get_quiz_by_id(quiz_id)
    
    if quiz:
        if current_user.id == quiz.user_id:
            schema = {
                "type": "object",
                "properties": {
                    "title": {"type": "string", "minLength": 4, "maxLength": 55, "optional": False},
                    "is_private": {"type": "string", "minLength": 1, "maxLength": 1, "optional": False},
                    }
                }

            v = Draft4Validator(schema)
            errors = sorted(v.iter_errors(request.json), key = lambda e: e.path)
    
            if len(errors) > 0:
                msg = u"Error : "
                if len(request.json['title']) < 4 or len(request.json['title']) > 55:
                    msg = u"Title length should be greater than 3 and less than 55 symbols"
                else:
                    for e in errors:
                        msg = msg + e.message.decode("UTF-8")
                    
                result = {"status": "ERROR", "message": msg}
                current_app.logger.warning(result)
                return jsonify(result)
            else:
                title = request.json['title']
                is_private = request.json['is_private']
                if is_private == 'T':
                    Quiz.update_quiz_by_id(quiz_id, title, None, 'private')
                else:
                    Quiz.update_quiz_by_id(quiz_id, title, None, 'public')
                db.session.commit()
                
                current_app.logger.debug('Quiz updated. quiz.id - ' + str(quiz_id) + ', title - ' + title)
                return jsonify({"status" : "OK", "quizid": quiz_id})
        else:
            msg = auth_failure_message + u"update this quiz(id = " + str(quiz_id).decode("UTF-8")+")"
            current_app.logger.warning(msg)
            return jsonify({"status" : "ERROR", "message": msg})
    else:
        msg = u"No quiz found with such quiz_id" + str(quiz_id).decode("UTF-8")
        current_app.logger.warning(msg)
        return jsonify({"status": "ERROR", "message": msg})
Example #8
0
def quiz_list():
    current_app.logger.debug("quiz_list")

    quizes = Quiz.get_quizes_by_user_id(current_user.id)

    for q in quizes:
        q.quiz_results = QuizResult.get_quiz_results_only_by_quiz_id(q.qid)

    lat = 37.4419
    lon = -122.1419

    if len(quizes) > 0:
        lat = quizes[0].latitude
        lon = quizes[0].longitude

    def serialize_for_left_menu(q):
        return {
            "quiz_results": [qr.serialize_for_statistics for qr in q.quiz_results],
            "quiz": q.serialize_for_result
        }

    jsdata = {
              "latitude": lat,
              "longitude": lon,
              "quizes": [serialize_for_left_menu(q) for q in quizes]
              }

    return render_template("quiz_list.html", quizes=quizes, jsdata=jsdata, \
                           active_page="quiz_list", showTour=(not current_user.isTrained()))
Example #9
0
 def __init__(self):        
     self.user = User()
     self.course = Course()
     self.category = Category()
     self.quiz = Quiz()
     self.announcement = Announcement()
     self.discussion = Discussion()
Example #10
0
def quiz(quiz_id):
    current_app.logger.debug("quiz. quiz_id - " + str(quiz_id))
    
    quiz = Quiz.get_quiz_by_id(quiz_id)
    if quiz:            
        if current_user.id == quiz.user_id:
            jsdata = {
                      "questions": [i.serialize for i in quiz.questions],
                      "show_private_page": True
                      }
            if (len(quiz.questions) > 0):
                QuizResult.start_session(quiz_id, current_user.id)
                db.session.commit()
            return render_template('quiz.html', quiz=quiz, jsdata=jsdata)

        elif quiz.permission == 'public':
            jsdata = {
              "questions": [i.serialize_with_answers for i in quiz.questions],
              "show_private_page": False
            }
            return render_template('quiz_public.html', quiz=quiz, jsdata=jsdata)
        else:
            return render_template('auth_failure.html')            
    else:
        current_app.logger.warning("No quiz found")
        return render_template('404.html')
Example #11
0
    def select_dir(self):
        self.timer.stop()
        self.directory = str(QFileDialog.getExistingDirectory(self, "Select Directory"))
        self.widget_pubquiz_dir.setText(self.directory)

        self.pubquiz = Quiz.load_dir_with_ini(self.directory)
        self.refresh()
        self.timer.start(3000)
Example #12
0
def initQuizInfo(input_file, sectionDict):
  quizList = [{} for _ in range(len(sectionDict))]
  with open(input_file, newline = '', encoding = 'utf-8') as csvfile:
    rows = csv.reader(csvfile)
    for row in rows:
      idx = sectionDict[row[1]]
      quizList[idx][row[0]] = Quiz(quizId = row[0], sectionId = idx, difficulty = row[2])

  return quizList
Example #13
0
def ask():
    quiz = Quiz(
        initiator=ANONYMOUS_USER_ID,
        category_id=SPA_GAME_CATEGORY_ID,
        room_id=SPA_ROOM_ID,
        backend=BACKEND
    )
    img, answers, question_id, question = quiz.ask_image_type()

    try:
        image = Image(img, quiz.room_id, question_id, convert_svg=False)
        image = str(image).split('/')[-1]
        return jsonify(url=f'/media/{image}', question_id=question_id,
                       question=question)
    except (FileTypeError, NotFoundError) as e:
        return e.msg, e.code
    except AttributeError:
        return "Image not found", 404
Example #14
0
 def get_quiz_result_by_quiz_id_user_id(quiz_id, user_id):
     hs = Historysession.get_current_history_session_by_user_id_quiz_id(user_id)
     if hs:
         qr = QuizResult.query.filter_by(session_id=hs.hsid).first()
         if qr:
             qr.quiz = Quiz.get_quiz_only_by_id(qr.quiz_id)
         return qr
     else:
         return None
Example #15
0
def jcreate():
    current_app.logger.debug("jcreate")

    quiz = Quiz.create_quiz(current_user.id)
    db.session.commit()

    current_app.logger.debug('Quiz created. quiz.id - ' + str(quiz.qid))

    return jsonify({"status": "OK", "quizid": quiz.qid})
Example #16
0
def create():
    current_app.logger.debug("create")

    quiz = Quiz.create_quiz(current_user.id)
    db.session.commit()

    current_app.logger.debug('Quiz created. quiz.id - ' + str(quiz.qid))

    return redirect("/quiz/" + str(quiz.qid) + "/#edit")
Example #17
0
def check():
    data = request.json

    result = data.get('answer')
    question_id = data.get('questionId')
    if result:
        if result in Quiz.get_answers(question_id=question_id):
            return jsonify(result='OK')
        else:
            return jsonify(result='FAIL')
Example #18
0
 def __init__(self, window):
     ''' Create a quiz and GUI frontend for that quiz '''
     
     self.quiz = Quiz()
     
     self.question_text = Text(window, font="arial 16", width = 40, height = 4, wrap = WORD)
     self.question_text.insert(1.0, self.quiz.ask_current_question())
     self.question_text.pack()
     
     self.answer = StringVar()
     self.answerEntry = Entry (window, textvariable = self.answer)
     self.answerEntry.pack(side = LEFT)
     self.answerEntry.focus_set()
     self.answerEntry.bind("<Return>", self.check_answer)
     
     self.instructions = StringVar()
     self.instructions.set('\u21D0 Enter your answer here')
     self.instrLabel = Label(window, textvariable = self.instructions)
     self.instrLabel.pack(side = LEFT)
Example #19
0
 def test_remove_quizzes_not_from_multiple_choices(self):
     """
     Removing questions NOT in the list of multiple choices shouldn't 
     change multiple choice list.
     """
     self.mock_listener.expects(never()).question_changed()
     self.quiz = Quiz(self.QUIZ_POOL[:])
     old_multi_choices = self.quiz.multi_choices[:]
     old_question = self.quiz.question[:]
     quiz_list = self.QUIZ_POOL[:]
     for quiz in old_multi_choices:
         quiz_list.remove(quiz)
     for quiz in quiz_list:
         self.quiz.remove_quizzes([quiz])
         assert self.quiz.multi_choices == old_multi_choices, \
                 "Multiple choice options changed after removing other "\
                 "quizzes. " "New: %s; Old: %s; Removed: %s." % \
                 (self.quiz.multi_choices, old_multi_choices, quiz)
     self.mock_listener.verify()
Example #20
0
 def start_session(quiz_id, user_id):
     hs = Historysession.start_history_session(user_id)
     
     qr = QuizResult.query.filter_by(session_id=hs.hsid).first()
     if not qr:
         nquestion = Quiz.get_number_of_active_questions_by_id(quiz_id)
         
         qr = QuizResult(hs.hsid, quiz_id, nquestion, None)
         db.session.add(qr)
     qr.historysession = hs
     return qr
Example #21
0
def quizes():
    result = Quiz()
    print result
    print type(result)
    print len(result)

    if len(result) > 0:
        return render_template('quizes.html', quizes=result)
    else:
        msg = "No quizes found right now"
        return render_template('quizes.html', msg=msg)
Example #22
0
def main():
    init(autoreset=True)
    # file_path = os.path.join(os.getcwd(), 'src', 'day_17', 'data.txt')
    quiz_data = get_questions_data_from(
        "https://opentdb.com/api.php?amount=48&category=18")

    question_objects = get_questions_from(quiz_data)
    remove_unreadable_parts_from_list(question_objects)

    quiz = Quiz(question_objects)
    run_quiz(quiz)
Example #23
0
def setup(base, conf_fn):
    print '\n**** service initialization ****\n'
    global room, courseobj, categoryobj, userobj, announcementobj, discussionobj, quizobj, messageobj
    room = Room(base, conf_fn)
    courseobj = Course()
    categoryobj = Category()
    userobj = Users()
    announcementobj = Announcement()
    discussionobj = Discussion()
    quizobj = Quiz()
    messageobj = Message()
Example #24
0
def quiz(id):
    print colored(id, 'white', 'on_red')
    id = int(id)
    quizes = Quiz()
    for quiz in quizes:
        if (quiz.get('id') == id):
            result = quiz
            questions = result['question']
            break

        # return redirect(url_for('index'))
    return render_template('quiz.html', quiz=result, question=questions)
Example #25
0
class StartQuiz(web.RequestHandler):

    quizList = Quiz.get_quiz_list()
    quizId = None

    def data_received(self, chunk):
        pass

    def get(self):
        self.render("templates/start.html", quizes=self.quizList)

    def post(self):
        pass
Example #26
0
def jdelete(quiz_id):
    current_app.logger.debug("jdelete. quiz_id - " + str(quiz_id))
    
    quiz = Quiz.get_quiz_only_by_id(quiz_id)
    
    if quiz:
        if current_user.id == quiz.user_id:

            QuizResult.delete_quiz_results_by_quiz_id(quiz_id)
            Quiz.delete_quiz_by_id(quiz_id)

            db.session.commit()
            current_app.logger.debug("Quiz deleted")

            return jsonify({"status": "OK"})
        else:
            msg = auth_failure_message + u"delete this quiz(id = " + str(quiz_id).decode("UTF-8")+")"
            current_app.logger.warning(msg)
            return jsonify({"status": "ERROR", "message" : msg})
    else:
        msg = u"No quiz found with such quiz_id" + str(quiz_id).decode("UTF-8")
        current_app.logger.warning(msg)        
        return jsonify({"status": "ERROR", "message": msg})
Example #27
0
class Controller:
    
    #Constructor to create the window and its features.
    def __init__(self):
        
        #Create a window and give it a title.
        self.window = Tk()
        self.window.title('Simple Quiz')
        
        #Create an instance of the quiz class.
        self.quiz = Quiz()
        
        #Labels for the question to appear on the screen.
        self.question_text = Text(self.window, font="arial 16", width = 40, height = 4, wrap = WORD)
        self.question_text.insert(1.0, self.quiz.ask_current_question())
        self.question_text.pack()
        
        #Variable and entry for the user to put in his or her answer.
        self.answer = StringVar()
        self.answerEntry = Entry (self.window, textvariable = self.answer)
        self.answerEntry.pack(side = LEFT)
        
        #Bind the return key to enter the answer in the entry.
        self.answerEntry.focus_set()
        self.answerEntry.bind("<Return>", self.check_answer)
        
        #Label for the instructions for the quiz.
        self.instructions = StringVar()
        self.instructions.set('\u21D0 Enter your answer here')
        self.instrLabel = Label(self.window, textvariable = self.instructions)
        self.instrLabel.pack(side = LEFT)
        
        #Main loop to loop through the initialization method.
        self.window.mainloop()
    
    #Method that checks if the user was correct or incorrect.    
    def check_answer(self, event):
        if self.quiz.check_current_answer(self.answer.get()):
            #Got it right!!
            self.instructions.set("Good job!  Next question ...")
        else:
            self.instructions.set("Sorry, the answer was " + self.quiz.get_current_answer()) 
        self.answer.set('')
        
        #Go to the next question if it exists
        self.question_text.delete(1.0, END)  
        if (self.quiz.has_next()):
            self.quiz.next()
            self.question_text.insert(1.0, self.quiz.ask_current_question())
        else:  
            self.question_text.insert(1.0, 'Sorry, there are no more questions.')
            self.answerEntry.configure(state='disabled')
Example #28
0
class Admin(object):
    
    db = None
    
    '''
    classdocs
    '''
    #constructor
    def __init__(self):        
        self.user = User()
        self.course = Course()
        self.category = Category()
        self.quiz = Quiz()
        self.announcement = Announcement()
        self.discussion = Discussion()
              
    def resetDB(self):
        self.user.reset()
        self.course.reset()
        self.category.reset()
        self.quiz.reset()
        self.announcement.reset()
        self.discussion.reset()
        
Example #29
0
def run():
    flashcard_loader = FlashcardLoader()
    flashcard_loader.load_flashcards('data')
    quiz = Quiz()
    user_continuing = True
    while quiz.get_next_flashcard(True) or user_continuing:
        next_card = quiz.get_next_flashcard()
        correct_choice = raw_input()

        quiz.answer_question(next_card, correct_choice)
Example #30
0
def initialise_quiz() -> Quiz:
    """Retrieves quiz parameters from the user and returns a Quiz object based on those parameters."""
    try:
        num_players = int(input("Enter number of players: "))
        players = []
        for i in range(num_players):
            player_name = input(f"Enter player {i+1} name: ")
            players.append(player_name)

        num_rounds = int(input("Enter number of rounds: "))
        round_length = int(input("Enter number of questions in each round: "))
        quiz = Quiz(players, num_rounds, round_length)
    except Exception:
        print("Got an error trying to initialise the quiz. Please try again.")
        return initialise_quiz()
    else:
        return quiz
Example #31
0
class Controller:
    def __init__(self):
        self.window = Tk()
        self.window.title('Simple Quiz')

        self.quiz = Quiz()
        #setting the text box
        self.question_text = Text(self.window,
                                  font="arial 16",
                                  width=40,
                                  height=4,
                                  wrap=WORD)
        self.question_text.insert(1.0, self.quiz.ask_current_question())
        self.question_text.pack()
        #making the text entry and binding the 'enter' button to it
        self.answer = StringVar()
        self.answerEntry = Entry(self.window, textvariable=self.answer)
        self.answerEntry.pack(side=LEFT)
        self.answerEntry.focus_set()
        self.answerEntry.bind("<Return>", self.check_answer)
        #label
        self.instructions = StringVar()
        self.instructions.set('\u21D0 Enter your answer here')
        self.instrLabel = Label(self.window, textvariable=self.instructions)
        self.instrLabel.pack(side=LEFT)

        self.window.mainloop()

    def check_answer(self, event):
        if self.quiz.check_current_answer(self.answer.get()):
            #Got it right!!
            self.instructions.set("Good job!  Next question ...")
        else:
            self.instructions.set("Sorry, the answer was " +
                                  self.quiz.get_current_answer())
        self.answer.set('')

        #Go to the next question if it exists
        self.question_text.delete(1.0, END)
        if (self.quiz.has_next()):
            self.quiz.next()
            self.question_text.insert(1.0, self.quiz.ask_current_question())
        else:
            self.question_text.insert(
                1.0, 'Sorry, there are no more questions.'
            )  #when there are no more questions to be asked
            self.answerEntry.configure(state='disabled')
class Controller:
    ''' Drive an interactive quiz GUI '''
    def __init__(self, window):
        ''' Create a quiz and GUI frontend for that quiz '''

        self.quiz = Quiz()

        self.question_text = Text(window,
                                  font="arial 16",
                                  width=40,
                                  height=4,
                                  wrap=WORD)
        self.question_text.insert(1.0, self.quiz.ask_current_question())
        self.question_text.pack()

        self.answer = StringVar()
        self.answerEntry = Entry(window, textvariable=self.answer)
        self.answerEntry.pack(side=LEFT)
        self.answerEntry.focus_set()
        self.answerEntry.bind("<Return>", self.check_answer)

        self.instructions = StringVar()
        self.instructions.set('\u21D0 Enter your answer here')
        self.instrLabel = Label(window, textvariable=self.instructions)
        self.instrLabel.pack(side=LEFT)

    def check_answer(self, event):
        ''' Check if the user's current answer is correct '''

        if self.quiz.check_current_answer(self.answer.get()):
            #Got it right!!
            self.instructions.set("Good job!  Next question ...")
        else:
            self.instructions.set("Sorry, the answer was " +
                                  self.quiz.get_current_answer())
        self.answer.set('')

        #Go to the next question if it exists
        self.question_text.delete(1.0, END)
        if (self.quiz.has_next()):
            self.quiz.next()
            self.question_text.insert(1.0, self.quiz.ask_current_question())
        else:
            self.question_text.insert(1.0,
                                      'Sorry, there are no more questions.')
            self.answerEntry.configure(state='disabled')
Example #33
0
def jget(quiz_id):
    current_app.logger.debug("jget. quiz_id - " + str(quiz_id))
    
    quiz = Quiz.get_quiz_by_id(quiz_id)
    
    if quiz:
        if current_user.id == quiz.userid:
            result = {'status': 'OK'}
            result.update(quiz.serialize)
           
            return jsonify(result)
        else:
            msg = auth_failure_message + u"view this quiz(id = " + str(quiz_id).decode("UTF-8")+")"
            current_app.logger.warning(msg)
            return jsonify({"status": "ERROR", "message": msg})
    else:
        msg = u"No quiz found with such quiz_id" + str(quiz_id).decode("UTF-8")
        current_app.logger.warning(msg)
        return jsonify({"status" : "ERROR", "message": msg})
 def test_remove_quizzes_not_from_multiple_choices(self):
     """
     Removing questions NOT in the list of multiple choices shouldn't 
     change multiple choice list.
     """
     self.mock_listener.expects(never()).question_changed()
     self.quiz = Quiz(self.QUIZ_POOL[:])
     old_multi_choices = self.quiz.multi_choices[:]
     old_question = self.quiz.question[:]
     quiz_list = self.QUIZ_POOL[:]
     for quiz in old_multi_choices:
         quiz_list.remove(quiz)
     for quiz in quiz_list:
         self.quiz.remove_quizzes([quiz])
         assert self.quiz.multi_choices == old_multi_choices, (
             "Multiple choice options changed after removing other "
             "quizzes. "
             "New: %s; Old: %s; Removed: %s." % (self.quiz.multi_choices, old_multi_choices, quiz)
         )
     self.mock_listener.verify()
Example #35
0
 def get_quiz_result_by_id(session_id):
     quiz_result = QuizResult.query.filter_by(session_id=session_id).first()
     if quiz_result:
         quiz_result.quiz = Quiz.get_quiz_only_by_id(quiz_result.quiz_id)
         quiz_result.question_results = QuestionResult.get_question_results_by_id(session_id)
     return quiz_result
Example #36
0
File: exam.py Project: xluthi/ortho
            self.exam.answers.append(answer)
        print "Fin de l'examen."
    
    
    def get_score(self):
        """
        Correct the exam and print the score.
        """
        self.exam.correct()
        print u"Ton score est de %d sur %d" % (self.exam.score, self.quiz.length)
        if self.exam.score != self.quiz.length:
            print u"Tu t'es trompé sur les mots suivants:"
            for index in self.exam.mistakes:
                answer = self.exam.answers[index]
                word = self.quiz.words[index].word
                print "%25s --> %s" % (word, answer)
        else:
            print u"Magnifique %s!" % self.exam.student
            
            
if __name__ == "__main__":
    import os
    from lesson import Lesson
    quiz = Quiz("test", 15)
    lesson = Lesson('mots17', os.path.normpath(os.getcwdu()+'/../mots17'))
    quiz.add_lesson(lesson)
    quiz.generate()
    exam_runner = ExamRunner(u"Eléa", quiz)
    exam_runner.do_exam()
    exam_runner.get_score()
class Test_Quiz(unittest.TestCase):
    """
    Unittest for the class Quiz.
    """

    CLASS_TO_TEST = Quiz
    QUIZ_POOL = [[str(i), str(i * 10)] for i in range(10)]

    def setUp(self):
        self.quiz = self.CLASS_TO_TEST(self.QUIZ_POOL[:])
        self.mock_listener = Mock()
        self.quiz.connect("break_time", self.mock_listener.break_time)
        self.quiz.connect("question_changed", self.mock_listener.question_changed)

    ## Test add_quizzes and remove_quizzes ##

    def test_add_and_remove_quizzes(self):
        """
        Check that adding and removing quizzes come back to status quo.
        """
        old_quiz_pool = self.quiz.quiz_pool[:]
        new_quizzes = [[i, i * 100] for i in range(10, 20)]
        self.quiz.add_quizzes(new_quizzes)
        self.quiz.remove_quizzes(new_quizzes)
        assert old_quiz_pool == self.quiz.quiz_pool, (
            "quiz_pool changed after adding then removing "
            "%s from %s to %s" % (new_quizzes, old_quiz_pool, self.quiz.quiz_pool)
        )

    def test_remove_and_add_quizzes(self):
        """
        Removing all questions and then adding them again.
        """
        old_quiz_pool = self.quiz.quiz_pool[:]
        # Removing all questions #
        self.mock_listener.expects(once()).question_changed()
        self.quiz.remove_quizzes(self.quiz.quiz_pool[:])
        self.mock_listener.verify()
        assert self.quiz.quiz_pool == [], "quiz_pool still has %s after removing all quizzes" % self.quiz.quiz_pool
        assert self.quiz.question == ["", ""], "Non-empty question left though empty quiz_pool."
        # Adding original quizzes back. #
        self.mock_listener.expects(once()).question_changed()
        self.quiz.add_quizzes(old_quiz_pool[:])
        self.mock_listener.verify()
        assert self.quiz.quiz_pool == old_quiz_pool, "Adding %s to an empty quiz_pool leads to %s." % (
            old_quiz_pool,
            self.quiz.quiz_pool,
        )

    def test_remove_quizzes_from_multiple_choices(self):
        """
        Removing questions in the list of multiple choices.
        """
        self.mock_listener.expects(once()).question_changed()
        self.quiz.remove_quizzes([self.quiz.multi_choices[0]])
        self.mock_listener.verify()
        self.mock_listener.expects(once()).question_changed()
        self.quiz.remove_quizzes([self.quiz.multi_choices[-1]])
        self.mock_listener.verify()
        self.mock_listener.expects(once()).question_changed()
        self.quiz.remove_quizzes([self.quiz.question])
        self.mock_listener.verify()
        assert self.quiz.question in self.quiz.quiz_pool, "Question not in quiz_pool."

    def test_remove_quizzes_not_from_multiple_choices(self):
        """
        Removing questions NOT in the list of multiple choices shouldn't 
        change multiple choice list.
        """
        self.mock_listener.expects(never()).question_changed()
        self.quiz = Quiz(self.QUIZ_POOL[:])
        old_multi_choices = self.quiz.multi_choices[:]
        old_question = self.quiz.question[:]
        quiz_list = self.QUIZ_POOL[:]
        for quiz in old_multi_choices:
            quiz_list.remove(quiz)
        for quiz in quiz_list:
            self.quiz.remove_quizzes([quiz])
            assert self.quiz.multi_choices == old_multi_choices, (
                "Multiple choice options changed after removing other "
                "quizzes. "
                "New: %s; Old: %s; Removed: %s." % (self.quiz.multi_choices, old_multi_choices, quiz)
            )
        self.mock_listener.verify()

    ## Single Method Tests ##

    hint_place_holder = "-"

    def test_first_hint_should_be_blank(self):
        """
        Test that hint() starts with letters replaced by the place_holder.
        """
        solution = self.quiz.question[self.quiz.answer_to]
        first_hint = self.quiz.hint()
        assert first_hint == re.sub("\w", self.hint_place_holder, solution)

    def test_hint_adds_two_lettres_each_time(self):
        """
        Test that hint starts with letters replaced by underscores and gives 
        two letters each next hint.
        """
        solution = self.quiz.question[self.quiz.answer_to]
        first_hint = self.quiz.hint()
        next_hint = first_hint
        for hint_num in range((first_hint.count(self.hint_place_holder) + 1) // 2):
            assert next_hint.count(self.hint_place_holder) + hint_num * 2 == first_hint.count(self.hint_place_holder), (
                "Hint no. %s gives %s letters, but %s should have been " + "given."
            ) % (
                hint_num,
                first_hint.count(self.hint_place_holder) - next_hint.count(self.hint_place_holder),
                hint_num * 2,
            )
            next_hint = self.quiz.hint(next_hint)
        assert next_hint == solution, 'Final hint ("%s") is not the solution ("%s").' % (next_hint, solution)

    def test_hint_with_double_lettres(self):
        """
        Run previous test (test_hint_adds_two_lettres_each_time) with '0000'
        as double letters make comparison of solution and hint non-trivial.
        """
        test_question = ["0000", "0000"]
        self.quiz.add_quizzes([test_question])
        self.quiz.question = test_question
        self.test_hint_adds_two_lettres_each_time()

    def test_invalid_previous_hint(self):
        """
        Test that a string which wasn't a hint still gives a valid hint.
        """
        solution = self.quiz.question[self.quiz.answer_to]
        for first_hint in [self.quiz.hint("a completely wrong answer"), self.quiz.hint("!" + solution[1:])]:
            for hint_letter, solution_letter in zip(first_hint, solution):
                assert (
                    hint_letter == self.hint_place_holder or hint_letter == solution_letter
                ), 'Hint ("%s") does not match solution ("%s").' % (first_hint, solution)

    def test_hint_increments_tries(self):
        """
        Test that a hint counts as a try.
        """
        assert self.quiz.tries == 0
        self.quiz.hint()
        assert self.quiz.tries == 1
        self.quiz.hint()
        assert self.quiz.tries == 2

    def test_hint_does_not_change_correct_answer(self):
        assert self.quiz.hint(self.quiz.question[self.quiz.answer_to]) == self.quiz.question[self.quiz.answer_to]

    def test_check(self):
        self.mock_listener.expects(once()).question_changed()
        assert self.quiz.check(self.quiz.question[self.quiz.answer_to])
        self.mock_listener.verify()
        self.mock_listener.expects(once()).question_changed()
        assert not self.quiz.check("a wrong answer")
        assert self.quiz.check(self.quiz.question[self.quiz.answer_to])
        self.mock_listener.verify()

    def test__gen_multi_choices(self):
        multi_choices = self.quiz._gen_multi_choices()
        assert self.quiz.question in multi_choices, "Question %s not in multiple choice options %s." % (
            self.quiz.question,
            multi_choices,
        )

    def test__gen_multi_choices_has_no_answers_double(self):
        """Test that no answers are double in multi_choices."""
        multi_choices = self.quiz._gen_multi_choices()
        for i, choice in enumerate(multi_choices):
            assert not choice in multi_choices[i + 1 :], '"%s" is double in multi_choices ("%s").' % (
                choice,
                multi_choices,
            )

    def test__refit_multichoice_len(self):
        """
        Test length of multi_choices
        """
        self.mock_listener.expects(at_least_once()).question_changed()
        assert len(self.quiz.multi_choices) == self.quiz.DEFAULT_MULTICHOICE_LEN
        self.quiz.remove_quizzes(self.quiz.quiz_pool[self.quiz.DEFAULT_MULTICHOICE_LEN :])
        assert len(self.quiz.multi_choices) == self.quiz.DEFAULT_MULTICHOICE_LEN, (
            "self.quiz.multi_choices has wrong length: %s instead of %s."
            % (len(self.quiz.multi_choices), self.quiz.DEFAULT_MULTICHOICE_LEN)
        )
        self.quiz.remove_quizzes(self.quiz.quiz_pool[3 : self.quiz.DEFAULT_MULTICHOICE_LEN])
        assert len(self.quiz.multi_choices) == 3, "self.quiz.multi_choices has wrong length: %s instead of 3." % len(
            self.quiz.multi_choices
        )
        self.quiz.remove_quizzes(self.quiz.quiz_pool[:3])
        assert len(self.quiz.multi_choices) == 1
        self.mock_listener.verify()

    def test_get_answer_to_question(self):
        answer_to = self.quiz.answer_to
        ask_from = self.quiz.ask_from

        for question_pair in self.QUIZ_POOL:
            assert question_pair[answer_to] == self.quiz.get_answer_to_question(
                question_pair[ask_from]
            ), "%s should be answer to question %s." % (question_pair[answer_to], question_pair[ask_from])
        assert (
            self.quiz.get_answer_to_question("asdfasdf") == None
        ), "Non-existant question 'asdfasdf' should return 'None'."

    def test_get_question_to_answer_from_multichoices(self):
        answer_to = self.quiz.answer_to
        ask_from = self.quiz.ask_from

        for question_pair in self.quiz.multi_choices:
            assert question_pair[ask_from] == self.quiz.get_question_to_answer_from_multichoices(
                question_pair[answer_to]
            ), "%s should be question to answer %s." % (question_pair[ask_from], question_pair[answer_to])
        assert (
            self.quiz.get_question_to_answer_from_multichoices("asdfasdf") == None
        ), "Non-existant answer 'asdfasdf' should return 'None'."

    def test_get_question_to_answer(self):
        answer_to = self.quiz.answer_to
        ask_from = self.quiz.ask_from

        for question_pair in self.quiz.multi_choices:
            assert question_pair[ask_from] == self.quiz.get_question_to_answer(
                question_pair[answer_to]
            ), "%s should be question to answer %s." % (question_pair[ask_from], question_pair[answer_to])
        assert (
            self.quiz.get_question_to_answer("asdfasdf") == None
        ), "Non-existant answer 'asdfasdf' should return 'None'."

    def test_notify(self):
        """
        Tests that new_question and next notify properly.
        """
        # test_new_question #
        for i in range(self.quiz.session_length * 2):
            self.mock_listener.expects(once()).question_changed()
            self.quiz.new_question()
            self.mock_listener.verify()
        # test_next #
        for i in range(self.quiz.session_length - 1):
            self.mock_listener.expects(once()).question_changed()
            self.quiz.next()
            self.mock_listener.verify()
        self.mock_listener.expects(once()).question_changed()
        self.mock_listener.expects(once()).break_time()
        self.quiz.next()
        self.mock_listener.verify()

    def test_set_question_direction(self):
        self.quiz.set_question_direction(0)
        assert self.quiz.ask_from == 0 and self.quiz.answer_to == 1
        self.quiz.set_question_direction(0)
        assert self.quiz.ask_from == 0 and self.quiz.answer_to == 1
        self.quiz.set_question_direction(1)
        assert self.quiz.ask_from == 1 and self.quiz.answer_to == 0
Example #38
0
def run_quiz(quiz: Quiz):
    clear_console()
    print(quiz)

    while True:
        question_object = quiz.get_user_a_question()
        correct_answer = question_object.correct_answer
        # question = question_object.question
        incorrect_answers = question_object.incorrect_answers
        quiz.display_list_of_possible_answers(incorrect_answers,
                                              correct_answer)
        user_answer = quiz.ask_user_an_answer("Answer: ")
        result = quiz.get_result_from_user_answer(user_answer, correct_answer)

        string_false_answer = f"{Fore.RED}False!\n{Fore.WHITE}The correct answer is:{Fore.GREEN} {correct_answer}\n"
        string_correct_answer = f"{Fore.GREEN}Correct!\n"

        if result:
            clear_console()
            print("*" * 55)
            print(string_correct_answer)
            quiz.player_score += 1

        else:
            clear_console()
            print(string_false_answer)
            quiz.player_lives -= 1
            print("*" * 55)

        if quiz.check_user_has_done_every_question():
            clear_console()
            print(
                f"{Fore.BLUE} Congratulations! You finished the whole Quiz without losing!!"
            )
            quiz.print_player_score()
            break

        if not quiz.player_lives:
            quiz.print_player_score()
            print(
                f"{Fore.RED}No more lives left...{Fore.RESET} Do you want to try again? (y/n)"
            )
            play_again()
        quiz.print_player_score()
Example #39
0
from quiz import Quiz

questions_prompt = [
    "What color are apples?\n(a) Red/Green\n(b) Purple\n(c) Orange\n\n",
    "What color are Bananas?\n(a) Teal\n(b) Magenta\n(c) Yellow\n\n",
    "What color are strawberries?\n(a) Yellow\n(b) Red\n(c) blue\n\n"
]

questions = [
    Quiz(questions_prompt[0], "a"),
    Quiz(questions_prompt[1], "c"),
    Quiz(questions_prompt[2], "b"),
]


def run_test(questions):
    score = 0
    for question in questions:
        answer = input(question.prompt)
        if answer == question.answer:
            score += 1
    print("You got " + str(score) + "/" + str(len(questions)) + "correct")


run_test(questions)
Example #40
0
from question import Question
from quiz import Quiz

if __name__ == '__main__':
    q1 = Question('En iyi programlama dili?',['C#','Python','Java','Javascript'],'Python')
    q2 = Question('En sevilen programlama dil?',['C#','Python','Java','Javascript'],'Java')
    q3 = Question('En kolay programlama dil?',['C#','Python','Java','Javascript'],'C#')

    questions = [q1,q2,q3]

    quiz = Quiz(questions)
    quiz.load_question()
Example #41
0
def play_quiz():
    play = True
    while play:
        question_count, max_number = get_quiz_preference()
        new_quiz = Quiz(0, 0)

        if (not question_count) and (not max_number):
            new_quiz = Quiz()
        elif question_count and max_number:
            new_quiz = Quiz(question_count=question_count, max_num=max_number)
        else:
            new_quiz = Quiz(
                question_count=question_count) if question_count else Quiz(
                    max_num=max_number)

        new_quiz.take_quiz()

        if input("Play again? <Enter> to play again, QUIT to exit: ").upper(
        ) == "QUIT":
            print("Bye now!")
            play = False
        else:
            clear_screen()
Example #42
0
def ask_quiz(name):
    result = Quiz.fromDict(quizes.find_one({'name': name})).questions()

    return app.response_class(response=json.dumps(result, default=toJSON),
                              status=200,
                              mimetype='application/json')
Example #43
0
from quiz import Quiz
from database import Question as DBQ

if __name__ == '__main__':
    quiz = Quiz()

    for q in quiz.get_all_quiz():
        qdb = DBQ.get_or_none(DBQ.json_file == q.short_filepath)

        if qdb is None:
            quiz.publish(q)
        else:
            if q.checksum != qdb.last_checksum:
                # Удаляем сообщения из канала
                quiz.delete_messages(qdb.message_id)
                # Удаляем запись из БД
                qdb.delete_instance()
                quiz.publish(q)
Example #44
0
def new_quiz():
    quiz = Quiz.fromDict(request.get_json())
    quizes.insert_one(json.loads(json.dumps(quiz, default=toJSON)))

    return app.response_class(status=201,
                              headers=[('location', '/quiz/' + quiz.name)])
Example #45
0
    master_gui = tk.Tk()

    master_gui.title("VQM")
    master_gui.geometry("800x600")

    gui = OperatorGUI(master_gui, show)
    gui.pack()

    master_gui.mainloop()


print("--Volani Quiz Master: Main Menu--")
quizzes = []
quizzes.append(
    Quiz("Test Quiz", [
        Question("Test Question, B is Correct?",
                 ["Incorrect", "Correct", "Inccorect"], 2, 10)
    ], r"^[1-3]$"))
while True:

    choice = present_menu_get_response(["Create Quiz", "Run Show"])

    if choice == 1:
        print("Enter quiz title: ")
        title = input()
        print("Enter answer regex: ")
        answer_regex = input()

        input_valid = False

        questions = []
Example #46
0
class UserLogged(User):
    def __init__(self, user: User, dbID, username):
        super().__init__(user.socket, user.address)
        self.uuid = user.uuid
        self.dbID = dbID
        self.username = username
        self.quiz = None

    def __repr__(self):
        return str(self.address) + ' ' + str(self.uuid) + ' ' + self.username

    def handle(self):
        r = self.socket.recv(3)
        if r != b'':
            headerType, size = HeaderParser.decode(r)
            data = Protocol.decode(self.socket.recv(size))
            h, p = None, None

            if headerType == Header.DIS:
                raise socket.error('Disconnect')
            elif headerType == Header.ALI:
                r = requests.get(URL.local + 'quizzes-categories')

                if r.status_code == 200:
                    j = r.json()
                    l = []
                    for x in j:
                        l.append(x['category_name'])
                    h, p = Protocol.encode(Header.LIS, quizes=l)
                    Logger.log('Category request')
                else:
                    h, p = Protocol.encode(Header.ERR,
                                           msg='Cant get categories')
                    Logger.log('Category request failed')
            elif headerType == Header.STR:
                if data['category'] == []:
                    r = requests.get(URL.local + 'quizzes-categories')
                    r2 = requests.get(URL.local + 'stats',
                                      params={'userid': self.dbID})

                    if r.status_code == 200 and r2.status_code == 200:
                        cat = r.json()
                        stat = r2.json()

                        ret = []
                        for x in stat:
                            for y in cat:
                                if x['quizid'] == y['id']:
                                    print('abc')
                                    ret.append({
                                        'category': y['category_name'],
                                        'score': x['score']
                                    })
                                    break

                        if ret != []:
                            h, p = Protocol.encode(Header.STA, stats=ret)
                        else:
                            h, p = Protocol.encode(Header.ERR, msg='empty')
                        Logger.log('Stats request ' + str(self.dbID))
                    else:
                        Logger.log('Stats request failed' + str(self.dbID))
                else:
                    r = requests.get(URL.local + 'top-stats',
                                     params={'category': data['category']})

                    if r.status_code == 200:
                        stat = r.json()

                        if stat != []:
                            h, p = Protocol.encode(Header.STA, stats=stat)
                        else:
                            h, p = Protocol.encode(Header.ERR, msg='empty')
                        Logger.log('Stats request ' + str(self.dbID))
                    else:
                        Logger.log('Stats request failed' + str(self.dbID))

            elif headerType == Header.QUI:
                r = requests.get(URL.local + 'quizzes',
                                 params={'category_name': data['category']})

                if r.status_code == 200 and self.quiz == None:
                    j = r.json()
                    qq = []
                    for x in j:
                        q = x['Question']['question']
                        cor = None
                        a = x['Answers']
                        for y in a:
                            if y['id'] == x['Question']['correct_answer']:
                                cor = y['answer']

                        b = []
                        for i in range(4):
                            b.append(str(a[i]['answer']))
                        qq.append(Question(q, b, str(cor)))

                    self.quiz = Quiz(qq, j[0]['Question']['quizid'])
                    question = self.quiz.next()
                    h, p = Protocol.encode(Header.QUE,
                                           question=question.question,
                                           answers=question.answers,
                                           correct=question.correct)
                    Logger.log('Quiz begin' + str(self.dbID))
                else:
                    h, p = Protocol.encode(Header.ERR, msg='Cant begin quiz')
                    Logger.log('Quiz request fail ' + str(self.dbID))
            elif headerType == Header.NXT:
                if self.quiz != None:
                    question = self.quiz.next()
                    h, p = Protocol.encode(Header.QUE,
                                           question=question.question,
                                           answers=question.answers,
                                           correct=question.correct)
                    Logger.log('next question ' + str(self.dbID))
                else:
                    h, p = Protocol.encode(Header.ERR, msg='Invalid request')
                    Logger.log('next question fail ' + str(self.dbID))
            elif headerType == Header.END:
                if self.quiz != None:
                    r = requests.patch(URL.local + 'stats',
                                       json={
                                           'userid': self.dbID,
                                           'quizid': self.quiz.quizid,
                                           'score': data['score']
                                       })

                    self.quiz = None

                    h, p = Protocol.encode(Header.ACK, msg='Quiz completed')
                    Logger.log('Quiz end ' + str(self.dbID))
                else:
                    h, p = Protocol.encode(Header.ERR,
                                           msg='Invalid end request')
                    Logger.log('Quiz end request fail ' + str(self.dbID))
            if h != None and p != None:
                self.transfer(h, p)

        return None