示例#1
0
 def put(self, question_uuid):
     """
     PUT handler
     """
     edit_question = Question(**api.payload)
     edit_question.uuid = question_uuid
     edit_question.save()
示例#2
0
def new(request, lang):
    if request.method == 'POST':
        participant_form = ParticipantForm(request.POST)

        if participant_form.is_valid():
            participant = participant_form.save(commit=False)
            participant.ip = get_client_ip(request),
            participant.ua = get_client_ua(request),
            participant.save()

            sequences = Sequence.objects.all()
            pairs = Pair.objects.all()

            if len(sequences) > len(pairs):
                generate_pairs(len(sequences) - len(pairs) + 1)
                pairs = Pair.objects.all()
                send_email(template='email/pairs_empty.html')

            pairs = pairs[:len(sequences)]

            for sequence, pair in zip(sequences, pairs):
                question = Question(participant=participant,
                                    left=pair.left,
                                    right=pair.right,
                                    sequence=sequence,
                                    answered=False)
                question.save()
                pair.delete()

            request.session['participant_id'] = participant.id
            #messages.add_message(request, messages.SUCCESS, u'Новый участник создан')
            return redirect(reverse('core.views.index', kwargs={'lang': lang}))

    #messages.add_message(request, messages.ERROR, u'Не удалось создать участника')
    return redirect(reverse('core.views.index', kwargs={'lang': lang}))
示例#3
0
    def test_question_check_answer_with_numbers(self):
        q = Question()
        q['correct'] = u'90,000'
        self.assertTrue(q.check_answer('90,000'))
        self.assertTrue(not q.check_answer('60,000'))

        q['correct'] = u'Terminator 2'
        self.assertTrue(q.check_answer('Terminatur 2'))
示例#4
0
    def test_question_check_answer_with_numbers(self):
        q = Question()
        q['correct'] = u'90,000'
        self.assertTrue(q.check_answer('90,000'))
        self.assertTrue(not q.check_answer('60,000'))

        q['correct'] = u'Terminator 2'
        self.assertTrue(q.check_answer('Terminatur 2'))
示例#5
0
 def setUp(self):
     """Create questions for testing."""
     grade_test = Grade(name="Grade Example")
     grade_test.save()
     subject_test = Subject(name="addition", grade=grade_test)
     subject_test.save()
     question1 = Question(question_content='what is 1 + 1?',
                          answer_content='This is an addition question',
                          subject=subject_test)
     question1.save()
示例#6
0
文件: forms.py 项目: djibon/simpleqa
 def save(self):
     data = self.cleaned_data
     str_title = data['title']
     str_question = data['question']
     str_tags= data['tags']
     tags = str_tags.split(',')
     
     q = Question(user = self.user,title=str_title,question=str_question)
     q.save()
     for t in tags:
         Tag.objects.add_tag(q,t.strip())
     return q
def question_create(request):
    if request.method == 'POST':
        form = QuestionForm(request.POST)
        if form.is_valid():
            question = Question(title=form.cleaned_data['title'],
                                body=form.cleaned_data['body'],
                                user=request.user)
            question.save()
        return HttpResponseRedirect(
            reverse_lazy('question_detail', kwargs={'pk': question.pk}))
    else:
        form = QuestionForm()
    context = {'form': form}

    return render(request, 'core/question_create.html', context)
 def create(self, data):
     instance = Question()
     instance.question = data.get('question')
     instance.answer = data.get('answer')
     instance.parameter = data.get('parameter')
     instance.answer_text = data.get("answer_text")
     instance.save()
     return instance
示例#9
0
    def setUp(cls):
        """
        Data setup for Feedback Question Unit test cases
        """
        role = Role(role="organizer")
        role.save()

        user = User.objects.create_user(email="*****@*****.**",
                                        password="******")
        role_obj = Role.objects.get(role="organizer")

        user_profile_obj = UserProfile.objects.create(
            user=user,
            name="*****@*****.**",
            contact_number="9999911111",
            organization="organization",
            address="Bangalore",
            role=role_obj)
        user_profile_obj.save()
        data = dict(email="*****@*****.**", password="******")
        login_response = cls.client.post('/authentication/login',
                                         json.dumps(data),
                                         content_type='application/json')
        cls.user_id = login_response.data['data']['user']['user_id']
        cls.token = login_response.data['data']['access']
        cls.end_point = "/core/feedback-questions/"
        cls.question = Question(question="Demo question1 ?")
        cls.question.save()
