Esempio n. 1
0
def delete_question(id: int) -> wrappers.Response:
    Questions.query.get_or_404(id)
    try:
        Questions.delete_note(id)
        return jsonify({"200 OK": "HTTP/1.1"})
    except:
        return jsonify({"403 Forbidden": "HTTP/1.1"})
Esempio n. 2
0
def edit_question(id: int) -> wrappers.Response:
    Questions.query.get_or_404(id)
    try:
        Questions.edit(request.get_json(), id)
        return jsonify({"200 OK": "HTTP/1.1"})
    except:
        return jsonify({"403 Forbidden": "HTTP/1.1"})
Esempio n. 3
0
def process_data_to_db(data):
    rows = data.shape[0]
    ####
    for i in range(rows):
        #process row
        qcode = data.iloc[i].QCode
        qname = data.iloc[i].Title
        qlink = qcode
        sol_link = None
        if type(data.iloc[i].Editorial) == type("  "):
            sol_link = qcode
        platform = "codechef"
        tags = data.iloc[i].Tags
        tags = tags.strip('[]')
        tags_list = tags.split(',')
        tags_list = [t.strip().strip('\'') for t in tags_list]
        #insert into db
        if sol_link:
            question = Questions(Qname=qname,
                                 Ques_link=qlink,
                                 Sol_link=sol_link,
                                 Platform=platform)
        else:
            question = Questions(Qname=qname,
                                 Ques_link=qlink,
                                 Sol_link=None,
                                 Platform=platform)
        db.session.add(question)
        db.session.flush()
        db.session.refresh(question)
        qid = question.Qid
        for tag in tags_list:
            tag_entry = QuestionTags(Tag=tag, Ques_id=qid)
            db.session.add(tag_entry)
    db.session.commit()
Esempio n. 4
0
def add_question() -> wrappers.Response:
    question = request.get_json()
    print(question)
    try:
        Questions.add(question)
        return jsonify({"201 Created": "HTTP/1.1"})
    except:
        return jsonify({"403 Forbidden": "HTTP/1.1"})
Esempio n. 5
0
 def create_questions():
     data = request.get_json()
     question = data.get('question')
     date_posted = datetime.datetime.now()
     new_question = Questions(question, date_posted)
     return jsonify({
         'message': 'success, Question created',
         'question': new_question.save()
     }), 201
Esempio n. 6
0
def add_question_to_db():
    """
        Adds question, answer pairs to database
    """
    data = request.get_json(silent=False)
    user_id = current_user.get_id()
    user = Users.query.filter(Users.id == user_id).first()
    content = data['sentence']
    answer = data['answer']
    question_date = data['question_date']
    answer_date = data['answer_date']

    if content != "":
        # add question, answer pair
        words = UserWords(content=content,
                          answer=answer,
                          time=question_date,
                          answer_time=answer_date)
        words.talker_id = user.id
        db.session.add(words)

        # increment question count for all users
        count = db.session.query(Questions).filter_by(
            talker_id=user_id).first()
        if count is None:
            db.session.add(Questions(question=1, talker_id=user_id))
        else:
            count.question = int(count.question) + 1
        db.session.commit()
    return 'OK', 200
Esempio n. 7
0
    def generate_questions(self, cnt):
        if cnt is None:
            return False

        print('Generate {} questions'.format(cnt))
        author_ids = list(Users.objects.values_list('id', flat=True))
        tags_ids = list(Tags.objects.values_list('id', flat=True))
        print('start generate array of questions {}'.format(
            datetime.datetime.now()))
        questions = [
            Questions(title=f.sentence(nb_words=10),
                      text=f.paragraph(nb_sentences=5),
                      date=f.date_this_year(),
                      rating=f.pyint(0, 1000),
                      author_id=choice(author_ids)) for _ in range(cnt)
        ]
        print('end generate array of questions {}'.format(
            datetime.datetime.now()))
        print('start add questions to DB {}'.format(datetime.datetime.now()))
        self.insert_data(Questions, questions)
        print('end add questions to DB {}'.format(datetime.datetime.now()))
        print('start add tags to questions to DB {}'.format(
            datetime.datetime.now()))
        for item in Questions.objects.all():
            tags = list(choices(tags_ids, k=randint(0, 6)))
            item.tags.add(*tags)
        print('end add tags to questions to DB {}'.format(
            datetime.datetime.now()))
