def get(self, request, format=None): if not 'token' in request.GET: return Response(status=status.HTTP_404_NOT_FOUND) student = get_student(request.GET['token']) quiz = Quiz(subject='subtraction') quiz.save() scores = Score.objects.all().filter(subject='subtraction', student=student) avg = 0 if len(scores) > 2: for score in scores: avg = avg + score.value avg = avg / len(scores) if avg <= num_questions / 3.0: low_x = 3 low_y = 1 high = 9 elif avg <= (2 * num_questions) / 3.0: low_x = 5 low_y = 3 high = 20 else: low_x = 15 low_y = 11 high = 99 for i in range(num_questions): x = random.randint(low_x, high) y = random.randint(low_y, x - 1) answer = x - y text = str(x) + ' ' + str(y) explanation = str(x) + ' - ' + str(y) + ' is equal to ' + str(answer) question = Question(text=text, answer=str(answer), explanation=explanation, quiz=quiz) question.save() quiz.save() serializer = QuizSerializer(quiz) return Response(serializer.data)
def get(self, request, format=None): if not 'token' in request.GET: return Response(status=status.HTTP_404_NOT_FOUND) student = get_student(request.GET['token']) quiz = Quiz(subject='division') quiz.save() scores = Score.objects.all().filter(subject='division', student=student) avg = 0 if len(scores) > 2: for score in scores: avg = avg + score.value avg = avg / len(scores) if avg <= num_questions / 3.0: low = 1 high = 4 elif avg <= (2 * num_questions) / 3.0: low = 3 high = 7 else: low = 6 high = 12 for i in range(num_questions): y = random.randint(low, high) answer = random.randint(low, high) x = y * answer text = str(x) + ' ' + str(y) explanation = str(x) + ' divided by ' + str(y) + ' is equal to ' + str(answer) question = Question(text=text, answer=str(answer), explanation=explanation, quiz=quiz) question.save() quiz.save() serializer = QuizSerializer(quiz) return Response(serializer.data)
def create(self, request): data = request.data print('data >> ', data) assignment = Assignment() teacher = User.objects.get(username=data['teacher']) assignment.teacher = teacher assignment.title = data['title'] assignment.save() order = 1 for q in data['questions']: newQ = Question() newQ.question = q['title'] newQ.order = order newQ.save() for c in q['choices']: newC = Choice() newC.title = c newC.save() newQ.choices.add(newC) newQ.answer = Choice.objects.get(title=q['answer']) newQ.assignment = assignment newQ.save() order += 1 return assignment
def create_likert(text): """ Inserts a likert question with text Parameters ---------- text : string text for the question. """ Question.create_question(q_type=QuestionType.likert, text=text)
def create_likert(text, link_audio): """ Inserts a likert question with text and audio Parameters ---------- text : string text for the question. """ Question.create_question(q_type=QuestionType.likert, text=text, audio=link_audio)
def get(self, request, format=None): if not 'token' in request.GET: return Response(status=status.HTTP_404_NOT_FOUND) student = get_student(request.GET['token']) quiz = Quiz(subject='fractions') quiz.save() scores = Score.objects.all().filter(subject='fractions', student=student) avg = 0 if len(scores) > 2: for score in scores: avg = avg + score.value avg = avg / len(scores) if avg <= num_questions / 3.0: low_mult = 2 high_mult = 3 low_num = 1 high_num = 3 high_denom = 6 elif avg <= (2 * num_questions) / 3.0: low_mult = 3 high_mult = 5 low_num = 1 high_num = 4 high_denom = 8 else: low_mult = 6 high_mult = 9 low_num = 1 high_num = 5 high_denom = 10 for i in range(num_questions): multiplier = random.randint(low_mult, high_mult) numerator = random.randint(low_num, high_num) denom = random.randint(numerator + 1, high_denom) ans_denom = denom * multiplier answer = numerator * multiplier text = str(numerator) + ' ' + str(denom) + ' ' + str(ans_denom) explanation = 'The correct answer is ' + str( answer) + ' because ' + str(numerator) + '/' + str( denom) + ' times ' + str(multiplier) + '/' + str( multiplier) + ' is ' + str(answer) + '/' + str( ans_denom) question = Question(text=text, answer=str(answer), explanation=explanation, quiz=quiz) question.save() quiz.save() serializer = QuizSerializer(quiz) return Response(serializer.data)
def create_new_phase(self, phase): """ Creates a new phase with the specified categories. It will take all images with the categories and add them to the question :param phase: The left and right categories in an object :return: A newly created question """ images = Image.query.filter( or_(Image.category_id.in_(phase['left_categ']), Image.category_id.in_((phase['right_categ'])))).all() question = Question(text="", q_type=QuestionType.binary, images=images) add_to_db(question) for c_left in phase['left_categ']: q_to_c = Question_to_category(q_id=question.id, c_id=c_left, is_left=True) add_to_db(q_to_c) for c_right in phase['right_categ']: q_to_c = Question_to_category(q_id=question.id, c_id=c_right, is_left=False) add_to_db(q_to_c) return question
async def get(self): code = 200 page_num = int(self.request.query.get('page', '1')) logger.debug(f'Request: {self.request.url}') # A single object if self.pk: try: question = await Question.get_by(self.pk) result = self._format_obj(question) except Question.DoesNotExist: code = 404 logger.debug(f'Object was not found by id {self.pk}') result = { 'id': self.pk, 'error_message': 'Object is not found by "id"' } # List of objects else: result = [] questions = await Question.objects().execute( Question.select().order_by(Question.pub_date.desc()).paginate( page_num, settings.API_ITEMS_PER_PAGE)) for question in questions: result.append(self._format_obj(question)) logger.debug(f'Result: {result}') return web.json_response(result, status=code)
def add_question(): """ Function enables user to create a question by first checking if they have entered an empty string and returns an error message in that case. If not, it creates a question with the information from the json object and adds the question to a list of qeustions called 'questions' and returns a success message wuth the question that has been created. """ data = request.get_json() questionId = len(questions) questionId += 1 details = data.get('details') if not details or details.isspace(): return jsonify({"message": "Sorry, you didn't enter any question!"}), 400 question = Question(questionId, details) questions.append(question) return jsonify({ "id": questionId, "question": question.__dict__, "message": "Question added successfully!" }), 201
def save_question(question, answer, detractors): operator = get_math_operation(question) has_negative_values = check_for_negative_values(answer, *detractors) q = Question(text=question, operation_type=operator, has_negative_values=has_negative_values) q.save() all_answers = [] a = Answer(text=answer, is_correct_answer=True) a.save() all_answers.append(a) for d in detractors: a = Answer(text=d, is_correct_answer=False) a.save() all_answers.append(a) q.answers.add(*all_answers)
def add_question(request, user_id): mentee = Mentee.objects.get(id=user_id) question = Question() question.author = mentee question.title = request.data['title'] question.description = request.data['description'] question.language = request.data['language'] question.save() return Response(QuestionSerializer(question).data, status=status.HTTP_201_CREATED)
def get(self, request, format=None): if not 'token' in request.GET: return Response(status=status.HTTP_404_NOT_FOUND) student = get_student(request.GET['token']) quiz = Quiz(subject='fractions') quiz.save() scores = Score.objects.all().filter(subject='fractions', student=student) avg = 0 if len(scores) > 2: for score in scores: avg = avg + score.value avg = avg / len(scores) if avg <= num_questions / 3.0: low_mult = 2 high_mult = 3 low_num = 1 high_num = 3 high_denom = 6 elif avg <= (2 * num_questions) / 3.0: low_mult = 3 high_mult = 5 low_num = 1 high_num = 4 high_denom = 8 else: low_mult = 6 high_mult = 9 low_num = 1 high_num = 5 high_denom = 10 for i in range(num_questions): multiplier = random.randint(low_mult, high_mult) numerator = random.randint(low_num, high_num) denom = random.randint(numerator + 1, high_denom) ans_denom = denom * multiplier answer = numerator * multiplier text = str(numerator) + ' ' + str(denom) + ' ' + str(ans_denom) explanation = 'The correct answer is ' + str(answer) + ' because ' + str(numerator) + '/' + str(denom) + ' times ' + str(multiplier) + '/' + str(multiplier) + ' is ' + str(answer) + '/' + str(ans_denom) question = Question(text=text, answer=str(answer), explanation=explanation, quiz=quiz) question.save() quiz.save() serializer = QuizSerializer(quiz) return Response(serializer.data)
def get(self, question_id): answers = Question.get_or_404(question_id).answers answer_schema = AnswerSchema(many=True, only=["id", "title", "answerer"]) return jsonify({ "data": answer_schema.dump(answers).data, "status": "success", "message": SUCCESS_MESSAGES["fetched"].format("Answers") })
def delete(self, question_id): question = Question.get_or_404(question_id) question.delete() return jsonify({ "status": "success", "message": SUCCESS_MESSAGES["deleted"].format("Question") })
def post(self): request_data = request.get_json() user = User.query.first() question_schema = QuestionSchema( only=["id", "title", "created_at", "updated_at"]) question_data = question_schema.load_object_into_schema(request_data) question_data["questioner"] = user question = Question(**question_data) question.save() return jsonify({ "data": question_schema.dump(question).data, "status": "success", "message": SUCCESS_MESSAGES["created"].format("Question") })
def get(self, question_id): question = Question.get_or_404(question_id) question_schema = QuestionSchema(only=["title"]) return jsonify({ "data": question_schema.dump_object_into_schema(question), "status": "success", "message": SUCCESS_MESSAGES["fetched"].format("Question") })
def post(self, request, room_number): request.session.save() json = JSONParser().parse(request) room = get_or_none(Room, number=room_number) if room: question = Question(room=room, title=json['title'], balance=0) question.save() Group('room-%s' % question.room.number).send({ 'text': dumps({ 'type': 'question', 'action': 'create', 'data': QuestionSerializer(question).data }) }) return Response(QuestionSerializer(question).data, status=201) else: return Response({"error": "no room " + room_number + " found"}, status=404)
def get(self, request, format=None): if not 'token' in request.GET: return Response(status=status.HTTP_404_NOT_FOUND) student = get_student(request.GET['token']) quiz = Quiz(subject='subtraction') quiz.save() scores = Score.objects.all().filter(subject='subtraction', student=student) avg = 0 if len(scores) > 2: for score in scores: avg = avg + score.value avg = avg / len(scores) if avg <= num_questions / 3.0: low_x = 3 low_y = 1 high = 9 elif avg <= (2 * num_questions) / 3.0: low_x = 5 low_y = 3 high = 20 else: low_x = 15 low_y = 11 high = 99 for i in range(num_questions): x = random.randint(low_x, high) y = random.randint(low_y, x - 1) answer = x - y text = str(x) + ' ' + str(y) explanation = str(x) + ' - ' + str(y) + ' is equal to ' + str( answer) question = Question(text=text, answer=str(answer), explanation=explanation, quiz=quiz) question.save() quiz.save() serializer = QuizSerializer(quiz) return Response(serializer.data)
def PostQuestion(request): """!@brief Function which is called when a user adds a question @details the function takes a question object as part of the request body, extracts the object and then creates a new entry in the question table. Since the topics is a many-to-many field, the topics need to be added one by one @return returns the feed output for the given user """ serializer = QuestionSerializer(data=request.data) if serializer.is_valid(): ques = serializer.validated_data user = ques['user'] question = Question(user=user, username=user.name, userdepartment=user.department, userbio=user.bio, userdegree=user.degree, userspecialization=user.specialization, question=ques['question'], description=ques['description']) question.save() for topic in ques['topics']: question.topics.add(topic) return Feed(user.id) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def get(self, request, format=None): if not 'token' in request.GET: return Response(status=status.HTTP_404_NOT_FOUND) student = get_student(request.GET['token']) quiz = Quiz(subject='division') quiz.save() scores = Score.objects.all().filter(subject='division', student=student) avg = 0 if len(scores) > 2: for score in scores: avg = avg + score.value avg = avg / len(scores) if avg <= num_questions / 3.0: low = 1 high = 4 elif avg <= (2 * num_questions) / 3.0: low = 3 high = 7 else: low = 6 high = 12 for i in range(num_questions): y = random.randint(low, high) answer = random.randint(low, high) x = y * answer text = str(x) + ' ' + str(y) explanation = str(x) + ' divided by ' + str( y) + ' is equal to ' + str(answer) question = Question(text=text, answer=str(answer), explanation=explanation, quiz=quiz) question.save() quiz.save() serializer = QuizSerializer(quiz) return Response(serializer.data)
async def delete(self): logger.debug(f'Removing a question: id - {self.pk}') n = await Question.objects().execute( Question.delete().where(Question.id == self.pk)) if not n: logger.debug(f'Object was not found by id {self.pk}') result = { 'id': self.pk, 'error_message': 'Object is not found by "id"' } return web.json_response(result, status=404) return web.json_response(status=202)
def create_question(self, classroom_uuid, content): question_uuid = uuid.uuid1() school_uuid = self.classroom_helper.get_school_uuid_by_classroom_uuid( classroom_uuid) Question(uuid=question_uuid, classroom_uuid=classroom_uuid, school_uuid=school_uuid, creator=self.user_id, role=self.role, anonymous=self.anonymous, active=True, answer_count=0, content=content, created_timestamp=self.timestamp_now, updated_timestamp=self.timestamp_now).save()
def question_create(request): """ Create a one question. """ user = request.user question = Question(author=user) if request.method == 'POST': serializer = QuestionSerializer(question, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) else: return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)
def post(self, question_id): request_data = request.get_json() user = User.query.get("16") question = Question.get_or_404(question_id) answer_schema = AnswerSchema( only=["id", "title", "created_at", "updated_at", "parent_id"]) answer_data = answer_schema.load_object_into_schema(request_data) answer_data["answerer"] = user answer_data["answer"] = question answer_data["parent_id"] = 12 answer = Answer(**answer_data) answer.save() return jsonify({ "data": answer_schema.dump_object_into_schema(answer), "status": "success", "message": SUCCESS_MESSAGES["created"].format("Answer") })
def put(self, question_id): request_data = request.get_json() question = Question.get_or_404(question_id) question_schema = QuestionSchema(only=["title"]) question_data = question_schema.load_object_into_schema(request_data) print(request_data.get('title')) question = question.update(question_data) question.save() return jsonify({ "data": question_schema.dump_object_into_schema(question), "status": "success", "message": SUCCESS_MESSAGES["updated"].format("Question") })
def create(self, validated_data): question_tags = validated_data.pop('tags', None) question = Question(**validated_data) question.author = self.context['request'].user question.save() for request_tag in question_tags: tag_name = request_tag.get('name') if not Tag.objects.filter(name=tag_name).exists(): tag = create_tag(request_tag) else: tag = Tag.objects.filter(name=tag_name)[0] qt = QuestionTag.objects.create( question=question, tag=tag, ) qt.save() question.save() return question
async def random_questions(request, random_users: Tuple[List[User], List[Dict]]): async def fin(): async with in_transaction() as connection: for question in questions_db: await question.delete(using_db=connection) faker = Faker() questions = [] questions_db = [] request.addfinalizer(fin) users_db, users = random_users async with in_transaction() as connection: for user in users_db: question_data = QuestionInput(faker.paragraph(), user.id) question = Question(**asdict(question_data)) await question.save(using_db=connection) questions_db.append(question) questions.append(asdict(question_data)) yield questions
def question(request): if request.method == 'GET': name = request.GET.get('name' , request.GET.get('name',None)) title = request.GET.get('title' , request.GET.get('title',None)) content = request.GET.get('content' , request.GET.get('content',None)) replys = request.GET.get('replys' , request.GET.get('replys',None)) times = request.GET.get('times' , request.GET.get('times',None)) questions = Question.objects.all() if name: questions = questions.filter(name=name) if title: questions = questions.filter(title=title) if content: questions = question.filter(content=content) if replys: questions = question.filter(replys=replys) serializer = QuestionSerializer(questions, many=True) return Response(data=serializer.data, status=status.HTTP_200_OK) if request.method == 'POST': ques = request.data["params"] name = ques["name"] title = ques["title"] content = ques["content"] replys = ques["replys"] times = datetime.datetime.now().date() + datetime.timedelta(days=31) Question(name = name, title = title, content = content , replys=replys , times=times).save() return Response(data=status.HTTP_201_CREATED)
def get(self, request, format=None): if not 'token' in request.GET: return Response(status=status.HTTP_404_NOT_FOUND) student = get_student(request.GET['token']) quiz = Quiz(subject='geometry') quiz.save() scores = Score.objects.all().filter(subject='geometry', student=student) avg = 0 for i in range(num_questions): area = random.choice(['Area', 'Perimeter']) if len(scores) > 2: for score in scores: avg = avg + score.value avg = avg / len(scores) if avg <= num_questions / 3.0: shape = 'Square' low = 2 high = 5 elif avg <= (2 * num_questions) / 3.0: shape = random.choice(['Square', 'Rectangle']) low = 3 high = 9 else: shape = random.choice(['Square', 'Rectangle', 'Triangle']) low = 6 high = 20 val = '' if shape == 'Square': x = random.randint(low, high) if area == 'Area': answer = x * x elif area == 'Perimeter': answer = 4 * x val = str(x) elif shape == 'Rectangle': x = random.randint(low, high) y = random.randint(low, high) while y == x: y == random.randint(low, high) if area == 'Area': answer = x * y elif area == 'Perimeter': answer = 2 * (x + y) if y > x: val = str(x) + ' ' + str(y) else: val = str(y) + ' ' + str(x) elif shape == 'Triangle': x = random.randint(low, high) if x % 2 == 1: if not x == high: x = x + 1 else: x = x - 1 y = random.randint(low, high) while y == x: y == random.randint(low, high) if area == 'Area': answer = (x * y) / 2 if y > x: val = str(x) + ' ' + str(y) else: val = str(y) + ' ' + str(x) elif area == 'Perimeter': pythag = random.choice([[3, 4, 5], [5, 12, 13], [8, 15, 17], [7, 24, 25], [9, 40, 41], [11, 60, 61], [12, 35, 37], [16, 63, 65], [20, 21, 29]]) answer = pythag[0] + pythag[1] + pythag[2] val = str(pythag[0]) + ' ' + str(pythag[1]) + ' ' + str(pythag[2]) text = shape + ' ' + area + ' ' + val explanation = 'blank on purpose' question = Question(text=text, answer=str(answer), explanation=explanation, quiz=quiz) question.save() quiz.save() serializer = QuizSerializer(quiz) return Response(serializer.data)
def populate(): """Method that populates the databse with data""" db.session.close() db.drop_all() db.create_all() User.create_user("admin", "admin") c_male = Category.create_category(name="Jongen", metacategory=Metacategory.gender) c_female = Category.create_category(name="Meisje", metacategory=Metacategory.gender) c_programmer = Category.create_category( name="Programmeur", metacategory=Metacategory.profession) c_writer = Category.create_category(name="Schrijver", metacategory=Metacategory.profession) c_alone = Category.create_category(name="Alleen", metacategory=Metacategory.social) c_together = Category.create_category(name="Samen", metacategory=Metacategory.social) c_gaming = Category.create_category(name="Gamen", metacategory=Metacategory.hobby) c_tennis = Category.create_category(name="Tennis", metacategory=Metacategory.hobby) male_images = [ 'https://res.cloudinary.com/hctr0xmqp/image/upload/v1591276420/Gender/gender_male_1_dh1pbq.png', 'https://res.cloudinary.com/hctr0xmqp/image/upload/v1591276420/Gender/gender_male_2_bsbqc9.png', 'https://res.cloudinary.com/hctr0xmqp/image/upload/v1591276421/Gender/gender_male_3_eknmuv.png', 'https://res.cloudinary.com/hctr0xmqp/image/upload/v1591276421/Gender/gender_male_4_d1clch.png' ] female_images = [ 'https://res.cloudinary.com/hctr0xmqp/image/upload/v1591276422/Gender/gender_female_1_nph1ga.png', 'https://res.cloudinary.com/hctr0xmqp/image/upload/v1591276420/Gender/gender_female_2_fjfxrv.png', 'https://res.cloudinary.com/hctr0xmqp/image/upload/v1591276420/Gender/gender_female_3_erg7nd.png', 'https://res.cloudinary.com/hctr0xmqp/image/upload/v1591276420/Gender/gender_female_4_b0vc8l.png' ] programmer_images = [ ("https://res.cloudinary.com/hctr0xmqp/image/upload/v1591276505/Profession/profession_programmer_1_c6pvby.png", "App"), ("https://res.cloudinary.com/hctr0xmqp/image/upload/v1591276504/Profession/profession_programmer_2_rbcfov.png", "Laptop"), ("https://res.cloudinary.com/hctr0xmqp/image/upload/v1591276504/Profession/profession_programmer_3_cjwqsw.png", "Keyboard"), ("https://res.cloudinary.com/hctr0xmqp/image/upload/v1591276504/Profession/profession_programmer_4_xbviey.png", "Website") ] writer_images = [ ("https://res.cloudinary.com/hctr0xmqp/image/upload/v1591276504/Profession/profession_writer_1_o8xzue.png", "Newspaper"), ("https://res.cloudinary.com/hctr0xmqp/image/upload/v1591276504/Profession/profession_writer_2_mmpdnx.png", "Papers"), ("https://res.cloudinary.com/hctr0xmqp/image/upload/v1591276505/Profession/profession_writer_3_qyl8aq.png", "Pen"), ("https://res.cloudinary.com/hctr0xmqp/image/upload/v1591276505/Profession/profession_writer_4_tbvw0b.png", "Book") ] gaming_images = [ ("https://res.cloudinary.com/hctr0xmqp/image/upload/v1591276493/Hobby/hobby_gaming_1_tlfl07.png", "Game Controller"), ("https://res.cloudinary.com/hctr0xmqp/image/upload/v1591276493/Hobby/hobby_gaming_2_ruribs.png", "Game Controller"), ("https://res.cloudinary.com/hctr0xmqp/image/upload/v1591276493/Hobby/hobby_gaming_3_hvkfme.png", "Game Controller"), ("https://res.cloudinary.com/hctr0xmqp/image/upload/v1591276493/Hobby/hobby_gaming_4_cb1doe.png", "Game Controller") ] tenis_images = [ ("https://res.cloudinary.com/hctr0xmqp/image/upload/v1591276495/Hobby/hobby_tennis_1_ei7yic.png", "Net"), ("https://res.cloudinary.com/hctr0xmqp/image/upload/v1591276493/Hobby/hobby_tennis_2_qx7tms.png", "Racket"), ("https://res.cloudinary.com/hctr0xmqp/image/upload/v1591276493/Hobby/hobby_tennis_3_pdsnou.png", "Shoe"), ("https://res.cloudinary.com/hctr0xmqp/image/upload/v1591276493/Hobby/hobby_tennis_4_v5yam2.png", "Ball") ] alone_images = [ ("https://res.cloudinary.com/hctr0xmqp/image/upload/v1591276518/Social/social_alone_1_wy8rpb.png", "Alone"), ("https://res.cloudinary.com/hctr0xmqp/image/upload/v1591276516/Social/social_alone_2_vy3tmr.png", "Alone"), ("https://res.cloudinary.com/hctr0xmqp/image/upload/v1591276518/Social/social_alone_3_ygnsbz.png", "Alone"), ("https://res.cloudinary.com/hctr0xmqp/image/upload/v1591276517/Social/social_alone_4_ppasf1.png", "Alone") ] together_images = [ ("https://res.cloudinary.com/hctr0xmqp/image/upload/v1591276518/Social/social_together_1_eumalw.png", "Together"), ("https://res.cloudinary.com/hctr0xmqp/image/upload/v1591276517/Social/social_together_2_ketyo1.png", "Together"), ("https://res.cloudinary.com/hctr0xmqp/image/upload/v1591276517/Social/social_together_3_s4wzba.png", "Together"), ("https://res.cloudinary.com/hctr0xmqp/image/upload/v1591276517/Social/social_together_4_ea2yka.png", "Together") ] for link in male_images: Image.create_image(link=link, description="Man", attribute='man standing', c_id=c_male.id) for link in female_images: Image.create_image(link=link, description='Girl', attribute='girl standing', c_id=c_female.id) create_images(programmer_images, c_programmer.id) create_images(writer_images, c_writer.id) create_images(gaming_images, c_gaming.id) create_images(tenis_images, c_tennis.id) create_images(alone_images, c_alone.id) create_images(together_images, c_together.id) # likert create_likert( "Ik ben sociaal. " "Als je sociaal bent maak je makkelijk vrienden en werk je graag samen" ) create_likert("Ik ben graag de beste") create_likert("Ik ben gek op computers") create_likert("Ik wil later programmeur worden") create_likert( "Programmeurs zijn sociaal. " "Als je sociaal bent maak je makkelijk vrienden en werk je graag samen" ) create_likert("Programmeurs houden ervan om de beste te zijn") create_likert( "Programmeurs zijn gek op computers en hebben weinig andere hobby’s") create_likert("Programmeur zijn, dat is een beroep voor mannen") create_likert("Programmeur zijn, dat is een beroep voor vrouwen") create_likert( "Schrijvers zijn sociaal. " "Als je sociaal bent maak je makkelijk vrienden en werk je graag samen" ) create_likert("Schrijvers houden ervan om de beste te zijn") create_likert( "Schrijvers zijn gek op computers en hebben weinig andere hobby’s") create_likert("Schrijver zijn, dat is een beroep voor mannen") create_likert("Schrijver zijn, dat is een beroep voor vrouwen") Question.create_question(q_type=QuestionType.open_question, text="Wat doet een programmeur?") video_female = Image.create_image(link="173d_-zTd1o", description='Role model intervention', attribute='Female') video_male = Image.create_image(link="hEMOMVZbSBE", description='Role model intervention', attribute='Male') # video_question Question.create_question(q_type=QuestionType.video, images=[video_female]) mc_1 = Question.create_question(q_type=QuestionType.mc_single_answer, text="Hoe oud ben je?", information=ParticipantInformationType.age) for i in range(6, 19): QuestionChoice.create_choice(choice_num=i - 5, q_id=mc_1.id, text=str(i)) QuestionChoice.create_choice(choice_num=14, q_id=mc_1.id, text="Anders") mc_2 = Question.create_question( q_type=QuestionType.mc_multiple_answer, text="Wat is jouw achtergrond? Er zijn meerdere antwoorden mogelijk.", information=ParticipantInformationType.ethnicity) for i, ethnicity in enumerate(Ethnicity.__iter__(), 1): QuestionChoice.create_choice(choice_num=i, q_id=mc_2.id, text=ethnicity.value) mc_3 = Question.create_question( q_type=QuestionType.mc_single_answer, text="Ik voel me een ...", information=ParticipantInformationType.gender) for i, gender in enumerate(Gender.__iter__(), 1): QuestionChoice.create_choice(choice_num=i, q_id=mc_3.id, text=gender.value) Question.create_question( q_type=QuestionType.notes, text="Researcher notes", information=ParticipantInformationType.researcher_notes) # video_question Question.create_question(q_type=QuestionType.video, images=[video_male])
def submit_interaction(self): """ Submit interaction stores the given submission provided by the user. Submission can be answer to a particular variable or selection of a facet. """ getRequest = self.request.GET if self.QUESTION_PARAM_KEY in getRequest: question_id = getRequest[self.QUESTION_PARAM_KEY] variables = {} facets = {} has_submission = False # Old submission will be stored incase we need to undo old_submission = Question.get_submissions_for(self.user.visitor_id, question_id) old_submission = old_submission[0].to_json() if len(old_submission) == 1 else None if self.VARIABLE_PARAM_KEY in getRequest: variables = self.__get_name_value_from_string(getRequest[self.VARIABLE_PARAM_KEY]) has_submission = True # a user could have submitted either a variable's value or facets if self.FACETS_PARAM_KEY in getRequest: facets = self.__get_name_value_from_string(self.request.GET[self.FACETS_PARAM_KEY]) has_submission = True # there is no point saving if nothing has been submitted or selected if has_submission: self.user.save_submission(question_id, variables, facets) self._push_interaction(self.Interactions.SUBMIT, {self.QUESTION_PARAM_KEY: question_id, 'submission': old_submission}) answered_variables = self.user.get_answered_variables() selected_facets = self.user.get_selected_facets() # TODO: Code Refactor, too many duplicates, move code Question and Item Query block to a common method self.response = SlapResponse(visitor = self.user) item_id = None if self.CHALLENGE_PARAM_KEY in getRequest: challenge_id = getRequest[self.CHALLENGE_PARAM_KEY] (success, challenge_id) = self.__parse_int(challenge_id) if success: item_id = challenge_id if item_id is not None: items = SolrQuery(query_type = SolrQuery.CHALLENGE_QUERY, query_params = {'rows' : 1, 'id' : str(item_id), 'businessmodel' : '*'}).query() answered_variables = self.user.get_answered_variables() ItemTransformer(items = items).transform(answered_variables = answered_variables) self.response.set_items(items) # c & d. query the database for question with the missing variables # query the database for question with default variables # since we are selecting only one item we can select the variables with missing and default value for it variables_lists = [items[0]['missingVariables'], items[0]['defaultsOnly']] questions = [] for missing_vars in variables_lists: query_params = {} if len(missing_vars) > 0: for var in missing_vars: var = '&' + var query_params['variables'] = Filter(missing_vars) questions.extend(SolrQuery(query_params = query_params).query()) if len(questions) > 1: questions = questions[:1] # select only one question when item id is provided break Transformer.convert_answers_to_proper_format(questions) self.response.set_questions(questions) else: items = SolrQuery(query_type = SolrQuery.CHALLENGE_QUERY, query_params = selected_facets).query() ItemTransformer(items = items).transform(answered_variables = answered_variables) self.response.set_items(items) questions = SolrQuery().query() # fetch default questions Transformer.convert_answers_to_proper_format(questions) self.response.set_questions(questions)
def populate(): """Method that populates the databse with data""" db.session.close() db.drop_all() db.create_all() # User.create_user("admin", "admin") c_male = Category.create_category(name="Jongen", metacategory=Metacategory.gender) c_female = Category.create_category(name="Meisje", metacategory=Metacategory.gender) c_programmer = Category.create_category( name="Programmeur", metacategory=Metacategory.profession) c_writer = Category.create_category(name="Schrijver", metacategory=Metacategory.profession) c_alone = Category.create_category(name="Alleen", metacategory=Metacategory.social) c_together = Category.create_category(name="Samen", metacategory=Metacategory.social) c_gaming = Category.create_category(name="Videospelletjes spelen", metacategory=Metacategory.hobby) c_tennis = Category.create_category(name="Tennissen", metacategory=Metacategory.hobby) c_fruit = Category.create_category(name="Fruit", metacategory=Metacategory.demo) c_vegetable = Category.create_category(name="Groente", metacategory=Metacategory.demo) male_images = [ 'https://res.cloudinary.com/hwutobbxz/image/upload/v1596306179/gender/boy-1_xbqkzy.png', 'https://res.cloudinary.com/hwutobbxz/image/upload/v1596306179/gender/boy-2_smpd2z.png', 'https://res.cloudinary.com/hwutobbxz/image/upload/v1596306179/gender/boy-3_r4ytga.png', 'https://res.cloudinary.com/hwutobbxz/image/upload/v1596306179/gender/boy-4_nwlwjy.png' ] female_images = [ 'https://res.cloudinary.com/hwutobbxz/image/upload/v1596306179/gender/girl-1_kwkmrz.png', 'https://res.cloudinary.com/hwutobbxz/image/upload/v1596306179/gender/girl-2_rhniuk.png', 'https://res.cloudinary.com/hwutobbxz/image/upload/v1596306179/gender/girl-3_xe1a9u.png', 'https://res.cloudinary.com/hwutobbxz/image/upload/v1596306180/gender/girl-4_xkvjjs.png' ] programmer_images = [ ("https://res.cloudinary.com/hwutobbxz/image/upload/v1596306549/profession/programmer-1_ulwehs.png", "Website"), ("https://res.cloudinary.com/hwutobbxz/image/upload/v1596306550/profession/programmer-2_lof1xf.png", "App"), ("https://res.cloudinary.com/hwutobbxz/image/upload/v1596306550/profession/programmer-4_pidzdt.png", "Call"), ("https://res.cloudinary.com/hwutobbxz/image/upload/v1596306550/profession/programmer-3_eg4wkm.png", "Streaming") ] writer_images = [ ("https://res.cloudinary.com/hwutobbxz/image/upload/v1596306550/profession/writer-1_eztpu9.png", "Newspaper"), ("https://res.cloudinary.com/hwutobbxz/image/upload/v1596306550/profession/writer-2_rkpv82.png", "Papers"), ("https://res.cloudinary.com/hwutobbxz/image/upload/v1596306550/profession/writer-3_irllf9.png", "Magazine"), ("https://res.cloudinary.com/hwutobbxz/image/upload/v1596306551/profession/writer-4_o7htgn.png", "Book") ] gaming_images = [ ("https://res.cloudinary.com/hwutobbxz/image/upload/v1596306334/hobby/game-1_n9io3s.png", "Game Controller"), ("https://res.cloudinary.com/hwutobbxz/image/upload/v1596306334/hobby/game-2_aquxcc.png", "Game Controller"), ("https://res.cloudinary.com/hwutobbxz/image/upload/v1596306334/hobby/game-3_spykmr.png", "Game Controller"), ("https://res.cloudinary.com/hwutobbxz/image/upload/v1596306334/hobby/game-4_pauwrg.png", "Game Controller") ] tennis_images = [ ("https://res.cloudinary.com/hwutobbxz/image/upload/v1596306334/hobby/tennis-1_smfocf.png", "Net"), ("https://res.cloudinary.com/hwutobbxz/image/upload/v1596306334/hobby/tennis-2_nfparh.png", "Racket"), ("https://res.cloudinary.com/hwutobbxz/image/upload/v1596306334/hobby/tennis-3_ezuh7s.png", "Shoe"), ("https://res.cloudinary.com/hwutobbxz/image/upload/v1596306334/hobby/tennis-4_wxlwze.png", "Ball") ] alone_images = [ ("https://res.cloudinary.com/hwutobbxz/image/upload/v1596306654/social/alone-1_hvi8pd.png", "Alone"), ("https://res.cloudinary.com/hwutobbxz/image/upload/v1596306654/social/alone-2_pitedg.png", "Alone"), ("https://res.cloudinary.com/hwutobbxz/image/upload/v1596306654/social/alone-3_ez8euu.png", "Alone"), ("https://res.cloudinary.com/hwutobbxz/image/upload/v1596306654/social/alone-4_adw4ji.png", "Alone") ] together_images = [ ("https://res.cloudinary.com/hwutobbxz/image/upload/v1596306655/social/together-1_y4i6i4.png", "Together"), ("https://res.cloudinary.com/hwutobbxz/image/upload/v1596306655/social/together-2_edkl5i.png", "Together"), ("https://res.cloudinary.com/hwutobbxz/image/upload/v1596306654/social/together-3_dwqijb.png", "Together"), ("https://res.cloudinary.com/hwutobbxz/image/upload/v1596306654/social/together-4_ai0lmg.png", "Together") ] fruit_images = [ ("https://res.cloudinary.com/hwutobbxz/image/upload/v1596305962/demo/fruit-1_evzbef.png", "Fruit"), ("https://res.cloudinary.com/hwutobbxz/image/upload/v1596306043/demo/fruit-2_xfiwal.png", "Fruit"), ("https://res.cloudinary.com/hwutobbxz/image/upload/v1596306043/demo/fruit-3_cozz4g.png", "Fruit"), ("https://res.cloudinary.com/hwutobbxz/image/upload/v1596306043/demo/fruit-4_sgdvu9.png", "Fruit") ] vegetable_images = [ ("https://res.cloudinary.com/hwutobbxz/image/upload/v1596306043/demo/vegetable-1_u4jotx.png", "Vegetable"), ("https://res.cloudinary.com/hwutobbxz/image/upload/v1596306043/demo/vegetable-2_lwst5m.png", "Vegetable"), ("https://res.cloudinary.com/hwutobbxz/image/upload/v1596306043/demo/vegetable-3_h079fa.png", "Vegetable"), ("https://res.cloudinary.com/hwutobbxz/image/upload/v1596306046/demo/vegetable-4_xm9cyn.png", "Vegetable") ] for link in male_images: Image.create_image(link=link, description="Man", attribute='man standing', c_id=c_male.id) for link in female_images: Image.create_image(link=link, description='Girl', attribute='girl standing', c_id=c_female.id) create_images(programmer_images, c_programmer.id) create_images(writer_images, c_writer.id) create_images(gaming_images, c_gaming.id) create_images(tennis_images, c_tennis.id) create_images(alone_images, c_alone.id) create_images(together_images, c_together.id) create_images(fruit_images, c_fruit.id) create_images(vegetable_images, c_vegetable.id) # likert ## Demographics 1-5 create_likert( "Ik maak makkelijk vrienden en werk graag samen.", 'https://res.cloudinary.com/hwutobbxz/video/upload/v1596200541/audio/1_ywbmuk.m4a' ) create_likert( "Ik ben gek op computers", 'https://res.cloudinary.com/hwutobbxz/video/upload/v1596200541/audio/2_qty6fj.m4a' ) create_likert( "Ik vind het het leukst om", 'https://res.cloudinary.com/hwutobbxz/video/upload/v1596200542/audio/3_e3qsyz.m4a' ) create_likert( "Als ik dat zou willen, zou ik later programmeur kunnen worden.", 'https://res.cloudinary.com/hwutobbxz/video/upload/v1596200542/audio/4_yxejoq.m4a' ) create_likert( "Ik wil later programmeur worden", 'https://res.cloudinary.com/hwutobbxz/video/upload/v1596200542/audio/5_r7ghrl.m4a' ) ## 6-10 create_likert( "Wie maakt het makkelijkst vrienden en werkt het liefst samen?", 'https://res.cloudinary.com/hwutobbxz/video/upload/v1596200541/audio/6_tbouud.m4a' ) create_likert( "Wie speelt er het liefste videospelletjes?", 'https://res.cloudinary.com/hwutobbxz/video/upload/v1596200541/audio/7_wiwrjx.m4a' ) create_likert( "Wie speelt er het liefste tennis?", 'https://res.cloudinary.com/hwutobbxz/video/upload/v1596200541/audio/8_l9xs3q.m4a' ) create_likert( "Welk beroep vind jij iets voor meisjes?", 'https://res.cloudinary.com/hwutobbxz/video/upload/v1596200541/audio/9_zqwjng.m4a' ) create_likert( "Welk beroep vind jij iets voor jongens?", 'https://res.cloudinary.com/hwutobbxz/video/upload/v1596200542/audio/10_qjljyp.m4a' ) ## 11-14 create_likert( "Programmeurs maken makkelijk vrienden en werken graag samen.", 'https://res.cloudinary.com/hwutobbxz/video/upload/v1596200542/audio/11_g0dvmj.m4a' ) create_likert( "Programmeurs zijn gek op computers en hebben weinig andere hobby’s.", 'https://res.cloudinary.com/hwutobbxz/video/upload/v1596200542/audio/12_nvbyjz.m4a' ) create_likert( "Programmeur zijn, dat is een beroep voor", 'https://res.cloudinary.com/hwutobbxz/video/upload/v1596200542/audio/13_x4cjuw.m4a' ) create_likert("Vraag 14", '') #15 Question.create_question( q_type=QuestionType.open_question, text="Wat doet een programmeur?", audio= 'https://res.cloudinary.com/hwutobbxz/video/upload/v1596200543/audio/15_kgj5ql.m4a' ) video_female = Image.create_image(link="B3600xjaz3Y", description='Role model intervention', attribute='Female') video_male = Image.create_image(link="SwISXzPoNUQ", description='Role model intervention', attribute='Male') # video_question 16 Question.create_question(q_type=QuestionType.video, images=[video_female]) # demographics ## 17 18 19 mc_1 = Question.create_question( q_type=QuestionType.mc_single_answer, text="Hoe oud ben je?", information=ParticipantInformationType.age, audio= 'https://res.cloudinary.com/hwutobbxz/video/upload/v1596200542/audio/17_fcwq8f.m4a' ) for i in range(7, 19): QuestionChoice.create_choice(choice_num=i - 6, q_id=mc_1.id, text=str(i)) QuestionChoice.create_choice(choice_num=13, q_id=mc_1.id, text="Anders") mc_2 = Question.create_question( q_type=QuestionType.mc_multiple_answer, text= "Waar zijn jouw ouders/verzorgers geboren? Er zijn meerdere antwoorden mogelijk.", information=ParticipantInformationType.ethnicity, audio= 'https://res.cloudinary.com/hwutobbxz/video/upload/v1596200543/audio/18_etdcmb.m4a' ) for i, ethnicity in enumerate(Ethnicity.__iter__(), 1): QuestionChoice.create_choice(choice_num=i, q_id=mc_2.id, text=ethnicity.value) mc_3 = Question.create_question( q_type=QuestionType.mc_single_answer, text="Ik voel me een ...", information=ParticipantInformationType.gender, audio= 'https://res.cloudinary.com/hwutobbxz/video/upload/v1596200542/audio/19_iiqikw.m4a' ) for i, gender in enumerate(Gender.__iter__(), 1): QuestionChoice.create_choice(choice_num=i, q_id=mc_3.id, text=gender.value) # 20 Question.create_question( q_type=QuestionType.notes, text="Researcher notes", information=ParticipantInformationType.researcher_notes) # video_question 21 Question.create_question(q_type=QuestionType.video, images=[video_male]) # experience ## 22 23 mc_4 = Question.create_question( q_type=QuestionType.mc_multiple_answer, text= "Heb je wel eens geprogrammeerd? Er zijn meerdere antwoorden mogelijk", information=ParticipantInformationType.experience, audio= 'https://res.cloudinary.com/hwutobbxz/video/upload/v1596200543/audio/22_jlrycd.m4a' ) for i, experience in enumerate(Experience.__iter__(), 1): QuestionChoice.create_choice(choice_num=i, q_id=mc_4.id, text=experience.value) mc_5 = Question.create_question( q_type=QuestionType.mc_multiple_answer, text="Ken jij een programmeur? Er zijn meerdere antwoorden mogelijk", information=ParticipantInformationType.familiar, audio= 'https://res.cloudinary.com/hwutobbxz/video/upload/v1596200543/audio/23_iicnjg.m4a' ) for i, familiar in enumerate(Familiar.__iter__(), 1): QuestionChoice.create_choice(choice_num=i, q_id=mc_5.id, text=familiar.value)
def test_sequence_again(self): q = Question.create().save() assert q.id == 1
def get(self, request, format=None): if not 'token' in request.GET: return Response(status=status.HTTP_404_NOT_FOUND) student = get_student(request.GET['token']) quiz = Quiz(subject='geometry') quiz.save() scores = Score.objects.all().filter(subject='geometry', student=student) avg = 0 for i in range(num_questions): area = random.choice(['Area', 'Perimeter']) if len(scores) > 2: for score in scores: avg = avg + score.value avg = avg / len(scores) if avg <= num_questions / 3.0: shape = 'Square' low = 2 high = 5 elif avg <= (2 * num_questions) / 3.0: shape = random.choice(['Square', 'Rectangle']) low = 3 high = 9 else: shape = random.choice(['Square', 'Rectangle', 'Triangle']) low = 6 high = 20 val = '' if shape == 'Square': x = random.randint(low, high) if area == 'Area': answer = x * x elif area == 'Perimeter': answer = 4 * x val = str(x) elif shape == 'Rectangle': x = random.randint(low, high) y = random.randint(low, high) while y == x: y == random.randint(low, high) if area == 'Area': answer = x * y elif area == 'Perimeter': answer = 2 * (x + y) if y > x: val = str(x) + ' ' + str(y) else: val = str(y) + ' ' + str(x) elif shape == 'Triangle': x = random.randint(low, high) if x % 2 == 1: if not x == high: x = x + 1 else: x = x - 1 y = random.randint(low, high) while y == x: y == random.randint(low, high) if area == 'Area': answer = (x * y) / 2 if y > x: val = str(x) + ' ' + str(y) else: val = str(y) + ' ' + str(x) elif area == 'Perimeter': pythag = random.choice([[3, 4, 5], [5, 12, 13], [8, 15, 17], [7, 24, 25], [9, 40, 41], [11, 60, 61], [12, 35, 37], [16, 63, 65], [20, 21, 29]]) answer = pythag[0] + pythag[1] + pythag[2] val = str(pythag[0]) + ' ' + str(pythag[1]) + ' ' + str( pythag[2]) text = shape + ' ' + area + ' ' + val explanation = 'blank on purpose' question = Question(text=text, answer=str(answer), explanation=explanation, quiz=quiz) question.save() quiz.save() serializer = QuizSerializer(quiz) return Response(serializer.data)