示例#10
0
def dummy_questions(course: Course):
    """
    Creates a collection of dummy questions
    :param course: The course for which the questions will be generated
    """
    return [
        Question(uuid='50e46980-6c4e-450c-853e-efca2357a23a',
                 course=course,
                 question='2 + 2 ='),
        Question(uuid='29f47817-350f-4893-9372-50db5185618c',
                 course=course,
                 question='3 + 3 ='),
        Question(uuid='29f47817-350f-4893-9372-50db5185618c',
                 course=course,
                 question='4 + 4 =')
    ]
示例#11
0
 def get_question(self):
     """
     Selects a question at random
     """
     sample = {'$sample': {'size': 1}}
     result = Question.objects(course=self.course).aggregate(sample)
     document = next(result, None)
     return Question.objects.get(uuid=document['_id']) if document else None
示例#12
0
    def setUp(cls):
        """
        Data setup for Feedback Unit test cases
        """
        role = Role(role="organizer")
        role.save()
        role2 = Role(role="subscriber")
        role2.save()

        user = User.objects.create_user(email="*****@*****.**",
                                        password="******")
        cls.role_obj = Role.objects.get(role="organizer")

        user_profile_obj = UserProfile.objects.create(
            user=user,
            name="*****@*****.**",
            contact_number="9999911111",
            organization="organization",
            address="Bangalore",
            role=cls.role_obj)
        user_profile_obj.save()

        content2 = {
            "email": "*****@*****.**",
            "name": "user 20",
            "password": "******",
            "contact": "9999911111",
            "address": "Bangalore",
            "role": "subscriber",
            "organization": "Eventhigh"
        }

        response = cls.client.post('/authentication/registration',
                                   json.dumps(content2),
                                   content_type='application/json')
        cls.user_id = response.data['data']['user']['user_id']
        cls.token = response.data['data']['access']
        cls.end_point = "/core/feedback/"

        cls.event_type = EventType(type="test")
        cls.event_type.save()

        cls.event = Event(name="test_event",
                          type=cls.event_type,
                          description="New Event",
                          date="2020-04-02",
                          time="12:38:00",
                          location="karnal",
                          subscription_fee=499,
                          no_of_tickets=250,
                          images="https://www.google.com/images",
                          sold_tickets=0,
                          external_links="google.com",
                          event_created_by_id=User.objects.filter()[0].id)
        cls.event.save()
        cls.question = Question(question="Demo question1 ?")
        cls.question.save()
示例#13
0
 def test_score_single(self):
     """
     Test for score() when only a single answer is correct
     """
     answers = [
         AnswerChoice(uuid=uuid4(), answer='0', checked=False),
         AnswerChoice(uuid=uuid4(), answer='4', checked=True),
         AnswerChoice(uuid=uuid4(), answer='5', checked=False)
     ]
     question = Question(uuid=uuid4(),
                         question='2+2=?',
                         answers=answers,
                         multiple=False)
     for answer in answers:
         expected_score = 1.0 if answer.checked else 0.0
         score = question.score([answer.uuid])
         self.assertAlmostEqual
         (expected_score, score)
示例#14
0
def add_question(request):
    """adds a question authored by the pk of the user"""
    # breakpoint()
    if request.method == 'POST':
        form = QuestionCreateForm(request.POST)
        if form.is_valid():
            title = form.cleaned_data['title']
            content = form.cleaned_data['content']
            content = markdown.markdown(content)
            content = bleach.clean(content, markdown_tags, markdown_attrs)
            new_question = Question(author=request.user,
                                    content=content,
                                    title=title)
            new_question.save()
        return redirect(to='home')
    else:
        form = QuestionCreateForm()

        return render(request, 'new-question.html', {
            'form': form,
        })
