Beispiel #1
0
def load_sentences():
    """Load the content of data.yml into the English / Latin tables"""
    yaml = open('data/quiz_data.yml')
    data = ruamel.yaml.load(yaml, ruamel.yaml.RoundTripLoader)
    print data

    for topic_name, quiz in data.items():
        topic = (Topic.query.filter_by(name=topic_name).first()
                 or Topic(name=topic_name))
        print topic
        topic.save()

        for quiz_name, sentences in quiz.items():
            quiz = Quiz(name=quiz_name, topic=topic)
            print quiz
            quiz.save()

            for question, answers in sentences.items():
                type = answers.pop(0)['type']

                q = Sentence(type=type, text=question, quiz=quiz)

                for answer in answers:
                    a = Sentence(text=answer, )
                    q.translations.append(a)
                    a.translations.append(q)

                db.session.add(q)
                db.session.commit()
Beispiel #2
0
def post_new_quiz():
    form = NewQuizForm()
    form['csrf_token'].data = request.cookies['csrf_token']
    if form.validate_on_submit():
        questions = request.json["added_questions"]
        quiz = Quiz(name=form.data['name'],
                    is_private=form.data['is_private'],
                    question_quantity=len(questions),
                    user_id=current_user.id,
                    category_id=form.data["category_id"])
        db.session.add(quiz)
        db.session.flush()
        for i in range(len(questions)):
            new_question = Question(
                question_number=i + 1,
                body=questions[i]["question_body"],
                answer_1=questions[i]["answer_1"],
                answer_2=questions[i]["answer_2"],
                answer_3=questions[i]["answer_3"],
                correct_answer=questions[i]["correct_answer"],
                quiz_id=quiz.id)
            db.session.add(new_question)
        db.session.commit()
        return quiz.to_dict()
    return {'errors': validation_errors_to_error_messages(form.errors)}
 def test_user_posted_quiz(self):
     u = User(username="******", email='*****@*****.**', id=1)
     quiz = Quiz(category="Animals", filename="otters.json", user_id=u.id)
     db.session.add(quiz)
     db.session.commit()
     q = quiz.query.filter_by(filename="otters.json").first().postedby.id
     self.assertEqual(q, u.id)
def check_quiz(id):
    ordering = json.loads(flask.request.form['ord'])
    quiz = copy.deepcopy(quizzes[id])
    # print (flask.request.form)
    quiz['questions'] = sorted(quiz['questions'], key=lambda q: ordering.index(quiz['questions'].index(q)))
    # print (quiz['questions'])
    answers = dict( (int(k), quiz['questions'][int(k)]['options'][int(v)]) for k, v in flask.request.form.items() if k != 'ord' )

    # print (answers)

    if not len(answers.keys()):
        flash(f'Please answer all questions','danger')
        return redirect(url_for('quiz', id=id))

    for k in range(len(ordering)):
        if k not in answers:
            answers[k] = [None, False]

    answers_list = [ answers[k] for k in sorted(answers.keys()) ]
    number_correct = len(list(filter(lambda t: t[1], answers_list)))
    quiz = Quiz(score = number_correct, user=current_user)
    db.session.add(quiz)
    db.session.commit()
    flash(f'Answers submitted successfully','success')
    return redirect(url_for("home"))
Beispiel #5
0
    def test_for_building_database1(self):
        option1 = Option(option_body='World of Warcraft')
        option2 = Option(option_body='Team Fortress 2')
        option3 = Option(option_body='Steam')
        option4 = Option(option_body='Dota 2')
        question1 = Question(question_body='which one is a moba game?')
        option1.question = question1
        option2.question = question1
        option4.correct = True
        option4.question = question1
        option3.question = question1
        user1 = User(username='******', email='*****@*****.**')
        quiz1 = Quiz(usersesh=user1)

        db.session.add(quiz1)
        db.session.add(question1)
        db.session.commit()

        for question in db.session.query(Question).all():
            for option in question.options:
                print("test_for_building_database1 option: " +
                      option.option_body)

        print(
            "test_for_building_database1 quiz to user relationship (expected answer 1) user_id is: "
            + str(db.session.query(User).first().quiz[0].user_id))
Beispiel #6
0
def create_new():
    data = request.json
    previousQuiz = Quiz.query.filter(Quiz.name == data["quizName"]).first()
    if previousQuiz:
        return {"error": "A Quiz with that name already exists"}
    newQuiz = Quiz(userId=data["userId"], category=data["category"], name=data["quizName"])
    db.session.add(newQuiz)
    db.session.commit()
    quizId = Quiz.query.filter(Quiz.name == data["quizName"]).order_by(Quiz.id.desc()).first().id
    for i in range(len(data["questions"])):
        newQuestion = Question(quizId=quizId, questionType="mc", content=data["questions"][i])
        db.session.add(newQuestion)
        db.session.commit()
        questionId = Question.query.filter(Question.content == data["questions"][i]).order_by(Question.id.desc()).first().id
        allAnswerChoices = data["answerChoices"][i]
        for j in range(len(allAnswerChoices)):
            newAnswerChoice = AnswerChoice(content=allAnswerChoices[j], order=j, questionId=questionId)
            db.session.add(newAnswerChoice)
            db.session.commit()
            if(int(data["answers"][i]) == j):
                answerId = AnswerChoice.query.filter(AnswerChoice.content ==
                             allAnswerChoices[j]).order_by(AnswerChoice.id.desc()).first().id
                answer = AnswerJoin(questionId=questionId, answerChoiceId=answerId)
                db.session.add(answer)
                db.session.commit()
    return {"success": True}
