def add_question(): if not current_user.is_admin(): # permission deny return redirect(url_for("permission_deny")) error = "" # else: the admin has logged_in if request.method == "POST": quest = Question() # get the question set # grap the user input question = request.form["question"] answers = request.form["answers"].split("/") pool_id = request.form["pool_id"] q_type = request.form["type"] try: quest.add_q(question, pool_id, q_type, answers=answers) except TypeError as e: error = format(e) else: return render_template("success_add_q.html") # invalid input, push back what user has been input, and push the error message return render_template("add_q.html",\ msg_err = error,question = question, \ answers = request.form["answers"]) return render_template("add_q.html")
def get(self): #for check parameter no = int(self.request.get('no')) logging.debug(str(no)) # 問題を1件取得 question = Question().get_by_id(no) response_data = {} response_data['No'] = question.key().id() response_data['Date'] = str(question.date) response_data['Author'] = question.author response_data['Title'] = question.title response_data['Detail'] = question.detail response_data['Bakyo'] = question.bakyo response_data['Honba'] = question.honba response_data['Cha'] = question.cha response_data['Junme'] = question.junme response_data['Tenbo'] = question.tenbo response_data['Tehai'] = question.tehai response_data['Tsumo'] = question.tsumo response_data['Dora'] = question.dora # レスポンスデータ作成 resp = _ResponseFormat.create("GetQuestion", True, response_data) # レスポンス送信 send_response(self, resp)
def start(): questions_list = sample(range(0, len(df)), 11) change = Change(Question(questions_list[-1])) remove = Remove() second = Second() # game starting sequence clear() print("遊戲開始") print("輸入A、B、C、D作答,E、F、G啟用求救卡\nE:更換題目 F:刪去選項 G:第二條命\n你準備好了嗎?") time.sleep(1) for i in range(2): print(3 - i) time.sleep(2) for m in range(10): print("第{}題:\n".format(m + 1)) change, remove, second, isCorrect = check(Question(questions_list[m]), change, remove, second) if m == 9 and isCorrect: print("恭喜挑戰成功\n") return None elif not isCorrect: print("\nGAME OVER\n") return None else: print("------------\n 下一題\n------------\n")
def generateQuiz(): # Create a set of 10 questions for the quiz quiz = [] # Question 1 quiz.append(Question('The beaver is the national emblem of which country?', 'Canada', 'United States', 'Spain', 'Iceland', 1)) # Question 2 quiz.append(Question('How many players are there in a baseball team?', '7', '9', '11', '12', 2)) # Question 3 quiz.append(Question('In Fahrenheit, at what temperature does water freeze?', '-100', '-32', '0', '32', 4)) # Question 4 quiz.append(Question('The Statue of Liberty was given to the US by which country?', 'United States', 'Portugal', 'France', 'Great Britain', 3)) # Question 5 quiz.append(Question('Which of the planets is closest to the sun?', 'Mercury', 'Venus', 'Mars', 'Earth', 1)) # Question 6 quiz.append(Question('How many letters are there in the German alphabet?', '26', '30', '33', '38', 2)) # Question 7 quiz.append(Question('In the sport of Judo, what color belt follows an orange belt?', 'Red', 'Green', 'Blue', 'Brown', 2)) # Question 8 quiz.append(Question('Who was the first president of the United States?', 'Abraham Lincoln', 'George Washington', 'Woodrow Wilson', 'Benjamin Franklin', 2)) # Question 9 quiz.append(Question('What is the largest bone in the human body?', 'Spine', 'Elbow', 'Femur', 'Skull', 3)) # Question 10 quiz.append(Question('Entomology is the branch of science that studies what?', 'Forests', 'Oceans', 'Plants', 'Insects', 4)) return quiz
def get(self): # check for correct cookie name = self.request.cookies.get("name") # if cookie is correct, render page if name == "ADMIN": # various calculations for statistics numberOfStudents = User.query(User.isInstructor == 0).count() numberOfInstructors = User.query(User.isInstructor == 1).count() numberOfCourses = Course.query().count() studentInstructorRatio = round( float(numberOfStudents) / float(numberOfInstructors), 3) totalQuestionsCount = Question.query().count() answeredQuestionsCount = Question.query( Question.answer != "").count() unansweredQuestionsCount = totalQuestionsCount - answeredQuestionsCount values = { "username": "******", "numberOfStudents": numberOfStudents, "numberOfInstructors": numberOfInstructors, "numberOfCourses": numberOfCourses, "studentInstructorRatio": studentInstructorRatio, "totalQuestions": totalQuestionsCount, "answeredQuestions": answeredQuestionsCount, "unansweredQuestions": unansweredQuestionsCount } template = JINJA_ENVIRONMENT.get_template('HTML/ADMIN.html') self.response.write(template.render(values)) # else redirect to login page else: self.redirect('/')
def delete_wallet(self, app): from question import Question name = self.ids.wallet_selector.selection[0] d = Question( _('Delete wallet?') + '\n' + os.path.basename(name), lambda: app.delete_wallet(name)) d.open()
def vw_main(): pygame.init() vw_settings = Setting() vw_stats = Stats() screen = pygame.display.set_mode( (vw_settings.screen_width, vw_settings.screen_height)) pygame.display.set_caption("Verification wheel") # 方案1:从数据库中抽取10道题目,存入一个字典列表中 cur_question = Question(default_question, vw_settings, screen, vw_stats) # 方案2:控制循环次数,每次都从题库中抽取1个题目(不能重复) while vw_stats.game_active: if not vw_stats.answer_en: print("Welcome to Verification Wheel Game!") cur_question = vf.get_question(file_path, vw_settings, screen, vw_stats) # 将问题打印到屏幕上 # print(cur_question.ask) # 将选项在屏幕上显示 # print(cur_question.opts) # 传递答案 cur_question.gen_answer() vf.update_screen(vw_settings, vw_stats, screen, cur_question) vf.check_events(vw_settings, vw_stats, screen, cur_question)
def parse(self, string): super(StemsParser, self).parse(string) si = r'[0-9]+\.\s+' sb = r'.+?[?:.]\n\n' o = r'.+' regex = r"({si}{sb})({o})".format( si=si, sb=sb, o=o, ) self._tokenize(string) for token in self._tokens: question = Question() match = re.search(regex, token, re.DOTALL) if match: question.stem = match.group(1).strip() for option in match.group(2).split('\n'): if option: question.options.append(option.strip()) else: break self._questions.append(question) return self
def ask_boy_girl(): question = Question(question="Remind me, are you a BOY or a GIRL?", choices=["1)\tBOY", "2)\tGIRL"]) game_print(str(question)) question.user_input = game_input(regex=r"^[1-2]$") return question.user_input
def display_favorite(self): system("cls") all_fav = Favourites.display_all_favourite_product() element_to_search = {} if all_fav != []: for element in all_fav: element_to_search[element[0]] = element[1] C_EMPTY.append( Product.display_product(["name_product"], "id_product", element[0])[0][0]) C_EMPTY.append(MAIN_MENU) C_EMPTY.append(SUPRESS) qst_all_fav = Question(QUESTIONER, Q5, clean=1).answer if qst_all_fav != SUPRESS and qst_all_fav != MAIN_MENU: favourite_prod = Product.display_product(["id_product"], "name_product", qst_all_fav)[0][0] Favourites.display_favourite_product( str(favourite_prod), str(element_to_search[favourite_prod])) all_fav.clear() C_EMPTY.clear() elif qst_all_fav == SUPRESS: Favourites.suppress_all() all_fav.clear() C_EMPTY.clear() return MAIN_MENU elif qst_all_fav == MAIN_MENU: C_EMPTY.clear() return MAIN_MENU else: Question(display(150, "=", NO_FAV_PRODUCT, 1, "|", "left"), clean=1) return MAIN_MENU
def loadSurvey(filename): from question import Question from answer import Answer survey = None f = open(filename, "r") if f is not None: s = "" b = f.read(512) while len(b): s += b b = f.read(512) f.close() sd = jsonpickle.decode(s) survey = Survey() survey.name = sd['name'] survey.questions = {} for qd in sd['questions'].values(): question = Question() question.id = qd['id'] question.name = qd['name'] question.answers = {} for ad in qd['answers'].values(): answer = Answer() answer.id = ad['id'] answer.value = ad['value'] answer.selected = ad['selected'] answer.editable = ad['editable'] question.answers[answer.id] = answer survey.questions[question.id] = question return survey
def get(self): # check for correct cookie name = self.request.cookies.get("name") instructors = User.query(User.ePantherID == name, User.isInstructor == 1).fetch() # if cookie is correct, render page if len(instructors) != 0: curInstructor = instructors[0] # pull various landing page statistics totalQuestions = Question.query( Question.instructor == curInstructor.key).count() answeredQuestions = Question.query( Question.instructor == curInstructor.key, Question.answer != "").count() unansweredQuestions = totalQuestions - answeredQuestions values = { "username": curInstructor.ePantherID, "totalQuestions": totalQuestions, "answeredQuestions": answeredQuestions, "unansweredQuestions": unansweredQuestions } template = JINJA_ENVIRONMENT.get_template( 'HTML/Instructor Home.html') self.response.write(template.render(values)) # else redirect to login page else: self.redirect('/')
def __print_question(question: Question) -> str: if question.get_answer_column() == 1: return LatexExam.__print_question_1(question) elif question.get_answer_column() == 2: return LatexExam.__print_question_2(question) else: return LatexExam.__print_question_4(question)
def __print_question_4(question: Question) -> str: """ Print the question as 4 columns. :param question: Questions to print. :return: Character string representing the question content in latex. """ return """ \\begin{{question}} {question_content} \\begin{{tabular}}{{ m{{0.25\\linewidth}} m{{0.25\\linewidth}} m{{0.25\\linewidth}} m{{ 0.25\\linewidth}}}} A. {answer_1} & B. {answer_2} & C. {answer_3} & D. {answer_4} \\\\ \\end{{tabular}} \\end{{question}} """.format(question_content=question.question, answer_1=question.get_answer(1), answer_2=question.get_answer(2), answer_3=question.get_answer(3), answer_4=question.get_answer(4))
def game_socialization(): running = True questions = pygame.sprite.Group() for i in range(15): new_question = Question() questions.add(new_question) while running: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == KEYDOWN: if event.key == K_ESCAPE: running = False if player.finish == True: player.finish = False player.rect.x = 0 player.rect.y = 0 running = False for new_question in questions: if pygame.sprite.spritecollideany(new_question, all_sprites): new_question.kill() screen.fill(BLACK) maze.draw_maze(screen, WHITE) all_sprites.draw(screen) questions.draw(screen) all_sprites.update(maze) questions.update() pygame.display.flip() pygame.display.update() mainClock.tick(60)
def generate_questions(self): return [ Question(self.question1()), Question(self.question2()), Question(self.question3()), Question(self.question4()) ]
def parse(self, string): question = Question() option = False self._tokenize(string) for token in self._tokens: o = re.match(r"^\s*[a-zA-Z][.)] ", token) if o and o.group(): option = True try: assert question is not None question.options.append(token) except AssertionError: pass continue if option: self._questions.append(question) question = Question() question.stem = '' option = False try: assert question is not None question.stem += token + '\n' except AssertionError: pass if question and len(question.options) > 0: self._questions.append(question) return self
def parse(self, string): re_index = r'\**\s*(?:[A-Ea-e]\.|\(?[A-Ea-e]\))' re_body = r'.+' re_option = r'({index}\s+{body})'.format(index=re_index, body=re_body) self._tokenize(string) # spin thru the input chunks two at a time, the first being the # stem, presumably, and the second being the option group for st_index in range(0, len(self._tokens), 2): op_index = st_index +1 if op_index < len(self._tokens): question = Question() stem = re.search(r'[0-9]+(?:\.|\s).+$', self._tokens[st_index], re.DOTALL) #~ stem = re.search(r"\n*((?:[0-9]*\.*\s*).+)$", self._tokens[st_index], re.DOTALL) #~ stem = re.search(r"(?:[0-9]+\s+(?:.|\n)+$)+?|(?:\n*.+$)", self._tokens[st_index]) question.stem = stem.group().strip() if stem else self._tokens[st_index] options = [o.strip() for o in re.split(re_option, self._tokens[op_index]) if o.strip()] for option in options: question.options.append(option) self._questions.append(question) return self
def get(self): quizId = self.get_argument('user_choice', '') answerId = self.get_argument('answer', '') if int(answerId) > 1: print(SocketHandler.listForPoints) user_socket_list_that_was_already_check = [] #Question.check_answers(SocketHandler.listForPoints) for user in SocketHandler.listForPoints: if user[0] not in user_socket_list_that_was_already_check: user_socket_list_that_was_already_check.append(user[0]) print('aaaa') if Question.if_answer_correct(user[1], quizId, answerId): user_name = user[0] for user_to_check in SocketHandler.players: if user_to_check.userName == user_name: print('ws') user_to_check.addPoints(20) print(user_to_check.points) else: print('asdf') SocketHandler.listForPoints = [] if not self.questionList: self.questionList = Question.get_questions_by_id(quizId) self.render("templates/question.html", questions=self.questionList[int(answerId) - 1], points=SocketHandler.players, max_id=len(self.questionList))
def get(self): # check for correct cookie name = self.request.cookies.get("name") students = User.query(User.ePantherID == name, User.isInstructor == 0).fetch() # if cookie is correct, render page if len(students) != 0: curStudent = students[0] # pull counts of answered and unanswered questions allQuestionsQuery = Question.query( Question.student == curStudent.key) allQuestionsCount = allQuestionsQuery.count() answeredQuestionsCount = Question.query( Question.student == curStudent.key, Question.answer != "").count() unansweredQuestionsCount = allQuestionsCount - answeredQuestionsCount values = { "username": curStudent.ePantherID, "totalQuestions": allQuestionsCount, "answeredQuestions": answeredQuestionsCount, "unansweredQuestions": unansweredQuestionsCount } template = JINJA_ENVIRONMENT.get_template('HTML/Student Home.html') self.response.write(template.render(values)) # else redirect to login page else: self.redirect('/')
def read_question(self): line = self._question_file.read_until_data() q = Question(line) if q._type is not Question_type.UNKNOWN: self._questions.append(q) print("Question for {1}: {0}".format(Question(line), self._player_type))
def _best_split(self, rows): '''Finds the best Question (using info_gain) that splits the rows into left and right buckets. Returns a Question (records the col_index and the value.) @ bad performance when we have really large number of rows. Can improve by first sorting and then doing a binary search ''' previous_impurity = self.criterion.impurity(rows) BestInfoGain = 0 # find the best col and val to split the rows best_question = None num_rows, num_cols = rows.shape for col in range(num_cols - 1): # last col is the label # rows have same len for row in range(num_rows): val = rows.iloc[row, col] # this val may be the wedge # value for the question q = Question(col, val) left, right = q.divide_on_question(rows) if left.shape[0] == 0 or right.shape[0] == 0: continue # ignore the case when no splitting InfoGain = self.criterion.info_gain(left, right, previous_impurity) # if best info gain crossed save state or save Question if InfoGain >= BestInfoGain: BestInfoGain = InfoGain best_question = q if previous_impurity == InfoGain: return BestInfoGain, best_question # already best return BestInfoGain, best_question
def parse(self, string): re_index = r'\**\s*(?:[A-Ea-e]\.|\(?[A-Ea-e]\))' re_body = r'.+' re_option = r'({index}\s+{body})'.format(index=re_index, body=re_body) self._tokenize(string) # spin thru the input chunks two at a time, the first being the # stem, presumably, and the second being the option group for st_index in range(0, len(self._tokens), 2): op_index = st_index + 1 if op_index < len(self._tokens): question = Question() stem = re.search(r'[0-9]+(?:\.|\s).+$', self._tokens[st_index], re.DOTALL) #~ stem = re.search(r"\n*((?:[0-9]*\.*\s*).+)$", self._tokens[st_index], re.DOTALL) #~ stem = re.search(r"(?:[0-9]+\s+(?:.|\n)+$)+?|(?:\n*.+$)", self._tokens[st_index]) question.stem = stem.group().strip( ) if stem else self._tokens[st_index] options = [ o.strip() for o in re.split(re_option, self._tokens[op_index]) if o.strip() ] for option in options: question.options.append(option) self._questions.append(question) return self
def question(id): form = AnswerForm(request.form) question = Question.find(id) if not question: return random_question() if request.method == 'GET' or (request.method == 'POST' and not form.validate()): return render_template('question.html', question=question, form=form, amount=Question.size()) elif request.method == 'POST' and form.validate(): if request.form['answer'] == question.answer: flash('Correct!', 'positive') return random_question() else: flash('Wrong Answer!', 'negative') return render_template('question.html', question=question, form=form, amount=Question.size()) else: return render_template('invalid_request.html')
def test_blank_name(self): question = Question() question.text = 'Blank test question' question.answers = [] try: question.save() except KeyError, e: print 'Adding blank question failed: %s' % e
def answer(self, question: Question): correct_answer = question.get_correct_answer() wrong_answers = question.get_wrong_answers() if random() <= self._answer_prob[question.question_data.difficulty]: correct_answer.select() else: choice(wrong_answers).select()
def test_creation(self): q = {'name': 'q1', 'text': 'Random question one, choose a.', 'answers': [{'value': 'a', 'text': 'a'}, {'value': 'b', 'text': 'b'}, {'value': 'c', 'text': 'c'},{'value': 'd', 'text': 'd'}] } question = Question(q) assert question.name == q['name'] and question.text == q['text'] and question.answers == q['answers'] question.save()
def __init__(self): super().__init__("respond") # two for inserting new respond self.__mcq = RespondMcq() self.__text = RespondText() # check the type of question self.__survey = Survey() self.__question = Question()
class MyTest(unittest.TestCase): # test cases for assumption library # tests getTruthValue function from assumption library def test_getTruthValue(self): self.Numerical_truth_value = random.randint( 0, 2) #always randomize truthvalue for every test run self.assumption_text = 'Lorem Ipsum' self.reason_list = [(bool(random.getrandbits(1)), 'Lorem Ipsum1'), (bool(random.getrandbits(1)), "Lorem Ipsum2") ] #always randomize boolean values for reason list self.temp_assumption = Assumption(self.Numerical_truth_value, self.assumption_text, self.reason_list) self.assertEqual(self.temp_assumption.getTruthValue(), self.Numerical_truth_value) # tests getAssumptionText function from assumption library def test_getAssumptionText(self): self.Numerical_truth_value = random.randint(0, 2) self.assumption_text = 'Lorem Ipsum' self.reason_list = [(bool(random.getrandbits(1)), 'Lorem Ipsum1'), (bool(random.getrandbits(1)), "Lorem Ipsum2")] self.temp_assumption = Assumption(self.Numerical_truth_value, self.assumption_text, self.reason_list) self.assertEqual(self.temp_assumption.getAssumptionText(), self.assumption_text) # tests add_reason function from assumption library def test_add_reason(self): self.temp_assumption = get_random_assumption() self.test_value = bool(random.getrandbits(1)) self.test_reason = "Lorem Ipsum{}".format(random.randint( 0, 1000)) #randomize self.temp_assumption.add_reason(self.test_value, self.test_reason) self.assertEqual(self.temp_assumption.reason_list[-1], (self.test_value, self.test_reason)) # test cases for question library # tests addAssumption function in question library def test_addAssumption(self): # temporary assumptions self.temp_assumption = get_random_assumption() self.temp_assumption1 = get_random_assumption() self.assumptions = [self.temp_assumption] # temporary question self.name = "Lorem Ipsum{}".format(random.randint( 0, 1000)) # randomize string inputs self.rw_model = "Lorem Ipsum{}".format(random.randint(0, 1000)) self.ideal_model = "Lorem Ipsum{}".format(random.randint(0, 1000)) self.temp_question = Question(self.name, self.rw_model, self.ideal_model, self.assumptions) self.temp_question.addAssumption(self.temp_assumption1) self.assertEqual( self.temp_question.assumptions[-1].getAssumptionText(), self.temp_assumption1.getAssumptionText())
def get_question(question_id): if Question.is_null() == False: rows = Question.query(Question.serial_no==question_id).fetch() if len(rows) == 1: return dict(total= Question.count(), detail = rows[0]) else: return empty_question() else: return empty_question()
def test_display_FAQ(self): self.faq1 = Question(isFAQ=True, question="?", answer="!") self.faq2 = Question(isFAQ=True, question="??", answer="!!") self.faq3 = Question(isFAQ=True, question="???", answer="!!!") self.notfaq = Question(isFAQ=False, question="!????", answer="?!!!!") self.assertTrue(self.faq1.isFAQ) self.assertTrue(self.faq2.isFAQ) self.assertTrue(self.faq3.isFAQ) self.assertFalse(self.notfaq.isFAQ)
class RespondMcq(SqlUtil): """Control table for respond_mcq.""" def __init__(self): super().__init__("respond_mcq") self.__q = Question() def new_ans(self, respond_id, question_id, answer): # insert the respond_id by respond class self.insert("respond_id", respond_id) # insert the question_id self.insert("question_id", question_id) # insert the answer self.insert("answer", answer) return self.save() def count_respond(self, survey_id, question_id): # count grather all the respond to gether # get the information of this question this_q = self.__q.find_q(question_id) this_q = this_q[0] # count id for possible answers a_count = 0 # to record all the answers ans_l = [this_q[1], this_q[2]] for q in this_q[3:]: # serach for all possible answers self.clear(join=True, col=True) # get the information of this question this_q = self.__q.find_by_id(question_id).one() # join table search self.with_table("respond", "respond_id", "id").col_name("answer") # find the criteria self.find("question_id", question_id).find("survey_id", survey_id) # answer filter self.find("answer", a_count) a_count += 1 # count the answer number for this answer return_list = self.all() # count the results and append in to list ans_l.append([q, len(return_list)]) # force clear all the join self.clear(True, True) # return [question,[[ans, count],..]] return ans_l def delete_by_respond_id(self, respond_id): self.find("respond_id", respond_id).delete()
def get_questions(self): questions = [] file = open(self.file_name, 'r') for line in file: t = line.rstrip().split('**') if t[1] == 'T': questions.append(Question(t[0], True)) else: questions.append(Question(t[0], False)) return questions
def setUp(self): global survey survey = Survey() q = survey.add(Question(1, "Question1")) q.add(Answer(1, "answer1")) q.add(Answer(2, "answer2")) q = survey.add(Question(2, "Question2")) q.add(Answer(3, "answer3")) q.add(Answer(4, "answer4")) q.add(Answer(5, "answer5"))
def main(stdscr): # Clear stdscr.clear() curses.echo() # Show name and logo stdscr.addstr(1, 1, name, curses.A_BLINK) stdscr.addstr(7, 1, logo) stdscr.refresh() # Question window win = curses.newwin(10, 70, 10, 50) # Show instructions win.clear() win.addstr(1, 1, ( "Heu d'anar responent preguntes fins que n'encerteu {:d} seguides.\n" " Les preguntes es trien aleatoriament cada vegada que comenceu.\n" " Si falleu haureu d'esperar {:d} segons (aprofiteu aquest temps).\n" " Les respostes son una sola paraula o numero (sense espais)." "\n\n Premeu [Enter] per iniciar..." ).format(TOTAL_VALID, WAIT_TIME)) s = win.getstr(6, 1) # Start asking cho = Chooser(questions) valid = 0 while valid < TOTAL_VALID: # Start fresh win.clear() # Header win.addstr(1, 1, "Encertat {:d}/{:d}".format(valid, TOTAL_VALID)) # Ask q = Question(cho.choose(), win) ok = q.ask() if ok: valid += 1 # Show success win.clear() win.addstr(1, 1, "Correcte") win.refresh() time.sleep(2) else: cho.reset() valid = 0 # Sound print('\a') # bell alarm # Show fail and wait for i in range(WAIT_TIME): win.clear() win.addstr(1, 1, "Incorrecte. Espera {:d} segons...".format(WAIT_TIME - i)) win.refresh() time.sleep(1) # Winner win.clear() win.addstr(5, 1, "Heu superat el repte !!", curses.A_BLINK) win.refresh() time.sleep(10)
def parse(self, string): self._tokenize(string) if not self._tokens: return self question = Question() question.stem = self._tokens[0] question.options = self._tokens[1:] if len(self._tokens) > 1 else [] self._questions.append(question) return self
def test_duplicate(self): q = {'name': 'q2', 'text': 'Random question one, choose a.', 'answers': [{'value': 'a', 'text': 'a'}, {'value': 'b', 'text': 'b'}, {'value': 'c', 'text': 'c'},{'value': 'd', 'text': 'd'}] } question = Question(q) assert question.name == q['name'] and question.text == q['text'] and question.answers == q['answers'] question.save() try: question.save() except KeyError, e: print 'Trying to save duplicate: %s' % e
def test_illegal_keys(self): self.assertFalse(Question.iskey("")[0], "Empty string") self.assertFalse(Question.iskey(" ")[0], "Whitespace only") self.assertFalse(Question.iskey(" key")[0], "Leading whitespace") self.assertFalse(Question.iskey("end\t")[0], "Traling tabulation") self.assertFalse(Question.iskey("*$/\\")[0], "Non-alphanumeric characters") self.assertFalse(Question.iskey("end")[0], "Reserved keyword") self.assertFalse(Question.iskey("photoVisible")[0], "Reserved keyword") self.assertFalse(Question.iskey(32768)[0], "Not a string") self.assertFalse(Question.iskey("\n")[0], "Illegal escape character")
def questions(): form = NewQuestionForm(request.form) if request.method == 'POST' and form.validate(): question = Question(form.category.data, form.question.data, form.option_a.data, form.option_b.data, form.option_c.data, form.option_d.data, form.answer.data) question.save() flash('Question successfully created!', 'positive') return render_template('question_created.html', question=question, amount=Question.size()) elif request.method == 'POST' and not form.validate(): flash('Oops, your submitted question appears to be invalid.', 'negative') return render_template('question_new.html', form=form, amount=Question.size()) else: return render_template('invalid_request.html')
def accept_input(): content = request.args.get('content', '') number = request.args.get('from', '') # check for malicious URLs if url_check(content): print "This number is a spammer: %(number)s" % {"number": number} return if number == '447860033028': #no infinite loop 4 u return question = Question(content,number) question.ask() # debug statements below print("%(content)s from %(number)s." % {"content": question.message, "number": question.number}) return "%(content)s from %(number)s." % {"content": question.message, "number": question.number}
def ask(self, question, answer_type = str, **configs): self.question = Question(question, answer_type) self.answer = "" for key, value in configs.iteritems(): self.question.__dict__[key] = value if self.question.gather: return self.gather() self.say(self.question.question) # retry until the correct answer while True: try: self.answer = self.question.answer_or_default(self.get_response()) self.answer = self.question.change_case(self.answer) self.__class__(self.input, self.output) self.question.update() if not self.question.valid_answer(self.answer): self.explain_error("not_valid") raise QuestionError() self.answer = self.question.convert(self.answer) except QuestionError: pass else: self.question = None break return self.answer
def test_valid_keys(self): self.assertTrue(Question.iskey("A")[0], "Single-character") self.assertTrue(Question.iskey("thisIsALongKey")[0], "Multi-character") self.assertTrue(Question.iskey("--")[0], "Hyphens") self.assertTrue(Question.iskey("--key")[0], "Leading hyphens") self.assertTrue(Question.iskey("_")[0], "Underscores") self.assertTrue(Question.iskey("__key")[0], "Leading underscores") self.assertTrue(Question.iskey("_now-y0u_4re-pushing-1t")[0], "Mixed characters") self.assertTrue(Question.iskey("_end")[0], "Not a reserved keyword")
def onQuestion(self, msg): """ Gets called when a new question is received. The received question is then displayed in the GUI. """ self._answerLocked = False self.activeQuestion = Question.fromMsg(msg) self.ui.updateQuestion(self.activeQuestion)
def test_should_return_html_for_multi_line_answer_question(self): actual = Question.multi_line_answer("question") expected = '''\ <div id="1"> question <textarea rows=10 cols=30 id=1></textarea> </div> ''' self.assertEquals(HTMLReader(expected).to_s(), HTMLReader(actual).to_s())
def test_should_return_html_for_multi_choice_answer_question(self): actual = Question.multi_choice("question", "a1", "a2") expected = '''\ <div id="1"> question <input type=checkbox id="1_1">a1</input><input type=checkbox name="1_2">a2</input> </div> ''' self.assertEquals(HTMLReader(expected).to_s(), HTMLReader(actual).to_s())
def test_should_return_html_for_single_choice_question(self): actual = Question.single_choice("question", "a1", "a2") expected = '''\ <div id="1"> question <input type=radio name="1">a1</input><input type=radio name="1">a2</input> </div> ''' self.assertEquals(HTMLReader(expected).to_s(), HTMLReader(actual).to_s())
def test_should_return_html_for_single_line_answer_question(self): actual = Question.single_line_answer("question") expected = '''\ <div id="1"> question <input type="text" id=1></input> </div> ''' self.assertEquals(HTMLReader(expected).to_s(), HTMLReader(actual).to_s())
def __call__(self, qid): self.question = Question(qid) self.qid = int(qid) self.qtext = self.question.text #self.answer = self.question.answer #self.category = self.question.category #self.sentences = self.question.get_sentences() #self.tokens = self.question.tokenize() self.features = defaultdict(dict)
def parse(self, string): super(QuestParser, self).parse(string) regex = self._format(r"({i}{w}{body})({a}{w}{body})({b}{w}{body})({c}{w}{body})({d}{w}{body})?({e}{w}{ebody})?{lb}") self._tokenize(string) for token in [t.strip() for t in self._tokens if t]: question = Question() match = re.search(regex, token, re.DOTALL | re.IGNORECASE) if match: question.stem = match.group(1).strip() question.options.append(match.group(2).strip()) question.options.append(match.group(3).strip()) question.options.append(match.group(4).strip()) if match.group(5): question.options.append(match.group(5).strip()) if match.group(6): question.options.append(match.group(6).strip()) self._questions.append(question) return self
def jsubmit(question_id): hs = Historysession.get_current_history_session_by_user_id_quiz_id(current_user.id) session_id = hs.hsid current_app.logger.debug("jsubmit - " + str(question_id) + ", session_id - " + str(session_id)) current_app.logger.debug("json in jsubmit - " + str(request.json)) question = Question.get_active_question_by_id(question_id) if question: if current_user.id == question.user_id: schema = { "type" : "object", "properties" : { "id" : {"type" : "integer", "maxLength" : 8, "optional" : False}, "answers" : {"type": "array", "items": { "type" : "object", "properties": { "id" : {"type": "integer", "maxLength": 8, "optional": False}, "value" : {"type" : "string", "enum" : ["T", "F", "N"], "optional" : False} }}, "maxItems" : 25, "optional" : True} } } v = Draft4Validator(schema) errors = sorted(v.iter_errors(request.json), key=lambda e: e.path) if len(errors) > 0: msg = u"Error in json format" current_app.logger.warning(msg) return jsonify({"status" : "ERROR", "message" : msg}) else: qid = request.json['id'] received_answers = request.json['answers'] correct = True for i in range(0, len(received_answers)): item = received_answers[i] aid = item['id'] value = item['value'] AnswerResult.add_answer_result(session_id, aid, question.revision_id, value) correct = correct and (value == question.answers[i].correct) current_app.logger.debug("a# = " + str(i) + ", value = " + str(value) + ", answer = " + str(question.answers[i].correct) + ", correct = " + str(correct)) QuestionResult.add_question_result(session_id, question.qid, question.revision_id, correct) db.session.commit() result = {'jstaus':'OK'} return jsonify(result) else: msg = auth_failure_message + u"submit this question" current_app.logger.warning(msg) return jsonify({"status" : "ERROR", "message" : msg}) else: return jsonify({"status" : "ERROR"})
def markdown_questionlist(qlist): qlist.formatted_questions = [] for q in qlist.questions: if isinstance(q,Question): question = q else: question = Question.get(q) if question: question.formatted_text = mymarkdown(question.text) qlist.formatted_questions.append(question)
def refresh_chapter(chapter): chapter.refresh = True chapter.put() query = Question.all().filter('chapter =', chapter) for q in query.run(): q.refresh = True q.put query = Chapter.all().ancestor(chapter.key()) for c in query.run(): if c != chapter: refresh_chapter(c)
def get_default_question_objects(): """ Creates a list which is returned, this is to be used as default option in the list ```question_objects_list``` Returns: list: A list with default question objects """ question_list = list() question1 = Question(0, 'Choose A, B or C', False) question1.add_alternative(0, 'A', True) question1.add_alternative(1, 'B', False) question1.add_alternative(2, 'C', False) question_list.append(question1) question2 = Question(1, 'Choose D, E or F', False) question2.add_alternative(0, 'D', False) question2.add_alternative(1, 'E', False) question2.add_alternative(2, 'F', True) question_list.append(question2) return question_list
def __init__(self): # Set up a clock for managing the frame rate. self.clock = pygame.time.Clock() self.x = -100 self.vx = 10 self.paused = False self.direction = -1 self.circle_size = 150 self.horse_change_semaphore = 3 self.horse_change = 0 self.font = pygame.font.SysFont('monospace', 36) self.lg_font = pygame.font.SysFont('monospace', 60) self.xlg_font = pygame.font.SysFont('monospace', 90) self.hurdle_number = 0 self.points = 0 self.question = Question() self.question_text_label = self.lg_font.render( str(self.question), 1, Color.BLACK ) self.question_label = self.font.render( 'Hurdle #' + str(self.hurdle_number), 1, Color.BLACK ) self.score_label = self.lg_font.render( str(self.points), 1, Color.BLACK ) self.buttons = [] self.songs = [ self.get_sound_path('william_tell_overture_intro.wav'), self.get_sound_path('william_tell_overture_race.wav') ] self.death_sfx = pygame.mixer.Sound(self.get_sound_path('sad_trombone.wav')) self.jump_sfx = pygame.mixer.Sound(self.get_sound_path('success.wav'))
def parse(self, string): question = None self._tokenize(string) for token in self._tokens: s = re.match(r"^\s*\d+\.\s", token) if s and s.group(): if question and len(question.options) > 0: self._questions.append(question) question = Question() question.stem = token continue if question is not None: o = re.match(r"^\s*[\[\(]?[a-zA-Z][.):\]]\s", token) if o and o.group(): question.options.append(token) if question and len(question.options) > 0: self._questions.append(question) return self
def save_question(self, data, suffix=''): """ Adds question to question collection stored in ``QuestionController`` class. :param data: JSON object that contains question in a format: data = { 'id': 1, 'text': 'Text', 'alternatives': [ { 'id': '1', 'text': 'Text', 'isCorrect': 'false' }, { 'id': '2', 'text': 'Text2', 'isCorrect': 'false' }, ... ], 'hasDifficultyLevel': 'false' } :param suffix: :return: JSON object with the size of questions collection and last added question """ try: q_id = int(data['id']) q_text = data['text'] if data['hasDifficultyLevel']: q_has_diff_lvl = True else: q_has_diff_lvl = False new_question = Question(q_id, q_text, q_has_diff_lvl) for i in range(0, len(data['alternatives'])): # TODO: Note that the called function in CreatedAnswers throws error # TODO: See comment in Question::add_alternative if not new_question.add_alternative(i, data['alternatives'][i]['text'], data['alternatives'][i]['isCorrect']): return {'status': 'Not saved', 'message': 'Alternative is not valid'} if new_question.is_valid: if q_id < 0: new_question.set_question_id(len(self.questions_json_list)) self.questions_json_list.append(new_question.to_json()) else: for i in range(0, len(self.questions_json_list)): if self.questions_json_list[i]['id'] == q_id: del self.questions_json_list[i] self.questions_json_list.insert(i, new_question.to_json()) num_questions = len(self.questions_json_list) question = self.questions_json_list[num_questions - 1] return {'status': 'successful', 'numQuestions': num_questions, 'question': question} else: return{'status': 'unsuccessful', 'message': 'Question data is not valid'} except Exception as ex: return {'status': 'unsuccessful', 'message': str(ex)}
def create_object_from_json(self): """ Creates a list of Question objects from the JSON dictionary questions_json_list Returns: list: List containing objects of the class Questions """ question_list = list() # loop through all the json questions and add them to the list for json_question in self.questions_json_list: q_id = json_question['id'] q_text = json_question['question'] q_diff_lvl = json_question['has_difficulty_level'] question = Question(q_id, q_text, q_diff_lvl) # loop through all the alternatives for this question and add them for alt in json_question['alternatives']: a_id = alt['id'] a_text = alt['text'] a_is_correct = alt['isCorrect'] question.add_alternative(a_id, a_text, a_is_correct) # add the question object to the list question_list.append(question) return question_list