示例#15
0
    def test_score_multiple(self):
        """
        Test for score() in the multi-select scenario. Coursera-style scoring is expected.
        """
        answers = [
            AnswerChoice(uuid=uuid4(), answer='Panama', checked=True),
            AnswerChoice(uuid=uuid4(), answer='Montreal', checked=False),
            AnswerChoice(uuid=uuid4(), answer='Canada', checked=True),
            AnswerChoice(uuid=uuid4(), answer='Overfitting', checked=False)
        ]
        question = Question(question="Which of the following are countries?",
                            answers=answers,
                            multiple=True)

        def get_uuids(*indexes):
            return [answers[idx].uuid for idx in indexes]

        score = question.score([])
        self.assertAlmostEqual(0.5, score)
        score = question.score(get_uuids(0, 2))
        self.assertAlmostEqual(1.0, score)
        score = question.score(get_uuids(0, 1, 3))
        self.assertAlmostEqual(0.25, score)
        score = question.score(get_uuids(0, 2, 3))
        self.assertAlmostEqual(0.75, score)
示例#16
0
 def get_question(self):
     """
     Selects the closest question to the student's current ability level
     """
     if not self.level:
         self._fetch_level()
     # TODO: Avoid repetition
     question = Question.objects(
         course=self.course,
         level__gte=self.level).order_by('level').first()
     if not question:
         question = Question.objects.order_by('-level').first()
     return question
示例#17
0
def new(request, lang):
    if request.method == 'POST':
        participant_form = ParticipantForm(request.POST)

        if participant_form.is_valid():
            participant = participant_form.save(commit=False)
            participant.ip = get_client_ip(request),
            participant.ua = get_client_ua(request),
            participant.save()

            sequences = Sequence.objects.all()
            pairs = Pair.objects.all()

            if len(sequences) > len(pairs):
                generate_pairs(len(sequences) - len(pairs) + 1)
                pairs = Pair.objects.all()
                send_email(template='email/pairs_empty.html')

            pairs = pairs[:len(sequences)]

            for sequence, pair in zip(sequences, pairs):
                question = Question(
                    participant=participant,
                    left=pair.left,
                    right=pair.right,
                    sequence=sequence,
                    answered=False
                )
                question.save()
                pair.delete()

            request.session['participant_id'] = participant.id
            #messages.add_message(request, messages.SUCCESS, u'Новый участник создан')
            return redirect(reverse('core.views.index', kwargs={'lang': lang}))

    #messages.add_message(request, messages.ERROR, u'Не удалось создать участника')
    return redirect(reverse('core.views.index', kwargs={'lang': lang}))
示例#18
0
def create_questions(form):
    """ Create a fake question for a form """
    type_list = list(Type)
    for _ in range(DEFAULT_NUMBER_QUESTIONS):
        _type = random.choice(type_list)
        question = Question(form=form, name=fake.profile()['username'],
                            question=fake.lexify(text='Random Question: ??????????'), input_type=_type.value)
        question.full_clean()
        question.save()

        create_options(question)
示例#19
0
    def test_question_check_answer(self):
        q = Question()
        q['correct'] = u'Yes'
        self.assertTrue(q.check_answer('yes'))
        self.assertTrue(not q.check_answer('no'))

        q['alternatives'] = [u'Maybe', u'Perhaps']
        self.assertTrue(q.check_answer('yes', alternatives_are_correct=True))
        self.assertTrue(q.check_answer('maybe', alternatives_are_correct=True))
        self.assertTrue(q.check_answer('perhaps', alternatives_are_correct=True))
        self.assertTrue(not q.check_answer('inte', alternatives_are_correct=True))

        # now with edit distance
        # too short
        self.assertTrue(not q.check_answer('yeah'))
        # sufficiently long
        q['correct'] = u'Correct'
        self.assertTrue(q.check_answer('corect'))
        self.assertTrue(not q.check_answer('korecct'))

        q['correct'] = u'Tupac Shakur'
        self.assertTrue(q.check_answer('tupak Shacur'))
        self.assertTrue(not q.check_answer('Toopack shakure'))  # too wrong