def process_data_to_db(data):
    rows = data.shape[0]
    ####
    prev_name = None
    for i in range(rows):
        #process row
        if ((i >= 860 and i < 910)
                or (i >= 25480 and i < 25830)):  #error for these indices
            continue
        qname = str(data['name'][i])
        if prev_name:
            if qname == prev_name:
                continue
        qcode = data.iloc[i].id
        qcode_contest = qcode[:-1]
        qcode_problem = qcode[-1]
        qlink = str(qcode_contest) + "/problem/" + str(qcode_problem)
        sol_link = str(qcode_contest) + "/submission/" + str(data['sol id'][i])
        platform = "codeforces"
        tags = data.iloc[i].tags
        tags_list = tags.split(',')
        #insert into db
        question = Questions(Qname=qname,
                             Ques_link=qlink,
                             Sol_link=sol_link,
                             Platform=platform)
        db.session.add(question)
        db.session.flush()
        db.session.refresh(question)
        qid = question.Qid
        for tag in tags_list:
            tag_entry = QuestionTags(Tag=tag, Ques_id=qid)
            db.session.add(tag_entry)
        prev_name = qname
    db.session.commit()
def AskQuestion():
    form = AskQuestionForm(request.form)

    if form.validate():
        user = current_user
        question = Questions(Title=form.Title.data,
                             Content=form.Body.data,
                             User_id=user.id)
        db.session.add(question)
        db.session.commit()
        return redirect(url_for('main.Home'))

    return render_template("askquestion.html", form=form)
Esempio n. 10
0
def admin():
    if current_user.admin:
        form = QuestionForm()
        if form.validate_on_submit():
            question = Questions(question=form.question.data,
                                 answers=form.answers.data,
                                 correct_answer=form.correct.data,
                                 speed=form.speed.data)
            db.session.add(question)
            db.session.commit()
            return redirect(url_for('admin'))
        return render_template('admin.html', form=form)
    else:
        return redirect(url_for('index'))
Esempio n. 11
0
def add_question():
    form = AddQuestionForm()
    if request.method == 'POST' and form.validate():
        user_id = g.user.id
        question = request.form['question']
        details = request.form['details']
        new_question = Questions(question=question,
                                 details=details,
                                 user_id=user_id)
        db_session.add(new_question)
        db_session.commit()
        flash('Your question successfully submitted!')
        return redirect(url_for('main_page'))
    return render_template('add_question.html',
                           title='Add question',
                           form=form)
Esempio n. 12
0
def Post_Answer(title):
    new_ans_id = AnswerId()
    user = session['user']
    reqd = Questions.query.filter((Questions.title == title)).first()
    row_updated = Questions(qid=mydefault(),
                            title=reqd.title,
                            question_body=reqd.question_body,
                            answer_id=new_ans_id,
                            asked_by_username=reqd.asked_by_username)
    db.session.add(row_updated)
    db.session.commit()
    answer = request.form["answer-body"]
    answer_updated = Answers(answer_id=new_ans_id,
                             answer_body=answer,
                             answered_by_user=user)
    db.session.add(answer_updated)
    db.session.commit()
    return render_template('index.html', logged_in=True)
Esempio n. 13
0
def Ask_Question():
    usrname = session['user']
    title = request.form['question_title']
    body = request.form['question_body']
    tag = request.form['question_tags']
    question = Questions(title=title,
                         qid=mydefault(),
                         question_body=body,
                         asked_by_username=usrname,
                         tag=tag)
    db.session.add(question)
    db.session.commit()
    userinf = User.query.filter((User.username == session['user'])).first()
    pic2 = None
    if userinf.profile_image_data != None:
        pic = b64encode(userinf.profile_image_data)
        pic2 = pic.decode('ascii')
    return render_template('User_HomePage.html',
                           username=userinf.display_name,
                           userinfo=userinf,
                           image=pic2)