Beispiel #7
0
def createQuiz():
    if current_user.is_admin == True:
        form = QuizCreation()
        if request.method == 'GET':
            return render_template('createQuizNew.html', title='Create Quiz', form=form)
        if form.validate_on_submit():
            quiz = Quiz(quiz_name=form.quiz_name.data, quiz_details=form.quiz_details.data, date_posted=datetime.now())
            db.session.add(quiz)
            db.session.commit()
            quiz = Quiz.query.filter_by(quiz_name = form.quiz_name.data).first()
            for question in form.question.data:
                new_question = Question(question=question["quizQuestion"], quiz=quiz.id)
                db.session.add(new_question)
                db.session.commit()
                id_question = Question.query.filter_by(question=question["quizQuestion"]).first()
                answers1 = Answer(answer=question["quizAnswer"], correct=True, questions=id_question.id, quiz=quiz.id)
                option1 = Answer(answer=question["option1"], correct=False, questions=id_question.id, quiz=quiz.id)
                option2 = Answer(answer=question["option2"], correct=False, questions=id_question.id, quiz=quiz.id)
                option3 = Answer(answer=question["option3"], correct=False, questions=id_question.id, quiz=quiz.id)
                db.session.add(answers1)
                db.session.add(option1)
                db.session.add(option2)
                db.session.add(option3)
                db.session.commit()
            return redirect(url_for('quizSelector'))
    else:
        return redirect(url_for('index'))
def create_quiz():
    if 'user' in session and (user := session['user']):
        form = f.QuizForm(request.form)
        if request.method == 'POST' and form.validate():
            user = User.query.filter_by(email=user.email).first()
            quiz = Quiz(user=user,
                        limited_time=int(form.limited_time.data),
                        title=form.title.data,
                        access_code=form.access_code.data,
                        visibility=form.visibility.data,
                        questions=[
                            Question(correct_answer=i['correct_answer'],
                                     content=i['content'],
                                     choices=[
                                         Choice(content=c["content"])
                                         for c in i['choices']
                                     ]) for i in form.questions.data
                        ])
            user.created_quizzes.append(quiz)
            db.session.add(user)
            db.session.commit()
            return redirect(url_for('main.user_profile'))
        session['quiz'] = {
            "title": "",
            "access_code": "",
            "limited_time": "",
            "visibility": "Public",
            "questions": [],
        }
        form = f.QuizForm(data=session["quiz"])
        return render_template('create_quiz.html',
                               form=form,
                               get_index=get_index,
                               get_index_int=get_index_int)
Beispiel #9
0
def add_quiz(user, name):
    '''Adds educator created quiz'''
    if Quiz.query.filter_by(userID=user.id, name=name).first():
        return
    quiz = Quiz(userID=user.id, name=name)
    db.session.add(quiz)
    db.session.commit()
    return quiz
def index(page):
    try:
        db.drop_all()
        db.create_all()
        # create quiz maker
        quiz_maker = User(name='Hassan',
                          email='*****@*****.**',
                          password='******')
        # create quiz with single-choice questions
        quiz = Quiz(title="Quiz 1", limited_time=12, posted_at=datetime.now())
        # create and add question for the quiz
        question = Question(content="1+1=?",
                            correct_answer=2,
                            choices=[
                                Choice(content="1"),
                                Choice(content="2"),
                                Choice(content="3"),
                                Choice(content="4"),
                            ])
        quiz.questions.append(question)
        quiz.questions.append(
            Question(content="1+2=?",
                     correct_answer=3,
                     choices=[
                         Choice(content="1"),
                         Choice(content="2"),
                         Choice(content="3"),
                         Choice(content="4"),
                     ]))
        # add created quiz to quiz maker's created quizzes list
        quiz_maker.created_quizzes.append(quiz)

        # create quiz taker
        quiz_taker = User(name='guest', email='[email protected]', password='******')
        # quiz taker take a quiz, create user quiz result
        quiz_result = QuizResult(quiz=quiz)
        # add quiz result to the taker
        quiz_taker.quizzes_results.append(quiz_result)
        # set quiz taker's answer for question[0] in the quiz, here user choose the second choice which is at index 1
        user_choice = quiz.questions[0].choices[1]
        # create a user choice,
        user_answer = UserChoice(choice=user_choice, answer_right=True)
        # add the user answer to the quiz result
        quiz_result.user_choices.append(user_answer)
        quiz_result.user_choices.append(
            UserChoice(choice=quiz.questions[1].choices[1],
                       answer_right=False))
        # add and commit changes
        db.session.add(quiz_maker)
        db.session.add(quiz_taker)
        db.session.commit()
        # query all users
        users = User.query.all()
        # print(users[1].quizzes_results[0])
        return render_template('%s.html' % page, users=users)
    except Exception as ex:
        print(ex)
        abort(404)