示例#20
0
 def delete(self, question_uuid):
     """
     DELETE handler
     """
     Question.objects(uuid=question_uuid).delete()
示例#21
0
def setup_assignment(vault_content_path, output_cabinet_path, board_id,
                     school_id, standard_number, subject_id, aql_chapter_id,
                     aql_metadata_file_number):

    # first validate the arguments against the exiting database
    board = Board.objects.get(pk=board_id)
    school = School.objects.get(pk=school_id)
    standard = Standard.objects.get(number=standard_number)
    subject = Subject.objects.get(pk=subject_id)
    aql_chapter = Chapter.objects.get(pk=aql_chapter_id)

    # build path to aql data file
    common_path = os.path.join(str(board_id), str(school_id),
                               str(standard_number), str(subject_id))

    aql_data_file_dir = os.path.join(vault_content_path, common_path)
    aql_data_file_path = os.path.join(
        aql_data_file_dir,
        str(aql_metadata_file_number) + DATA_FILE_EXT)

    with open(aql_data_file_path, 'r') as f:
        aql_data_raw = f.read().strip()

    print 'Processing AQL data'
    aql_data_raw = aql_data_raw_process(aql_data_raw)
    aql_data = json.loads(aql_data_raw)
    aql_data = aql_data_process(aql_data)

    # aql data has revision, questions and description
    # transfer the revision, put the description in db and then deal with the questions
    print 'Creating new AQL in db'
    new_aql = AssignmentQuestionsList(
        school=school,
        standard=standard,
        subject=subject,
        chapter=aql_chapter,
        number=1,  # this will be validated at the end
        description=aql_data['description'])
    new_aql.save()

    print 'Putting AQL metadata into cabinet'
    aql_output_dir = os.path.join(output_cabinet_path, 'aql_meta', common_path)

    try:
        os.makedirs(aql_output_dir)
    except OSError:
        # the output dir already exists, no need to do anything
        pass
    with open(os.path.join(aql_output_dir,
                           str(new_aql.pk) + DATA_FILE_EXT), 'w') as f:
        f.write(dump_json_string(get_aql_data_for_cabinet(aql_data)))

    # finally, copy over the img folder too - and apply watermarks
    print 'Copying AQL images'
    copy_img_folder(aql_data_file_dir, aql_output_dir)

    # now lets grab the question data too

    questions = aql_data['questions']
    question_data_file_path_stub = os.path.join(vault_content_path,
                                                common_path)

    for chapter_block in questions:
        chapter_id = chapter_block['chapter']
        db_chapter_id = chapter_block.get('chapter_db', chapter_id)
        print 'Encountered db chapter id:', db_chapter_id
        chapter = Chapter.objects.get(pk=db_chapter_id)

        question_data_file_path_stub_with_chapter = os.path.join(
            question_data_file_path_stub, str(chapter_id))
        question_container_data_file_path_stub = os.path.join(
            question_data_file_path_stub_with_chapter, 'containers')
        question_subpart_data_file_path_stub = os.path.join(
            question_data_file_path_stub_with_chapter, 'subparts')

        print 'Prepping output dirs in cabinet for question metadata files'
        question_container_output_dir = os.path.join(output_cabinet_path,
                                                     'questions', 'containers',
                                                     common_path,
                                                     str(chapter.pk))

        try:
            os.makedirs(question_container_output_dir)
        except OSError:
            # the output dir already exists, no need to do anything
            pass

        question_subpart_output_dir = os.path.join(output_cabinet_path,
                                                   'questions',
                                                   'raw', common_path,
                                                   str(chapter.pk))

        try:
            os.makedirs(question_subpart_output_dir)
        except OSError:
            # the output dir already exists, no need to do anything
            pass

        for question in chapter_block['numbers']:
            print 'Processing data for question:', question
            is_removed = False
            if ('removed' in chapter_block) and (question
                                                 in chapter_block['removed']):
                print 'ALERT: This question is to be removed from the aql'
                is_removed = True

            question_container_data_file_path = os.path.join(
                question_container_data_file_path_stub,
                str(question) + DATA_FILE_EXT)

            with open(question_container_data_file_path, 'r') as f:
                question_container_data_raw = f.read().strip()

            question_container_data_raw = question_container_data_raw_process(
                question_container_data_raw)
            question_container_data = json.loads(question_container_data_raw)
            question_container_data = question_container_data_process(
                question_container_data)

            # question container data has subparts and tags (and other metadata which is to be carried over into cabinet)
            print 'Creating new question in db'
            new_question = Question(school=school,
                                    standard=standard,
                                    subject=subject,
                                    chapter=chapter)
            new_question.save()
            add_question_tags(new_question, question_container_data['tags'])

            reflect_subparts_in_db(new_question,
                                   question_container_data['subparts'])

            if not is_removed:  # still want to preserve the question in the question bank, just dont want to include it in the aql
                print "Adding newly created question to new AQL's question list"
                new_aql.questions.add(new_question)

            with open(
                    os.path.join(question_container_output_dir,
                                 str(new_question.pk) + DATA_FILE_EXT),
                    'w') as f:
                f.write(
                    dump_json_string(
                        get_question_container_data_for_cabinet(
                            question_container_data)))

            # now lets handle the subparts for this question
            subparts = question_container_data['subparts']
            for subpart in subparts:
                print 'Processing data for subpart:', subpart
                question_subpart_data_file_path = os.path.join(
                    question_subpart_data_file_path_stub,
                    str(subpart) + DATA_FILE_EXT)

                with open(question_subpart_data_file_path, 'r') as f:
                    question_subpart_data_raw = f.read().strip()

                question_subpart_data_raw = question_subpart_data_raw_process(
                    question_subpart_data_raw)
                question_subpart_data = json.loads(question_subpart_data_raw)
                question_subpart_data = question_subpart_data_process(
                    question_subpart_data)

                with open(
                        os.path.join(question_subpart_output_dir,
                                     str(subpart) + DATA_FILE_EXT), 'w') as f:
                    f.write(
                        dump_json_string(
                            get_question_subpart_data_for_cabinet(
                                question_subpart_data)))

        # finally, copy over the img folder too - and apply watermarks - do this at chapter level only to avoid repetition
        print 'Copying container images'
        copy_img_folder(question_container_data_file_path_stub,
                        question_container_output_dir)
        print 'Copying subpart images'
        copy_img_folder(question_subpart_data_file_path_stub,
                        question_subpart_output_dir)

    # now validate the number of the aql we just created in the db
    while True:
        try:
            check_duplicate_aql_identifiers(new_aql)
        except DuplicateAqlIdentifierError:
            new_aql.number += 1
            new_aql.save()
            continue

        print 'Settled on number %s for new aql' % new_aql.number
        break

    return new_aql.pk