Esempio n. 14
0
def ask():
    experts = User.query.filter_by(expert=True)
    if request.method == "POST":
        user_question = request.form.get("question")
        expert = request.form.get("experts")

        #get expert username
        name = User.query.get(int(expert))

        #add to database
        new_question = Questions(expert_id=int(expert),
                                 question=user_question,
                                 answer=" ",
                                 expert_name=name.username,
                                 qna=current_user)

        db.session.add(new_question)
        db.session.commit()

        flash("Question uploaded successfully")
        return (redirect(url_for("main.ask")))
    else:
        return (render_template("ask.html", experts=experts))
Esempio n. 15
0
def postQuestion():
    if (not session or not session['loggedin']):
        return redirect(url_for('index'))

    if (request and request.method == 'POST'):
        title = request.form['title']
        body = request.form['content']
        code = request.form['code']
        tagstring = request.form['tags']
        tags = tagstring.split(';')

        new_row = Questions(title, body, code, session['userid'])
        question_id = new_row.question_id
        db.session.add(new_row)

        for tag in tags:
            new_tag = Tags(tag, question_id)
            db.session.add(new_tag)

        db.session.commit()
        # return redirect(url_for("answers/"+str(2)))
        return answers(question_id)
    else:
        return render_template('question_post.html', title="Ask Question")
Esempio n. 16
0
def questions() -> Dict[str, List[Dict[str, str]]]:
    return Questions.to_json(dict(Questions.get_questions()))
Esempio n. 17
0
def views(request):
    data = {'title': 'Challenges'}

    if request.method == 'POST':
        if 'action' in request.POST:
            action = request.POST['action']

            if action == 'create_challenge':
                try:
                    with transaction.atomic():

                        if 'challenge_name' in request.POST and request.POST['challenge_name'] != '':
                            challenge_name = request.POST['challenge_name']
                            if Challenges.objects.filter(name=challenge_name).exists():
                                return bad_json(message="Challenge Name already exists. "
                                                        "Please change the name of the challenge and try again. ")

                            new_code = generate_code()
                            challenge = Challenges(name=challenge_name, code=new_code)
                            challenge.save()
                            return ok_json(data={'message': 'Good Job!. You successfully created a new Challenge.'})

                        else:
                            return bad_json(message="Not Challenge received")

                except Exception as ex:
                    return bad_json(error=1)

            if action == 'questions':
                challenge = Challenges.objects.get(pk=int(request.POST['id']))

                question = None
                if 'qid' in request.POST and request.POST['qid'] != '':
                    question = Questions.objects.get(pk=int(request.POST['qid']))

                correct_answer = int(request.POST['q_answers_checks'])

                try:
                    with transaction.atomic():

                        if not question:

                            question = Questions(challenge=challenge,
                                                 text=request.POST['q_text'],
                                                 order=request.POST['q_order'],
                                                 answer1=request.POST['q_answer1'],
                                                 answer2=request.POST['q_answer2'],
                                                 answer3=request.POST['q_answer3'],
                                                 answer4=request.POST['q_answer4'],
                                                 is_correct_answer1=True if correct_answer == 1 else False,
                                                 is_correct_answer2=True if correct_answer == 2 else False,
                                                 is_correct_answer3=True if correct_answer == 3 else False,
                                                 is_correct_answer4=True if correct_answer == 4 else False)

                        else:

                            question.text = request.POST['q_text']
                            question.order = request.POST['q_order']
                            question.counter_time = request.POST['q_counter']

                            question.answer1 = request.POST['q_answer1']
                            question.answer2 = request.POST['q_answer2']
                            question.answer3 = request.POST['q_answer3']
                            question.answer4 = request.POST['q_answer4']
                            question.is_correct_answer1 = True if correct_answer == 1 else False
                            question.is_correct_answer2 = True if correct_answer == 2 else False
                            question.is_correct_answer3 = True if correct_answer == 3 else False
                            question.is_correct_answer4 = True if correct_answer == 4 else False

                        question.save()

                        return ok_json(data={'redirect_url': '/challenges',
                                             'message': 'Successfully {} a Question'.format('Created' if not question else 'Edited')})

                except Exception:
                    return bad_json(message="Error saving data")

            if action == 'delete_question':
                try:
                    question = Questions.objects.get(pk=int(request.POST['qid']))
                    with transaction.atomic():
                        if question.responses_set.exists():
                            question.responses_set.all().delete()
                        question.delete()
                        return ok_json(data={'redirect_url': '/challenges',
                                             'message': 'Successfully Deleted the Question.'})
                except Exception:
                    return bad_json(message="Error deleting Question")

            if action == 'access_challenge':
                try:
                    code = request.POST['code']
                    if not Challenges.objects.filter(code=code).exists():
                        return bad_json(message='Code does not exist in the system.')

                    return ok_json(data={'challengeID': Challenges.objects.filter(code=code)[0].id})

                except Exception:
                    return bad_json(message='Error getting data')

            if action == 'response_question':
                question = Questions.objects.get(pk=int(request.POST['qid']))
                response = int(request.POST['response'])

                if response == 1 and question.is_correct_answer1:
                    return ok_json()

                elif response == 2 and question.is_correct_answer2:
                    return ok_json()

                elif response == 3 and question.is_correct_answer3:
                    return ok_json()

                elif response == 4 and question.is_correct_answer4:
                    return ok_json()

                else:
                    return bad_json(message='INCORRECT')

        return bad_json(message="Bad Request")

    else:

        if 'action' in request.GET:
            if 'action' in request.GET:
                action = request.GET['action']

                if action == 'questions':
                    try:
                        data['title'] = 'New Question'
                        data['challenge'] = Challenges.objects.get(pk=request.GET['id'])
                        question = None
                        if 'qid' in request.GET and request.GET['qid'] != '':
                            question = Questions.objects.get(pk=int(request.GET['qid']))
                        data['question'] = question
                        return render(request, 'challenges/questions.html', data)
                    except Exception:
                        pass

                if action == 'play':
                    try:
                        data['title'] = 'Play Challenge'
                        data['challenge'] = challenge = Challenges.objects.get(pk=request.GET['id'])
                        data['questions'] = questions = challenge.get_my_questions()
                        data['first_question'] = questions[0]
                        data['current_question'] = questions[0]
                        return render(request, 'challenges/play.html', data)
                    except Exception:
                        pass

            return HttpResponseRedirect('/challenges')

        data['challenges'] = Challenges.objects.all()
        return render(request, 'challenges/view.html', data)