Beispiel #11
0
    def validate_quizjson(self, quizjson):
        try:
            ALLOWED_EXTENSIONS = ['json', 'txt']
            filename = quizjson.data.filename

            if not ('.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS):
               raise ValidationError('Please upload a json File Format')

            file_content = quizjson.data.read()
            parsed_quiz = json.loads(file_content)
            
            mandatory_fields = ["name", "questions"]
            for key in mandatory_fields:
                if key not in parsed_quiz:
                    raise ValidationError(key + ' is a mandatory field.')

            ques = parsed_quiz['questions']
            if type(ques) != list:
                raise ValidationError('Questions should be list of disctionaries.')

            mandatory_fields_ques = ['type', 'question', 'correct']
            for qu in ques:
                for key in mandatory_fields_ques:
                    if key not in qu:
                        raise ValidationError(key + ' is mandatory for all questions.')
                if type(qu['type']) != int or qu['type'] < 1:
                    raise ValidationError('Question type should always be an integer greater than 0.')
                if 'marks' in qu and (type(qu['marks']) != int or qu['marks'] < 1):
                    raise ValidationError('Question marks should always be an integer greater than 0.')
                if qu['type'] == 1: 
                    if 'options' not in qu:
                        raise ValidationError('options is mandatory for question type 1 (MCQs).')
                    elif type(qu['options']) != list:
                        raise ValidationError('options should be comma sepearted list of values.')
            print('valid json')
            qu_id = Quiz.query.order_by(Quiz.id.desc()).first()
            q_id = 0
            if not qu_id:
                q_id = 1
            else:
                q_id += qu_id.id + 1
            print(q_id)
            print(parsed_quiz['name'])
            print(current_user)
            quiz = Quiz(name=parsed_quiz['name'], author=current_user)
            db.session.add(quiz)
            #db.session.commit()
            for que in ques:
                question = Question(quiz=quiz, ques_type=que['type'], question=que['question'], options=que['options'], correct_answer=que['correct'], marks=que['marks'])
                db.session.add(question)
                #db.session.commit()
            db.session.commit()

        except json.decoder.JSONDecodeError as e:
            raise ValidationError('Invalid JSON File: ' + str(e))
Beispiel #12
0
def create():

    if request.form:
        name = request.form["quiz_name"]
        new_quiz = Quiz(name=name)
        db.session.add(new_quiz)
        db.session.commit()

        return redirect(url_for("show_quizzes"))

    return render_template("create.html")
Beispiel #13
0
def createquiz(): #currently used
    form = CreateQuizForm() 
    #user check should go above form = 
    #if current_user.is_authenticated: # fix chekc for users
    #    return redirect(url_for('index'))
    if form.validate_on_submit():
        quiz = Quiz(quizname=form.quizname.data, q1=form.q1.data, q2=form.q2.data, q3=form.q3.data)
        db.session.add(quiz)
        db.session.commit()
        flash('Congratulations, you have made a quiz')
        return redirect(url_for('login'))
    return render_template('create_quiz.html', title='Create-Quiz', form=form)
Beispiel #14
0
def quiz():

    # querie to get a list of short answer questions
    short_questions = Question.query.filter_by(long_question=False)
    # querie to get a list of long answer questions
    long_questions = Question.query.filter_by(long_question=True)
    result = 0

    # if the quiz form on quiz.html has been submitted
    if request.method == "POST":

        # check if the answer submitted are correct for the short answer questions and generate the result accordingly
        for question in short_questions:
            strqid = str(question.id)
            request_name = request.form[strqid]
            if Option.query.filter_by(
                    option_body=request_name).first().correct:
                result += 1

        #check if quiz has been done by a user previously if not add a quiz table for the result of the user
        if not bool(Quiz.query.filter_by(user_id=current_user.id).first()):
            quiz = Quiz(usersesh=current_user)
            db.session.add(quiz)
            db.session.commit()
        current_user.quiz[0].result = result
        db.session.commit()

        # check if a long answer question has been answered in the past if not then add it, if so reset all responses and marks
        for question in long_questions:
            strqid = str(question.id)
            longAnswer = request.form[strqid]
            if not bool(
                    Long_Answers.query.filter_by(
                        user_id=current_user.id,
                        question_id=question.id).first()):
                long_answer = Long_Answers(long_answer_user=current_user,
                                           long_question=question)
                db.session.add(long_answer)
                db.session.commit()
            dbsesh = current_user.long_answer.filter_by(
                question_id=question.id).first()
            dbsesh.answer = longAnswer
            dbsesh.response = None
            dbsesh.mark = None
            db.session.commit()

        return redirect(url_for('account'))

    return render_template('quiz.html',
                           title='Quiz',
                           short_questions=short_questions,
                           long_questions=long_questions)
Beispiel #15
0
def create_quiz():
    if current_user.is_anonymous:
        return redirect(url_for("login"))

    form = CreateQuizForm()
    if form.validate_on_submit():
        quiz = Quiz(name=form.title.data, authorID=current_user.id)
        db.session.add(quiz)
        db.session.commit()
        flash("Quiz erstellt")
        return redirect(url_for("create_question", quizID=quiz.id))

    return render_template("create_quiz.html", form=form)
Beispiel #16
0
def randomQuiz():
  catLength = random.randint(5, 15)
  nameLength = random.randint(5,15)
  catname = ""
  quizname = ""
  for i in range(0,catLength):
    catname += random.choice(string.ascii_letters)
  for i in range(0,nameLength):
    quizname += random.choice(string.ascii_letters)
  quizfilename = quizname + '.JSON'
  randuser = random.choice(User.query.all())
  quiz = Quiz(category=catname, quizname=quizname, filename=quizfilename, user_id=randuser.id)
  db.session.add(quiz)
  db.session.commit()
Beispiel #17
0
def index():
    """Renders the homepage.

    Creates a quizzer or quizmaster. Adds them to the db.
    Sets the username and quizid of the user in the session.
    Button to delete all users and quizzes from the db.
    """
    join_form = JoinQuizForm()
    create_form = CreateQuizForm()

    if join_form.joinSubmit.data and join_form.validate():
        quiz = Quiz.query.filter_by(id=join_form.quizid.data).first_or_404()
        user = User(username=join_form.username.data, quizid=quiz.id)
        db.session.add(user)
        db.session.commit()
        login_user(user)
        user.set_logged_in_status(True)
        db.session.commit()
        session["USERNAME"] = user.username
        session["QUIZID"] = quiz.id
        next_page = request.args.get('next')
        if not next_page or url_parse(next_page).netloc != '':
            next_page = url_for('main.quiz')
        return redirect(next_page)

    if create_form.createSubmit.data and create_form.validate():
        quiz = Quiz(quizname=create_form.quizname.data,
                    quizmaster=create_form.username.data)
        db.session.add(quiz)
        db.session.commit()
        user = User(username=create_form.username.data, quizid=quiz.id)
        db.session.add(user)
        db.session.commit()
        login_user(user)
        user.set_logged_in_status(True)
        db.session.commit()
        session["USERNAME"] = user.username
        session["QUIZID"] = quiz.id
        next_page = request.args.get('next')
        if not next_page or url_parse(next_page).netloc != '':
            next_page = url_for('main.quizmaster')
        return redirect(next_page)

    return render_template('index.html',
                           title='Home',
                           join_form=join_form,
                           create_form=create_form)
Beispiel #18
0
def quiz():

    form = QuizForm()
    if form.validate_on_submit():
        date = form.created_at.data
        print(type(date))

        grade = form.grade.data
        print(type(grade))
        class_id = form.class_id.data
        print(type(class_id))
        db.session.add(Quiz(created_at=date, grade=str(grade), class_id=int(class_id)))
        db.session.commit()
    quizzes = Quiz.query.all()
    print(quizzes)

    return render_template('quiz.html', Title='Quizzes', form=form, quizzes=quizzes)
 def setUp(self):
     basedir = os.path.abspath(os.path.dirname(__file__))
     app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(
         basedir, 'test.db')
     self.app = app.test_client()
     db.create_all()
     user1 = User(id=0000000, username='******', email='*****@*****.**')
     user2 = User(id=5555555, username='******', email='*****@*****.**')
     quiz1 = Quiz(quizname='example_quiz',
                  creator_id='0000000',
                  q1='question1',
                  q2='question2',
                  q3='question3')
     db.session.add(user1)
     db.session.add(user2)
     db.session.add(quiz1)
     db.session.commit()
Beispiel #20
0
def create_quiz():
    #Ensures that only admin has access to this page
    if current_user.get_id() != 0:
        flash("You don't have access to this page")
        return redirect(url_for('index'))
    form = CreateQuizForm()
    #If all values valid, create new quiz and redirect to question creation process
    if form.validate_on_submit():
        quiz = Quiz(quiz_name=str(form.name.data).strip(),
                    quiz_image=form.image.data,
                    hidden=1)
        db.session.add(quiz)
        db.session.commit()
        #Placeholder for linking to creating questions in a quiz
        #flash("Congratulations, you've successfully added a quiz!")
        return redirect(url_for('create_question', quiz_id=quiz.quiz_id))
    return render_template('./admin/create_quiz.html',
                           title='Create new Quiz',
                           form=form)
Beispiel #21
0
def upload():
  if(current_user.is_admin==False):
    return redirect(url_for('index')) #only admins can visit this page
  quizform=AddQuizForm()
  if quizform.validate_on_submit():
    basedir = os.path.abspath(os.path.dirname(__file__))
    quiz_dir = os.path.join(basedir, 'static')
    quizfile = quizform.quiz.data

    quizfilename = secure_filename(quizfile.filename)
    # save the quiz file
    quizfile.save(os.path.join(quiz_dir, 'quizzes', quizfilename))

    flash('Quiz uploaded successfully.')
    quiz = Quiz(quizname=quizform.quizname.data, category=quizform.category.data, filename=quizfilename, user_id=current_user.id )
    db.session.add(quiz)
    db.session.commit()
    return redirect(url_for('index'))
  return render_template('uploadquestions.html', quizform=quizform)
Beispiel #22
0
def reload():
    try:
        db.session.query(UserQuizProgress).delete()
        db.session.query(Answers).delete()
        db.session.query(Question).delete()
        db.session.query(Quiz).delete()
        User.query.update({User.rating: 0})

        answers1 = [
            Answers(answer="Ответ 1"),
            Answers(answer="Ответ 2", isAnswer=True),
            Answers(answer="Ответ 3")
        ]
        answers2 = [
            Answers(answer="Ответ 1"),
            Answers(answer="Ответ 2", isAnswer=True),
            Answers(answer="Ответ 3")
        ]
        answers3 = [Answers(answer="test", isAnswer=True)]
        questions = [
            Question(question="Вопрос 1", type=Type.CHECKBOX,
                     answers=answers1),
            Question(question="Вопрос 2", type=Type.RADIO, answers=answers2),
            Question(question="Вопрос 3",
                     type=Type.TEXTFIELD,
                     answers=answers3)
        ]
        quiz = Quiz(name="Тестовый тест", questions=questions)
        db.session.add(quiz)
        db.session.commit()
        flash("База обновлена")
    except Exception as e:
        db.session.rollback()
        flash("База не обновилась: " + e.__str__())

    return redirect(url_for('main.index'))
Beispiel #23
0
    db.session.commit()

for index, row in dfquestion.iterrows():
    u = Question(id=row[0], question=row[1], category=row[2], num_pres=row[3])
    db.session.add(u)
    db.session.commit()

for index, row in dfanswer.iterrows():
    u = Answer(id=row[0], answer=row[1])
    db.session.add(u)
    db.session.commit()

for index, row in dfmiddle.iterrows():
    u = QuestionAnswer(id=row[0],
                       question_id=row[1],
                       answer_id=row[2],
                       correct=row[3],
                       num_picked=row[1])
    db.session.add(u)
    db.session.commit()

for index, row in dfquiz.iterrows():
    u = Quiz(id=row[0],
             user_id=row[1],
             category=row[2],
             recent_score=row[3],
             total_score=row[4],
             attempts=row[5])
    db.session.add(u)
    db.session.commit()
Beispiel #24
0
def create_quiz():
    if not _validate_session():
        abort(401)

    data = request.json
    if 'timeLim' not in data or 'name' not in data or 'ownerid' not in data or 'groupName' not in data or \
            'questions' not in data:
        abort(400)

    try:
        time_limit = int(data['timeLim'])
        ownerid = int(data['ownerid'])
        questions_attrs = list(data['questions'])
    except ValueError:
        abort(400)
        return
    name = data['name']
    group_name = data['groupName']
    target_group = Group.query.filter_by(name=group_name).first()

    if not target_group:
        return jsonify(success=False,
                       message="Group {} does not exist!".format(group_name))

    questions = []
    for question_attr in questions_attrs:
        size = int(question_attr['size'])
        max_cadt = int(question_attr['maxCADT'])
        rule = DEFAULT_DATA['rules'][question_attr['rule']]
        phonemes = DEFAULT_DATA['phonemes']
        gen = Generator(phonemes, DEFAULT_DATA['templates'], rule, 5,
                        DEFAULT_DATA['f2t'], DEFAULT_DATA['f2ss'])
        rule_type = rule.get_rule_type(phonemes, DEFAULT_DATA['f2t'],
                                       DEFAULT_DATA['f2ss'])

        q_data = gen.generate(GenMode.IPAg, [size, max_cadt * 5], True, False,
                              DEFAULT_DATA['gloss_grp'])

        question_obj = Question(templates=q_data['templates'],
                                poi=' '.join(q_data['phone_interest']),
                                rule_type=str(rule_type),
                                phonemes=' '.join(q_data['phonemes']),
                                rule_name=rule.get_name(),
                                gloss=q_data['Gloss'],
                                UR=q_data['UR'],
                                SR=q_data['SR'],
                                size=size,
                                canUR=bool(question_attr['canUR']),
                                canPhoneme=bool(question_attr['canPhoneme']),
                                maxCADT=max_cadt,
                                rule_content=rule.get_content_str(),
                                rule_family=rule.get_family().get_name())
        questions.append(question_obj)
        db.session.add(question_obj)

    quiz = Quiz(name=name, owner_id=ownerid, time_limit_seconds=time_limit)
    db.session.add(quiz)
    db.session.flush()

    for question in questions:
        db.session.add(QuizQuestion(quiz_id=quiz.id, question_id=question.id))

    for user_bond in target_group.users_bond:
        db.session.add(UserQuiz(quiz_id=quiz.id, user_id=user_bond.user_id))

    db.session.commit()
    return jsonify(success=True)
def import_quiz(filename):
    quiz_df = pandas.read_csv(filename)
    for quiz_id, data in quiz_df.groupby('quiz_id'):
        print quiz_id

        subreddit = data.subreddit.min()
        num_questions = len(data) // 2
        #Create a new quiz


        num_questions_added = 0

        new_quiz = Quiz(subreddit=subreddit, num_questions=num_questions)
        db.session.add(new_quiz)
        db.session.commit()

        for pair_id, images in data.groupby('question_id'):
            if len(images) < 2:
                continue
            image_dict = images.to_dict(orient='records')
            posts = []
            for image in image_dict:

                """ First check if the post is in the database already"""

                query_1 = Post.query.filter(Post.reddit_id==image['id'])

                if len(query_1.all()) > 0 :
                    p = query_1.first()
                else:
                    if 'year' in image:
                        image_year = image['year']
                    else:
                        image_year = -1
                    if 'month' in image:
                        image_month = image['month']
                    else:
                        image_month = -1
                    p = Post(image['url'], image['title'], image['score'], image['id'], subreddit, 
                             image_year,image_month)
                    db.session.add(p)
                    db.session.commit()
                posts.append(p)
            if posts[0].id == posts[1].id:
                continue
            if posts[0].url =='http://i.imgur.com/gooPC.png' or posts[1].url=='http://i.imgur.com/gooPC.png':
                continue

            if posts[0].score == posts[1].score:
                continue

            if posts[0].url.find('#') != -1 or posts[1].url.find('#') != -1:
                continue

            if posts[0].url.find('?') != -1 or posts[1].url.find('?') != -1:
                continue



            image_pair = ImagePair(image_1_id = posts[0].id, image_2_id = posts[1].id)
            db.session.add(image_pair)
            db.session.commit()
            num_questions_added += 1


            quiz_to_image_pair = Quiz_to_ImagePair(quiz_id = new_quiz.id, image_pair_id = image_pair.id)
            db.session.add(quiz_to_image_pair)
            db.session.commit()
        
        if num_questions_added < num_questions:
            new_quiz.num_questions = num_questions_added
            db.session.commit()
Beispiel #26
0
def seed_quizzes():

    users = User.query.all()
    categories = Category.query.all()

    demo1 = Quiz(
        name="How Well Do You Know Computer Science?",
        hashed_password=None,
        is_private=False,
        question_quantity=5,
        user=users[0],
        category=categories[0]
    )

    demo2 = Quiz(
        name="Let's Make Drinks!",
        hashed_password=None,
        is_private=False,
        question_quantity=5,
        user=users[0],
        category=categories[1]
    )

    demo3 = Quiz(
        name="What is Zoology?",
        hashed_password=None,
        is_private=False,
        question_quantity=5,
        user=users[0],
        category=categories[2]
    )

    demo4 = Quiz(
        name="Let's Dive into Some Plant Science...",
        hashed_password=None,
        is_private=False,
        question_quantity=5,
        user=users[0],
        category=categories[3]
    )

    demo5 = Quiz(
        name="Ruby on Rails Commands",
        hashed_password=None,
        is_private=False,
        question_quantity=5,
        user=users[0],
        category=categories[0])

    demo6 = Quiz(
        name="Learn Node.js",
        hashed_password=None,
        is_private=False,
        question_quantity=5,
        user=users[0],
        category=categories[0])

    demo7 = Quiz(
        name="Properties of Hair and Scalp",
        hashed_password=None,
        is_private=False,
        question_quantity=5,
        user=users[0],
        category=categories[5]
    )

    demo8 = Quiz(
        name="Basics of Linear Algebra",
        hashed_password=None,
        is_private=False,
        question_quantity=5,
        user=users[0],
        category=categories[6]
    )

    demo9 = Quiz(
        name="Grammy Awards 2019",
        hashed_password=None,
        is_private=False,
        question_quantity=5,
        user=users[0],
        category=categories[7]
    )

    demo10 = Quiz(
        name="Cooking Vocabulary",
        hashed_password=None,
        is_private=False,
        question_quantity=5,
        user=users[0],
        category=categories[8]
    )

    demo11 = Quiz(
        name="NBA All Stars 2020-21",
        hashed_password=None,
        is_private=False,
        question_quantity=5,
        user=users[0],
        category=categories[4]
    )

    quizzes = {demo1, demo2, demo3, demo4, demo5,
               demo6, demo7, demo8, demo9, demo10,
               demo11}
    for quiz in quizzes:
        db.session.add(quiz)
        db.session.commit()
        db.session.flush()
 def test_user_attempt_quiz(self):
     u = User(username="******", email='*****@*****.**', id=1)
     quiz = Quiz(category="Movies", filename="otters.json", user_id=u.id)
     attempt = Attempt(user_id=u.id, quiz_id=quiz.id, score=5)
     self.assertEqual(attempt.user_id, u.id)
Beispiel #28
0
def make_quiz(session, title='sample_quiz'):
    quiz = Quiz()
    quiz.title = title
    session.add(quiz)
    session.commit()
    return quiz
 def init_db_helper(self):
     user = User(username="******", email="*****@*****.**")
     user.set_password('password')
     user.admin = False
     db.session.add(user)
     db.session.add(Quiz(quizname="Flag Quiz", creator_id=1, style=1))
     db.session.add(
         QuizStyle(style_name="Old flag style",
                   template_file="quizStyle1.html"))
     db.session.add(
         QuizContent(
             quiz_id=1,
             text_content=
             "Are you truly aware of the outside world? Do you have what it takes to test your knowledge on the flags of the world? Take our test !",
             img_content="au.svg"))
     db.session.add(Question(quiz_id=1, question_number=1))
     db.session.add(Question(quiz_id=1, question_number=2))
     db.session.add(Question(quiz_id=1, question_number=3))
     db.session.add(Question(quiz_id=1, question_number=4))
     db.session.add(Question(quiz_id=1, question_number=5))
     db.session.add(Question(quiz_id=1, question_number=6))
     db.session.add(Question(quiz_id=1, question_number=7))
     db.session.add(Question(quiz_id=1, question_number=8))
     db.session.add(Question(quiz_id=1, question_number=9))
     db.session.add(Question(quiz_id=1, question_number=10))
     db.session.add(
         QuestionContent(question_id=1,
                         text_content="What country flag is this?",
                         img_content="flag01.svg"))
     db.session.add(
         QuestionContent(question_id=2,
                         text_content="What country flag is this?",
                         img_content="flag02.svg"))
     db.session.add(
         QuestionContent(question_id=3,
                         text_content="What country flag is this?",
                         img_content="flag03.svg"))
     db.session.add(
         QuestionContent(question_id=4,
                         text_content="What country flag is this?",
                         img_content="flag04.svg"))
     db.session.add(
         QuestionContent(question_id=5,
                         text_content="What country flag is this?",
                         img_content="flag05.svg"))
     db.session.add(
         QuestionContent(question_id=6,
                         text_content="What country flag is this?",
                         img_content="flag06.svg"))
     db.session.add(
         QuestionContent(question_id=7,
                         text_content="What country flag is this?",
                         img_content="flag07.svg"))
     db.session.add(
         QuestionContent(question_id=8,
                         text_content="What country flag is this?",
                         img_content="flag08.svg"))
     db.session.add(
         QuestionContent(question_id=9,
                         text_content="What country flag is this?",
                         img_content="flag09.svg"))
     db.session.add(
         QuestionContent(question_id=10,
                         text_content="What country flag is this?",
                         img_content="flag10.svg"))
     db.session.add(
         QuestionChoice(question_id=1,
                        choice_number=1,
                        choice_content="Namibia",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=1,
                        choice_number=2,
                        choice_content="Turks and Caicos Islands",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=1,
                        choice_number=3,
                        choice_content="Mongolia",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=1,
                        choice_number=4,
                        choice_content="Saint Pierre and Miquelon",
                        choice_correct=True))
     db.session.add(
         QuestionChoice(question_id=2,
                        choice_number=1,
                        choice_content="French Polynesia",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=2,
                        choice_number=2,
                        choice_content="Maldives",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=2,
                        choice_number=3,
                        choice_content="Djibouti",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=2,
                        choice_number=4,
                        choice_content="Botswana",
                        choice_correct=True))
     db.session.add(
         QuestionChoice(question_id=3,
                        choice_number=1,
                        choice_content="Anguilla",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=3,
                        choice_number=2,
                        choice_content="Lesotho",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=3,
                        choice_number=3,
                        choice_content="Western Sahara",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=3,
                        choice_number=4,
                        choice_content="Gabon",
                        choice_correct=True))
     db.session.add(
         QuestionChoice(question_id=4,
                        choice_number=1,
                        choice_content="Heard Island and McDonald Islands",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=4,
                        choice_number=2,
                        choice_content="American Samoa",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=4,
                        choice_number=3,
                        choice_content="Zimbabwe",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=4,
                        choice_number=4,
                        choice_content="Puerto Rico",
                        choice_correct=True))
     db.session.add(
         QuestionChoice(question_id=5,
                        choice_number=1,
                        choice_content="Isle of Man",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(
             question_id=5,
             choice_number=2,
             choice_content="South Georgia and the South Sandwich Islands",
             choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=5,
                        choice_number=3,
                        choice_content="Iran",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=5,
                        choice_number=4,
                        choice_content="Pitcairn",
                        choice_correct=True))
     db.session.add(
         QuestionChoice(question_id=6,
                        choice_number=1,
                        choice_content="Korea (Republic of)",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=6,
                        choice_number=2,
                        choice_content="Cayman Islands",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=6,
                        choice_number=3,
                        choice_content="Myanmar",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=6,
                        choice_number=4,
                        choice_content="Kiribati",
                        choice_correct=True))
     db.session.add(
         QuestionChoice(question_id=7,
                        choice_number=1,
                        choice_content="Slovenia",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=7,
                        choice_number=2,
                        choice_content="Brunei",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=7,
                        choice_number=3,
                        choice_content="Saint Martin (French part)",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=7,
                        choice_number=4,
                        choice_content="Suriname",
                        choice_correct=True))
     db.session.add(
         QuestionChoice(question_id=8,
                        choice_number=1,
                        choice_content="Finland",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=8,
                        choice_number=2,
                        choice_content="Fiji",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=8,
                        choice_number=3,
                        choice_content="Bahamas",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=8,
                        choice_number=4,
                        choice_content="Colombia",
                        choice_correct=True))
     db.session.add(
         QuestionChoice(question_id=9,
                        choice_number=1,
                        choice_content="Rwanda",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=9,
                        choice_number=2,
                        choice_content="Georgia",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=9,
                        choice_number=3,
                        choice_content="Palestine",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=9,
                        choice_number=4,
                        choice_content="Czechia",
                        choice_correct=True))
     db.session.add(
         QuestionChoice(question_id=10,
                        choice_number=1,
                        choice_content="Afghanistan",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=10,
                        choice_number=2,
                        choice_content="Indonesia",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=10,
                        choice_number=3,
                        choice_content="Angola",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=10,
                        choice_number=4,
                        choice_content="Jersey",
                        choice_correct=True))
     db.session.add(Quiz(quizname="Language Quiz", creator_id=1, style=2))
     db.session.add(
         QuizStyle(style_name="Language quiz style",
                   template_file="quizStyle2.html"))
     db.session.add(
         QuizContent(
             quiz_id=2,
             text_content=
             "How much do you know about world culture, information and languages?",
             img_content="people-banner.png"))
     db.session.add(Question(quiz_id=2, question_number=1))
     db.session.add(Question(quiz_id=2, question_number=2))
     db.session.add(Question(quiz_id=2, question_number=3))
     db.session.add(Question(quiz_id=2, question_number=4))
     db.session.add(Question(quiz_id=2, question_number=5))
     db.session.add(Question(quiz_id=2, question_number=6))
     db.session.add(Question(quiz_id=2, question_number=7))
     db.session.add(Question(quiz_id=2, question_number=8))
     db.session.add(Question(quiz_id=2, question_number=9))
     db.session.add(Question(quiz_id=2, question_number=10))
     db.session.add(
         QuestionContent(
             question_id=11,
             text_content="What is the Official Language of Taiwan",
             img_content="taiwan-languageQuiz.jpg"))
     db.session.add(
         QuestionContent(
             question_id=12,
             text_content="What is the Official Language of Australia",
             img_content="australia-languageQuiz.jpg"))
     db.session.add(
         QuestionContent(
             question_id=13,
             text_content="What is the Official Language of Norway",
             img_content="norway-languageQuiz.jpg"))
     db.session.add(
         QuestionContent(
             question_id=14,
             text_content="What is the Official Language of Colombia",
             img_content="colombia-languageQuiz.jpg"))
     db.session.add(
         QuestionContent(
             question_id=15,
             text_content="What is the Official Language of Pakistan",
             img_content="pakistan-languageQuiz.jpg"))
     db.session.add(
         QuestionContent(
             question_id=16,
             text_content="What is the Official Language of Ukraine",
             img_content="ukraine-languageQuiz.jpg"))
     db.session.add(
         QuestionContent(
             question_id=17,
             text_content="What is the Official Language of Malaysia",
             img_content="malaysia-languageQuiz.jpg"))
     db.session.add(
         QuestionContent(
             question_id=18,
             text_content="What is the Official Language of Mexico",
             img_content="mexico-languageQuiz.jpg"))
     db.session.add(
         QuestionContent(
             question_id=19,
             text_content="What is the Official Language of Iran",
             img_content="iran-languageQuiz.jpg"))
     db.session.add(
         QuestionContent(
             question_id=20,
             text_content="What is the Official Language of Indonesia",
             img_content="indonesia-languageQuiz.jpg"))
     db.session.add(
         QuestionChoice(question_id=11,
                        choice_number=1,
                        choice_content="Taiwanese",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=11,
                        choice_number=2,
                        choice_content="Japanese",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=11,
                        choice_number=3,
                        choice_content="Mandarin",
                        choice_correct=True))
     db.session.add(
         QuestionChoice(question_id=11,
                        choice_number=4,
                        choice_content="Cantonese",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=12,
                        choice_number=1,
                        choice_content="English",
                        choice_correct=True))
     db.session.add(
         QuestionChoice(question_id=12,
                        choice_number=2,
                        choice_content="German",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=12,
                        choice_number=3,
                        choice_content="Korean",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=12,
                        choice_number=4,
                        choice_content="Russian",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=13,
                        choice_number=1,
                        choice_content="German",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=13,
                        choice_number=2,
                        choice_content="Spanish",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=13,
                        choice_number=3,
                        choice_content="English",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=13,
                        choice_number=4,
                        choice_content="Romani",
                        choice_correct=True))
     db.session.add(
         QuestionChoice(question_id=14,
                        choice_number=1,
                        choice_content="Spanish",
                        choice_correct=True))
     db.session.add(
         QuestionChoice(question_id=14,
                        choice_number=2,
                        choice_content="Irish",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=14,
                        choice_number=3,
                        choice_content="Dutch",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=14,
                        choice_number=4,
                        choice_content="French",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=15,
                        choice_number=1,
                        choice_content="Perish",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=15,
                        choice_number=2,
                        choice_content="Hindi",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=15,
                        choice_number=3,
                        choice_content="Arabic",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=15,
                        choice_number=4,
                        choice_content="Urdu",
                        choice_correct=True))
     db.session.add(
         QuestionChoice(question_id=16,
                        choice_number=1,
                        choice_content="Ukrainian",
                        choice_correct=True))
     db.session.add(
         QuestionChoice(question_id=16,
                        choice_number=2,
                        choice_content="Russian",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=16,
                        choice_number=3,
                        choice_content="Greenlandic",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=16,
                        choice_number=4,
                        choice_content="Galician",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=17,
                        choice_number=1,
                        choice_content="Malaysian",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=17,
                        choice_number=2,
                        choice_content="Malayense",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=17,
                        choice_number=3,
                        choice_content="Mandarin",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=17,
                        choice_number=4,
                        choice_content="Malay",
                        choice_correct=True))
     db.session.add(
         QuestionChoice(question_id=18,
                        choice_number=1,
                        choice_content="Spanish",
                        choice_correct=True))
     db.session.add(
         QuestionChoice(question_id=18,
                        choice_number=2,
                        choice_content="Mexian",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=18,
                        choice_number=3,
                        choice_content="Portuguese",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=18,
                        choice_number=4,
                        choice_content="Welsh",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=19,
                        choice_number=1,
                        choice_content="Arabic",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=19,
                        choice_number=2,
                        choice_content="Hebrew",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=19,
                        choice_number=3,
                        choice_content="Persian",
                        choice_correct=True))
     db.session.add(
         QuestionChoice(question_id=19,
                        choice_number=4,
                        choice_content="Hindi",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=20,
                        choice_number=1,
                        choice_content="Malay",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=20,
                        choice_number=2,
                        choice_content="Indonesia",
                        choice_correct=True))
     db.session.add(
         QuestionChoice(question_id=20,
                        choice_number=3,
                        choice_content="Mandarin",
                        choice_correct=False))
     db.session.add(
         QuestionChoice(question_id=20,
                        choice_number=4,
                        choice_content="Thai",
                        choice_correct=False))
Beispiel #30
0
load_dotenv()

with app.app_context():
    db.drop_all()
    db.create_all()

    demo = User(email="*****@*****.**",
                username="******",
                hashedPassword=sha256_crypt.hash("password"))

    nick = User(email="*****@*****.**",
                username="******",
                hashedPassword=sha256_crypt.hash("password"))

    jsTrivia = Quiz(userId=2, category="jsTrivia", name="JavaScipt Trivia 1")

    question1 = Question(
        quizId=1,
        questionType="mc",
        content="Is JavaScript single threaded or multi threaded?")

    q1a1 = AnswerChoice(content="Multi threaded", order=1, questionId=1)

    q1a2 = AnswerChoice(content="Single Threaded", order=2, questionId=1)

    answerJoin1 = AnswerJoin(questionId=1, answerChoiceId=2)

    question2 = Question(quizId=1,
                         questionType="mc",
                         content="What is one difference between let and var?")