示例#22
0
 def get(self, question_uuid):
     """
     GET handler
     """
     return Question.objects(uuid=question_uuid).first()
示例#23
0
 def get(self, course_uuid):
     """
     Retrieves the list of questions for the course
     """
     return list(Question.objects(course=course_uuid).all())
示例#24
0
    def test_simple_question_update(self):
        """
        Pass in a simple JSON file.
        """
        question_id = 123
        test_question = Question(id=question_id)
        test_question.save()
        related_options = Option.objects.filter(question=test_question)
        assert (len(related_options) == 3)

        user = User.objects.create(username='******')
        user.set_password('password')
        user.save()

        self.client = Client()
        logged_in = self.client.login(username='******', password='******')

        assert (logged_in)

        data = {
            "name":
            question_id,
            "correct":
            "option_content_2",
            "question_content": [
                {
                    "text": "This is a test question",
                    "inline": False
                },
            ],
            "option_content_1": [{
                "text": "option 1",
                "inline": False
            }],
            "option_content_2": [{
                "text": "option 2",
                "inline": False
            }],
            "option_content_3": [{
                "text": "option 3",
                "inline": False
            }],
            "additional_information": [],
            "answer_explanation_content": [
                {
                    "text": "This is the answer",
                    "inline": False
                },
            ]
        }

        response = self.client.post('/question_content/',
                                    json.dumps(data),
                                    content_type="application/json")
        assert (response.status_code == 200)
        question = Question.objects.get(id=123)
        assert (json.loads(
            question.question_content_json) == data["question_content"])
        assert (question.question_content == "<p>This is a test question</p>")
        assert (json.loads(
            question.answer_content_json) == data["answer_explanation_content"]
                )
        assert (question.answer_content == "<p>This is the answer</p>")
        # fetch the associated options
        options = Option.objects.filter(question=question)
        # assumes questions are created in the order that is created
        assert (len(options) == 3)
        assert (json.loads(
            options[0].content_json) == data["option_content_1"])
        assert (options[0].content == "<p>option 1</p>")
        assert (json.loads(
            options[1].content_json) == data["option_content_2"])
        assert (options[1].content == "<p>option 2</p>")
        assert (json.loads(
            options[2].content_json) == data["option_content_3"])
        assert (options[2].content == "<p>option 3</p>")

        new_data = {
            "name":
            question_id,
            "correct":
            "option_content_2",
            "question_content": [
                {
                    "text": "new question text",
                    "inline": False
                },
            ],
            "option_content_1": [{
                "text": "new option 1",
                "inline": False
            }],
            "option_content_2": [{
                "text": "new option 2",
                "inline": False
            }],
            "option_content_3": [{
                "text": "new option 3",
                "inline": False
            }],
            "additional_information": [],
            "answer_explanation_content": [
                {
                    "text": "new answer text",
                    "inline": False
                },
            ]
        }

        response = self.client.post('/question_content/',
                                    json.dumps(new_data),
                                    content_type="application/json")
        assert (response.status_code == 200)
        question = Question.objects.get(id=123)
        assert (json.loads(
            question.question_content_json) == new_data["question_content"])
        assert (question.question_content == "<p>new question text</p>")
        assert (json.loads(question.answer_content_json) ==
                new_data["answer_explanation_content"])
        assert (question.answer_content == "<p>new answer text</p>")
        # fetch the associated options
        options = Option.objects.filter(question=question)
        # assumes questions are created in the order that is created
        assert (len(options) == 3)
        assert (json.loads(
            options[0].content_json) == new_data["option_content_1"])
        assert (options[0].content == "<p>new option 1</p>")
        assert (json.loads(
            options[1].content_json) == new_data["option_content_2"])
        assert (options[1].content == "<p>new option 2</p>")
        assert (json.loads(
            options[2].content_json) == new_data["option_content_3"])
        assert (options[2].content == "<p>new option 3</p>")