Esempio n. 18
0
def add_question_existing(request):
    """
    Allow user to add question to an existing route to the database
    :param request:
    :return: Return a response to ajax call on whether the question has been added successfully
    """
    # Get the values that user want to add into the database
    question = request.POST.get('question')
    answer = request.POST.get('answer')
    hint = request.POST.get('hint')
    node_num = 1
    latitude = request.POST.get('latitude')
    longtitude = request.POST.get('longtitude')
    routeID = request.POST.get('routeID')
    # Make the node number of the new question to be added highest out of all the node number with the same routeID
    while Questions.objects.filter(node_num=node_num,
                                   routeID=routeID).exists():
        node_num += 1
        print(node_num)
    b = Questions()
    b.questions = question
    b.answers = answer
    b.hints = hint
    b.latitude = float(latitude)
    b.longtitude = float(longtitude)
    b.node_num = int(node_num)
    b.routeID_id = int(routeID)
    b.save()
    if Questions.objects.filter(questions=question).exists():
        return HttpResponse("Added successfully")
    else:
        return HttpResponse("Not added")
Esempio n. 19
0
def add_question(request):
    """
    Add questions details retrieved from the ajax call and save it to the database
    :param request:
    :return: Return a reponse to ajax call whether the question has been added successfully or not
    """
    #adding question - getting data through post request
    question = request.POST.get('question')
    answer = request.POST.get('answer')
    hint = request.POST.get('hint')
    latitude = request.POST.get('latitude')
    longtitude = request.POST.get('longtitude')
    node_num = request.POST.get('node_num')
    routeID = request.POST.get('routeID')
    routeID = striptext(routeID)
    #
    print(question, answer, hint, latitude, longtitude, node_num, routeID)
    #setting up questions object
    b = Questions()
    b.questions = question
    b.answers = answer
    b.hints = hint
    b.latitude = float(latitude)
    b.longtitude = float(longtitude)
    b.node_num = int(node_num)
    b.routeID_id = int(routeID)
    # Save instance into database
    b.save()
    #checking if the questions were added successfully or not
    if Questions.objects.filter(questions=question).exists():
        return HttpResponse("Added successfully")
    else:
        return HttpResponse("Not added")
