def set_data_from_file(file_path): ques_dict = json.load(open(file_path)) print("Loading locations...") User.objects.exclude(player__isnull=True).delete() Question.objects.all().delete() for loc_name, ques in ques_dict.items(): db_ques = Question(loc_name=loc_name) fields = ('answer','rent','stipend') db_ques.text = ques.get('question','') for field in fields: if field in ques: setattr(db_ques,field,ques[field]) db_ques.save() print("Precomputing distances...") Distance.objects.all().delete() for source_name, source_data in ques_dict.items(): if "latitude" in source_data and "longitude" in source_data: for dest_name, dest_data in ques_dict.items(): if "latitude" in dest_data and "longitude" in dest_data: if dest_name==source_name: dist=0 else: dist = get_dist(source_data["latitude"], dest_data["latitude"], abs(source_data["longitude"] - dest_data["longitude"])) source_db_obj = Question.objects.get(loc_name=source_name) dest_db_obj = Question.objects.get(loc_name=dest_name) Distance(source=source_db_obj, dest=dest_db_obj, distance=dist).save()
def questionupload(request): all_courses = Course.objects.all() courses = {} for i in range(len(all_courses)): courses[i] = all_courses[i] if request.method == "POST": n = int(request.POST['number']) titles = request.POST.getlist('title') firstoption = request.POST.getlist('option1') secondoption = request.POST.getlist('option2') thirdoption = request.POST.getlist('option3') fourthoption = request.POST.getlist('option4') correctanswer = request.POST.getlist('answer') selected_item = request.POST.get('itemid') for i in range(n): question_details = Question() question_details.question_id = str(selected_item) + str(i) question_details.questiontext = titles[i] question_details.course_id = Course.objects.get( course_id=selected_item) question_details.option1 = firstoption[i] question_details.option2 = secondoption[i] question_details.option3 = thirdoption[i] question_details.option4 = fourthoption[i] question_details.correctanswer = correctanswer[i] question_details.save() return render(request, 'questionconfirmation.html') return render(request, 'questionupload.html', {'courses': courses})
def test_question_to_dict(self): # type: () -> None q = Question(title="OS", text="Favorite OS?", multivote=False, locked=False, show_count=True) q.save() o1 = Option(text="Linux", question=q) o2 = Option(text="Windows", question=q) o3 = Option(text="Mac", question=q) o4 = Option(text=s_chikoo, question=q) o1.save() o2.save() o3.save() o4.save() qdict = { "title": "OS", "text": "Favorite OS?", "multivote": False, "locked": False, "show_count": True, "options": ["Linux", "Windows", "Mac", s_chikoo], } self.assertEqual(question_to_dict(q), qdict)
def add_question(ques_dict): # type: (Mapping[text_type, Any]) -> None ques_obj = Question() for attr in Question.serialize_order: if attr in ques_dict: setattr(ques_obj, attr, ques_dict[attr]) ques_obj.save() for option_text in ques_dict["options"]: Option.objects.create(text=option_text, question=ques_obj)
def load_distributed_poll_file(name: str, lines: List[str]) -> Tuple[DistributedPoll, List[Block], List[Question]]: poll = DistributedPoll() poll.name = name if poll.name.endswith('.txt'): poll.name = poll.name[:-4] poll.save() blocks: List[Block] = [] questions: List[Question] = [] current_block: Optional[Block] = None current_question: Optional[Question] = None current_options: List[str] = [] on_options = False for line in lines: line = line.strip() if line.startswith("[[Block:"): if current_block is not None: blocks.append(current_block) on_options = False if current_question is not None: current_question.save() # noqa: T484 questions.append(current_question) current_question = None current_options = [] line = line[8:-2] line = line.strip() current_block = Block() current_block.name = line current_block.poll = poll current_block.save() elif len(line) == 0: if on_options: current_question.options = current_options # noqa: T484 questions.append(current_question) current_question.save() # noqa: T484 current_question = None current_options = [] on_options = False elif current_question is not None: on_options = True elif current_question is None: if current_block is None: raise Exception("Tried to start a question outside of a block\n" + line) current_question = Question() current_question.question = line current_question.block = current_block elif on_options: current_options.append(line) if current_question is not None and on_options: current_question.options = current_options # noqa: T484 questions.append(current_question) current_question.save() # noqa: T484 if current_block is not None: blocks.append(current_block) return poll, blocks, questions
def long_test_form(request): if request.method=="POST": question_text=request.POST['question_text'] long_text = request.POST['long'] q=Question() q.long_text=long_text q.question_text=question_text q.pub_date = datetime.now() q.save() return HttpResponseRedirect(reverse('detail', args=(q.id,))) return render(request, "main/form.html",{})
def createQuestion(self, count): for i in range(int(count)): now = datetime.datetime.now() title = random.choice("qwertyuiolkjhgfdsazxcvbnm") + random.choice("qwertyuiolkjhgfdsazxcvbnm") + random.choice("qwertyuiolkjhgfdsazxcvbnm") for i in range(20): text = random.choice("qwertyuiolkjhgfdsazxcvbnm") + random.choice("qwertyuiolkjhgfdsazxcvbnm") + random.choice("qwertyuiolkjhgfdsazxcvbnm") text = text*5 + "/n" i = random.choice(User.objects.all()) rating = randrange(0, 1000) question = Question(title = title, question_text = text, user = i, pubDate = now, rating = rating) question.save() print ("Question created!")
def get_question(request): try: username = request.POST.get('username') question = request.POST.get('question') question_object = Question() question_object.title = question question_object.username = username question_object.save() return JsonResponse(dict(result=True)) except: return JsonResponse(dict(result=False))
def add_ques_list(fname): Question.objects.all().delete() with open(fname) as qfile: data = json.load(qfile) for (i, ques) in enumerate(data): q = Question(qno=i+1) add_attrs(q, ('score', 'corrans'), ques) add_attrs(q, ('title',), ques, False) if "hint" in ques: add_attrs(q, ('hint', 'hint_penalty'), ques) q.hint_enabled = True else: q.hint_enabled = False q.save()
def add_ques_list(fname): Question.objects.all().delete() with open(fname) as qfile: data = json.load(qfile) for (i, ques) in enumerate(data): q = Question(qno=i + 1) add_attrs(q, ('score', 'corrans'), ques) add_attrs(q, ('title', ), ques, False) if "hint" in ques: add_attrs(q, ('hint', 'hint_penalty'), ques) q.hint_enabled = True else: q.hint_enabled = False q.save()
def add_question(section_in_db, question_dict): # add generic stuff question = Question() valid_properties = read_schemas.schemas["question"]["properties"] special_properties = ["metadata", "tags"] for key in question_dict: if key in valid_properties and key not in special_properties and hasattr( question, key): setattr(question, key, question_dict[key]) # It was planned at the beginning of the project that useless keys # will be added as JSON to the metadata field of models.Question # but implementing that seems to be difficult so I'm leaving it out for now question.section = section_in_db question.save() if "tags" in question_dict: for tagname in question_dict["tags"]: question.add_tag(tagname) # add type-specific stuff qtype = question_dict["type"] if qtype == "text" or qtype == "regex": text_question = TextQuestion(question=question) text_question.correct_answer = question_dict["answer"] if "ignore_case" in question_dict: text_question.ignore_case = question_dict["ignore_case"] if "use_regex" in question_dict: text_question.use_regex = question_dict["use_regex"] elif qtype == "regex": text_question.use_regex = True text_question.save() elif qtype == "mcq" or qtype == "mmcq": mcq_question = McqQuestion(question=question) if "multicorrect" in question_dict: mcq_question.multicorrect = question_dict["multicorrect"] elif qtype == "mmcq": mcq_question.multicorrect = True mcq_question.save() if "options" in question_dict: add_options(mcq_question, question_dict["options"], None) if "correct_options" in question_dict: add_options(mcq_question, question_dict["correct_options"], True) if "wrong_options" in question_dict: add_options(mcq_question, question_dict["wrong_options"], False) mcq_question.verify_correct_options() else: raise QuestionTypeNotImplemented(qtype)
def add_question(section_in_db,question_dict): # add generic stuff question = Question() valid_properties = read_schemas.schemas["question"]["properties"] special_properties = ["metadata","tags"] for key in question_dict: if key in valid_properties and key not in special_properties and hasattr(question,key): setattr(question,key,question_dict[key]) # It was planned at the beginning of the project that useless keys # will be added as JSON to the metadata field of models.Question # but implementing that seems to be difficult so I'm leaving it out for now question.section = section_in_db question.save() if "tags" in question_dict: for tagname in question_dict["tags"]: question.add_tag(tagname) # add type-specific stuff qtype = question_dict["type"] if qtype=="text" or qtype=="regex": text_question = TextQuestion(question=question) text_question.correct_answer = question_dict["answer"] if "ignore_case" in question_dict: text_question.ignore_case = question_dict["ignore_case"] if "use_regex" in question_dict: text_question.use_regex = question_dict["use_regex"] elif qtype=="regex": text_question.use_regex = True text_question.save() elif qtype=="mcq" or qtype=="mmcq": mcq_question = McqQuestion(question=question) if "multicorrect" in question_dict: mcq_question.multicorrect = question_dict["multicorrect"] elif qtype=="mmcq": mcq_question.multicorrect = True mcq_question.save() if "options" in question_dict: add_options(mcq_question,question_dict["options"],None) if "correct_options" in question_dict: add_options(mcq_question,question_dict["correct_options"],True) if "wrong_options" in question_dict: add_options(mcq_question,question_dict["wrong_options"],False) mcq_question.verify_correct_options() else: raise QuestionTypeNotImplemented(qtype)
def create_questions(n): profile_id_list = [user for user in User.objects.all()] tags_list = [tag.pk for tag in Tag.objects.all()] for _ in range(n): u_id = random.choice(profile_id_list) q = Question(author=u_id, title=fake.sentence(), text=fake.text()) q.save() for _ in range(random.randint(1, 3)): t_id = random.choice(tags_list) q.tags.add(t_id) q.save() create_answers(random.randint(1, 10), q) for i in range(10): create_like(q)
def details(request): try: selected_choice = request.POST['choice'] pub_date_selected = request.POST['pub_date'] author_selected = request.POST['author'] except (KeyError, Choice.DoesNotExist): selected_choice = '' pub_date_selected = '2018-08-08' author_selected = '' q = Question() q.question_text = selected_choice q.pub_date = pub_date_selected q.author = author_selected q.save() return render(request, 'main/details.html', {'selected_choice': selected_choice})
def question_add(request): if request.method == 'POST': form = NewForm(request.POST) if form.is_valid(): qs = Question() qs.question_text = form.cleaned_data['question'] qs.answer = form.cleaned_data['answer'] qs.save() return redirect('/') else: form = NewForm() print("pressed") return render(request, 'new_question.html', {'form': form})
def newView(request): current_user = request.user if not current_user.is_authenticated: return HttpResponseRedirect(reverse('account_signup')) if request.method != 'POST': render(request, 'new.html', {'current_user': current_user}) form = QuestionForm(request.POST) if not form.is_valid(): return render(request, 'new.html', {'current_user': current_user}) q = Question(user_id=current_user.id, title=form.cleaned_data['title'], body=form.cleaned_data['body']) q.save() return HttpResponseRedirect('/')
def add_question(request): """Page for adding a poll.""" if no_access(request, 'questions'): return HttpResponseRedirect(reverse('no_access')) grp = get_info(request) error = '' q = {'name': '', 'text': ''} if request.method == 'POST': try: name = request.POST['name'] text = request.POST['text'] q['name'] = name q['text'] = text answer_count = int(request.POST['answer_count']) answers = [ request.POST[('ans' + str(i + 1))] for i in range(answer_count) ] if name == '': raise Exception('Enter caption.') if text == '': raise Exception('Enter question text.') for answer in answers: if answer == '': raise Exception('Enter all answers') except Exception as ex: error = ex else: question = Question(name=name, text=text, answer_count=answer_count) question.save() for answer in answers: ans = Answer(text=answer, votes_count=0, question=question) ans.save() return HttpResponseRedirect(reverse('admin_questions')) template = loader.get_template('main/admin_add_question.html') context = RequestContext(request, { 'question': q, 'error_message': error, 'group': grp }) return HttpResponse(template.render(context))
def newView(request): current_user = request.user if not current_user.is_authenticated: return HttpResponseRedirect(reverse("account_signup")) if request.method != "POST": render(request, "new.html", {"current_user": current_user}) form = Question_form(request.POST) if not form.is_valid() or current_user.points < 0: return render(request, "new.html", {"current_user": current_user}) q = Question( user_id=current_user.id, title=form.cleaned_data["title"], body=form.cleaned_data["body"], ) q.save() return HttpResponseRedirect("/")
def new_question(request, session_id): data = {'type': 'new'} # Check we are allowed to actually access this session if not Session.objects.filter(id=session_id, course=request.session['course_id']): data['error'] = 'The session specified could not be found' return render_to_response('error.html', data, context_instance=RequestContext(request)) if request.method == 'POST': question = request.POST.get('question') max_options = request.POST.get('max-options') # Question must have a body set and the current course must contain the session if question and max_options: # We can now add the question to the database q = Question() q.session_id = session_id q.question_body = question q.save() for x in range(0,int(max_options)): # Is there an option set at this index? option_body = request.POST.get('option-body[{0}]'.format(x)) option_correct = bool(request.POST.get('option-correct[{0}]'.format(x))) if option_body: o = Question_option() o.question_id = q.pk o.body = option_body o.correct = option_correct o.save() return HttpResponseRedirect('/tutor/sessions/{0}/'.format(session_id)) else: if not max_options: data['error'] = '"max-options" option was missing from your request' else: data['error'] = 'Your question must have a body' return render_to_response('question_form.html', data, context_instance=RequestContext(request))
def add_question(request): """Page for adding a poll.""" if no_access(request, 'questions'): return HttpResponseRedirect(reverse('no_access')) grp = get_info(request) error = '' q = {'name':'', 'text':''} if request.method == 'POST': try: name = request.POST['name'] text = request.POST['text'] q['name'] = name q['text'] = text answer_count = int(request.POST['answer_count']) answers = [request.POST[('ans'+str(i+1))] for i in range(answer_count)] if name == '': raise Exception('Enter caption.') if text == '': raise Exception('Enter question text.') for answer in answers: if answer == '': raise Exception('Enter all answers') except Exception as ex: error = ex else: question = Question(name=name, text=text, answer_count=answer_count) question.save() for answer in answers: ans = Answer(text=answer, votes_count=0, question=question) ans.save() return HttpResponseRedirect(reverse('admin_questions')) template = loader.get_template('main/admin_add_question.html') context = RequestContext(request, { 'question':q, 'error_message':error, 'group':grp }) return HttpResponse(template.render(context))
def handle(self, *args, **options): # Создание пользователей for i in range(1, 10000): user = User.objects.create_user("username_" + str(i), password="******", email="email_" + str(i)) user.profile.nick_name = "nick_name_" + str(i) user.save() users = User.objects.all() # Создание тегов for i in range(1, 1000): try: Tag(name="тег_" + str(i)).save() except Exception: pass tags = Tag.objects.all() # Создание вопросов for i in range(1, 10000): q = Question( title="Заголовок вопроса " + str(i), text=("Текст вопроса " + str(i) + " ") * random.randint(1, 50), user=random.choice(users), ) q.save() for _ in range(0, random.randint(0, 3)): q.tags.add(random.choice(tags)) questions = Question.objects.all() # Создание ответов for i in range(1, 10000): Answer(text=("Текст ответа " + str(i) + " ") * random.randint(1, 50), is_correct=bool(random.randint(0, 1)), question=random.choice(questions), user=random.choice(users)).save() answers = Answer.objects.all() # Создание лайков вопросов for _ in range(1, 10000): like = QuestionLike(question=random.choice(questions), user=random.choice(users), is_like=bool(random.randint(0, 1))) like.save() if like.is_like: like.question.rating += 1 else: like.question.rating -= 1 like.question.save() # Создание лайков ответов for _ in range(0, 100001): like = AnswerLike(answer=random.choice(answers), user=random.choice(users), is_like=bool(random.randint(0, 1))) like.save() if like.is_like: like.answer.rating += 1 else: like.answer.rating -= 1 like.answer.save() # python manage.py database_data
def createNewQuestion(author_id): question = Question(author_id = author_id) question.save() return question