示例#25
0
def create_question(header, score, evaluation):
    question = Question(question_text=header, score=score, evaluation=evaluation)
    question.save()
示例#26
0
    def handle(self, *args, **options):
        for current in options['tsv_file']:
            with open(current) as input_file:
                results = {}
                parser_state = ""
                current_question_id = 0
                for row in input_file.readlines():
                    row = row.strip()
                    tokens = row.split("\t")
                    if tokens[0] == "##" or tokens[0] == "":
                        continue
                    elif parser_state == "" and tokens[0] == "Quiz":
                        results["quiz"] = tokens[1]
                        parser_state = "parsed_quiz"
                    elif parser_state == "parsed_quiz" and tokens[0] == "Timed":
                        results["timed"] = tokens[1]
                        parser_state = "parsed_timed"
                    elif parser_state == "parsed_timed" and tokens[
                            0] == "Max Time In Mins":
                        results["max_time_in_mins"] = tokens[1]
                        parser_state = "parsed_max_time"
                    elif parser_state == "parsed_max_time" and tokens[
                            0] == "Quiz Structure":
                        parser_state = "parse_quiz_structure"
                    elif parser_state == "parse_quiz_structure":
                        if "quiz_structure" not in results:
                            results["quiz_structure"] = []
                        # change state to parsing question bank
                        if tokens[0] == "Category":
                            parser_state = "parse_qb"
                            continue

                        # update quiz structure
                        current_qs = {}
                        k, v = tokens
                        current_qs[k] = int(v)
                        results["quiz_structure"].append(current_qs)
                    elif parser_state == "parse_qb":
                        # it is a question line
                        if len(tokens) > 2:
                            category, sub_category, question_type, point, question, choice = tokens[:
                                                                                                    6]

                            correct = ""
                            if len(tokens) > 6 and tokens[6] != "":
                                correct = tokens[6]

                            if "questions" not in results:
                                results["questions"] = {}
                            results["questions"][current_question_id] = {}
                            results["questions"][current_question_id][
                                "category"] = category
                            results["questions"][current_question_id][
                                "sub_category"] = sub_category
                            results["questions"][current_question_id][
                                "question_type"] = question_type
                            results["questions"][current_question_id][
                                "point"] = point
                            results["questions"][current_question_id][
                                "question"] = question
                            results["questions"][current_question_id][
                                "choices"] = []
                            current_choice = {}
                            current_choice["caption"] = choice
                            if correct == "Y":
                                current_choice["correct"] = True
                            else:
                                current_choice["correct"] = False
                            results["questions"][current_question_id][
                                "choices"].append(current_choice)
                            current_question_id += 1
                        else:
                            # append to choices
                            current_choice = {}
                            current_choice["caption"] = tokens[0]
                            if len(tokens) > 1 and tokens[1] == "Y":
                                current_choice["correct"] = True
                            else:
                                current_choice["correct"] = False
                            results["questions"][current_question_id -
                                                 1]["choices"].append(
                                                     current_choice)
                    else:
                        print(f"At {parser_state}: Cannot parse {row}")

                if self.DEBUG:
                    print("Parsed:")
                    print(json.dumps(results, indent=1))

                uniq_categories = []

                for current in results['questions']:
                    current_category = results['questions'][current][
                        'category']
                    if current_category not in uniq_categories:
                        uniq_categories.append(current_category)

                # create categories
                for current in uniq_categories:
                    if not Category.objects.filter(name=current).exists():
                        category = Category()
                        category.name = current
                        category.save()

                # create sub-categories
                for current in results['questions']:
                    current_category = results['questions'][current][
                        "category"]
                    category = Category.objects.get(name=current_category)
                    current_sub_category = results['questions'][current][
                        "sub_category"]
                    if not SubCategory.objects.filter(
                            name=current_sub_category).exists():
                        sub_category = SubCategory()
                        sub_category.category = category
                        sub_category.name = current_sub_category
                        sub_category.save()

                # create quiz
                quiz = None
                if Quiz.objects.filter(name=results["quiz"]).exists():
                    raise CommandError(
                        f"Quiz {results['quiz']} already exists")
                else:
                    quiz = Quiz()
                    quiz.name = results['quiz']
                    quiz.category = Category.objects.get(
                        name=uniq_categories[0])
                    quiz.sub_category = SubCategory.objects.filter(
                        category=quiz.category).first()
                    if results['timed'] == "Y":
                        quiz.timed = True
                    else:
                        quiz.timed = False
                    quiz.time_limit = int(results['max_time_in_mins'])
                    quiz.save()

                # create quiz structure
                for current in results['quiz_structure']:
                    quiz_structure = QuizStructure()
                    quiz_structure.quiz = quiz
                    quiz_structure.category = Category.objects.get(
                        name=uniq_categories[0])
                    sub_category, frequency = list(current.keys())[0], list(
                        current.values())[0]
                    quiz_structure.sub_category = SubCategory.objects.get(
                        name=sub_category, category=quiz_structure.category)
                    quiz_structure.frequency = frequency
                    quiz_structure.save()

                # create question type
                for current in results['questions']:
                    current_question_type = results['questions'][current][
                        "question_type"]
                    if not QuestionType.objects.filter(
                            name=current_question_type).exists():
                        question_type = QuestionType()
                        question_type.name = current_question_type
                        question_type.save()

                # create question & choices
                for current in results['questions']:
                    question = Question()
                    question.category = Category.objects.get(
                        name=results['questions'][current]["category"])
                    question.sub_category = SubCategory.objects.get(
                        name=results['questions'][current]["sub_category"],
                        category=category)
                    question.question_type = QuestionType.objects.get(
                        name=results['questions'][current]["question_type"])
                    question.point = results['questions'][current]["point"]
                    question.blurb = results['questions'][current]["question"]
                    question.save()

                    for current_choice in results['questions'][current][
                            "choices"]:
                        choice = Choice()
                        choice.question = question
                        choice.choice = current_choice['caption']
                        choice.correct = current_choice['correct']
                        choice.save()