Esempio n. 20
0
def insertQuestion(question):
    question_adding = Questions(**question)
    db.session.add(question_adding)
    db.session.commit()
Esempio n. 21
0
def views(request):
    data = {'title': 'Challenges'}

    if request.method == 'POST':
        if 'action' in request.POST:
            action = request.POST['action']

            if action == 'create_challenge':
                try:
                    with transaction.atomic():

                        if 'challenge_name' in request.POST and request.POST[
                                'challenge_name'] != '':
                            challenge_name = request.POST['challenge_name']
                            if Challenges.objects.filter(
                                    name=challenge_name).exists():
                                return bad_json(
                                    message="Challenge Name already exists. "
                                    "Please change the name of the challenge and try again. "
                                )

                            new_code = generate_code()
                            challenge = Challenges(name=challenge_name,
                                                   code=new_code)
                            challenge.save()
                            return ok_json(
                                data={
                                    'message':
                                    'Good Job!. You successfully created a new Challenge.'
                                })

                        else:
                            return bad_json(message="Not Challenge received")

                except Exception as ex:
                    return bad_json(error=1)

            if action == 'questions':
                challenge = Challenges.objects.get(pk=int(request.POST['id']))

                question = None
                if 'qid' in request.POST and request.POST['qid'] != '':
                    question = Questions.objects.get(
                        pk=int(request.POST['qid']))

                correct_answer = int(request.POST['q_answers_checks'])

                try:
                    with transaction.atomic():

                        if not question:

                            question = Questions(
                                challenge=challenge,
                                text=request.POST['q_text'],
                                order=request.POST['q_order'],
                                counter_time=request.POST['q_counter'],
                                answer1=request.POST['q_answer1'],
                                answer2=request.POST['q_answer2'],
                                answer3=request.POST['q_answer3'],
                                answer4=request.POST['q_answer4'],
                                is_correct_answer1=True
                                if correct_answer == 1 else False,
                                is_correct_answer2=True
                                if correct_answer == 2 else False,
                                is_correct_answer3=True
                                if correct_answer == 3 else False,
                                is_correct_answer4=True
                                if correct_answer == 4 else False)

                        else:

                            question.text = request.POST['q_text']
                            question.order = request.POST['q_order']
                            question.counter_time = request.POST['q_counter']

                            question.answer1 = request.POST['q_answer1']
                            question.answer2 = request.POST['q_answer2']
                            question.answer3 = request.POST['q_answer3']
                            question.answer4 = request.POST['q_answer4']
                            question.is_correct_answer1 = True if correct_answer == 1 else False
                            question.is_correct_answer2 = True if correct_answer == 2 else False
                            question.is_correct_answer3 = True if correct_answer == 3 else False
                            question.is_correct_answer4 = True if correct_answer == 4 else False

                        question.save()

                        return ok_json(
                            data={
                                'redirect_url':
                                '/challenges',
                                'message':
                                'Successfully {} a Question'.format(
                                    'Created' if not question else 'Edited')
                            })

                except Exception:
                    return bad_json(message="Error saving data")

            if action == 'delete_question':
                try:
                    question = Questions.objects.get(
                        pk=int(request.POST['qid']))
                    with transaction.atomic():
                        if question.responses_set.exists():
                            question.responses_set.all().delete()
                        question.delete()
                        return ok_json(
                            data={
                                'redirect_url': '/challenges',
                                'message': 'Successfully Deleted the Question.'
                            })
                except Exception:
                    return bad_json(message="Error deleting Question")

        return bad_json(message="Bad Request")

    else:

        if 'action' in request.GET:
            if 'action' in request.GET:
                action = request.GET['action']

            return HttpResponseRedirect('/access')

        return render(request, 'challenges/access.html', data)