示例#27
0
    def test_question_check_answer(self):
        q = Question()
        q['correct'] = u'Yes'
        self.assertTrue(q.check_answer('yes'))
        self.assertTrue(not q.check_answer('no'))

        q['alternatives'] = [u'Maybe', u'Perhaps']
        self.assertTrue(q.check_answer('yes', alternatives_are_correct=True))
        self.assertTrue(q.check_answer('maybe', alternatives_are_correct=True))
        self.assertTrue(
            q.check_answer('perhaps', alternatives_are_correct=True))
        self.assertTrue(
            not q.check_answer('inte', alternatives_are_correct=True))

        # now with edit distance
        # too short
        self.assertTrue(not q.check_answer('yeah'))
        # sufficiently long
        q['correct'] = u'Correct'
        self.assertTrue(q.check_answer('corect'))
        self.assertTrue(not q.check_answer('korecct'))

        q['correct'] = u'Tupac Shakur'
        self.assertTrue(q.check_answer('tupak Shacur'))
        self.assertTrue(not q.check_answer('Toopack shakure'))  # too wrong
示例#28
0
    def handle(self, *args, **options):
        print 'Reset db started.'

        Entity.objects.all().delete()
        Question.objects.all().delete()
        print 'db clear done.'

        print 'Loading books...'
        books_list = {}
        with open(BOOKS_FILE, 'r') as f:
            b_reader = csv.DictReader(f, delimiter=',')
            for book in b_reader:
                pk = int(book['id_b'])
                name = book['name'].decode('utf8')
                description = ''

                db_book = Entity(name=name, description=description)
                db_book.save()

                books_list[pk] = db_book

        print 'Done.'

        print 'Loading questions...'
        questions_list = {}
        with open(QUESTIONS_FILE, 'rb') as f:
            q_reader = csv.DictReader(f, delimiter=',')
            for question in q_reader:
                pk = int(question['id_q'])
                text = question['question'].decode('utf8')

                db_question = Question(text=text)
                db_question.save()

                questions_list[pk] = db_question

        print 'Done.'

        print 'Loading distributions...'
        with open(DISTRIBUTION_FILE, 'rb') as f:
            d_reader = csv.DictReader(f, delimiter=',')
            for distribution in d_reader:
                book_id = int(distribution['id_b'])
                question_id = int(distribution['id_q'])

                yes_count = int(
                    float(distribution['yes'].replace(',', '.')) * 100)
                no_count = int(
                    float(distribution['no'].replace(',', '.')) * 100)
                dm_count = int(
                    float(distribution['does not matter'].replace(',', '.')) *
                    100)

                book = books_list[book_id]
                question = questions_list[question_id]

                db_distribution = AnswersDistribution(entity=book,
                                                      question=question,
                                                      yes_count=yes_count,
                                                      no_count=no_count,
                                                      dm_count=dm_count)
                db_distribution.save()

        print 'Done.'
示例#29
0
 def test_was_published_recently_with_future_question(self):
     time = timezone.now() + datetime.timedelta(days=30)
     future_question = Question(pub_date=time)
     self.assertIs(future_question.was_published_recently(), False)
示例#30
0
 def test_was_published_recently_with_recent_question(self):
     time = timezone.now() - datetime.timedelta(
         hours=23, minutes=59, seconds=29)
     recent_question = Question(pub_date=time)
     self.assertIs(recent_question.was_published_recently(), True)