def match(data): matched_user = User.find_closest_rating(data['choice'], data['rating'], data['username']) if matched_user.is_authenticated: print("He is online!") new_question = Question(data['question'], "", current_user.name, data['choice']) new_question.save() for value in data['tags']: if value is not None: print(value) new_tag = Tag(value) new_tag.save() new_question_tag = Question_tag(new_question.id, new_tag.id) new_question_tag.save() chat_id = str(uuid.uuid1()) print("NEW CHAT ID IS {}".format(chat_id)) print("You are {}".format(matched_user.name)) print("I am {}".format(current_user.name)) emit('question_match', { 'question': data['question'], 'user_id': current_user.id, 'matched_user_id': matched_user.id, 'chat_id': chat_id }, room=matched_user.room_id) else: flash('No matches available. Try again!') print("No luck today!")
def quiz1(): return [ Question("what is the dog's name", { 'A': 'Jack', 'B': 'Jango' }, ['A']), Question("what is the cat's name", { 'A': 'Jack', 'B': 'Jango' }, ['B']) ]
def quiz2(): return [ Question("what is the car's color", { 'A': 'Blue', 'B': 'Black' }, ['A']), Question("what is the house's color", { 'A': 'White', 'B': 'Brown' }, ['B']) ]
def answer_question(self, question_str): question = Question() question.set_question(question_str) question = self.__question_classifier.classify(question) logging.info('开始处理Question:' + question.get_question() + '问题类型:' + str(question.get_question_type())) if question.get_question_type() == QuestionType.Open: return self.tl_chat(question_str) if question.get_question_type() != QuestionType.Solution: question = self.kb_based_answer_question(question) else: question = self.ir_based_answer_question(question) logging.info('候选答案: ' + question.get_expect_answer()) return question.get_expect_answer()
def ask(): print(current_user.name) if current_user.choice == 'Hasn\'t chosen': return redirect(url_for('choice')) return render_template("ask.html", user=current_user, questions=Question.find_by_user(current_user.name))
def manager(self): manager = Manager() conn = sqlite3.connect('data/database.db') cursor = conn.cursor() cursor.execute( 'SELECT subject.id, name, question, correct_alternatives.texto, wrong_alternatives.texto FROM subject ' 'LEFT JOIN question ON subject.id = question.id_subject ' 'LEFT JOIN correct_alternatives ON question.id = correct_alternatives.id_question ' 'LEFT JOIN wrong_alternatives ON question.id = wrong_alternatives.id_question;') data = cursor.fetchall() for k in range(0, len(data), 12): questions = [] for i in range(k, k + 12, 3): _, subject_name, question, correct_answer = data[i][:-1] alternatives = [] for j in range(i, i + 3): alternatives.append(data[j][-1]) random.shuffle(alternatives) right_post = random.randint(0, 3) alternatives.insert(right_post, correct_answer) questions.append(Question(question, alternatives, right_post)) subject_id = Generator() q = Quiz(subject_id, questions) manager.subjects[subject_id] = Subject(subject_id, data[k][1], q) return manager
def add_answer(self, question_id, source, author): question = Question.get_by_id(int(question_id)) if not question or not source: self.set_error_code(500) return #TODO: if answer is added by anonymouse, author should be set to None, # real_author is always set.(eg. question_relationship = get_relationshiop(question)) new_answer = Answer( parent = question.key, summary = source[0:100], question = question.key, author = author.key, real_author = author.key, content = source.replace("\n", "<br />"), source = source) new_answer.put() relation = AccountQuestionRelationService().get_relationship(author.key, question.key) relation.my_answer = new_answer.key relation.put() QuestionService().update_answer_num(question.key) return new_answer
def set_no_help(self, actor, question_id, answer_id): question = Question.get_by_id(int(question_id)) answer = Answer.get_by_id(parent = question.key, id = int(answer_id)) relation = AccountQuestionRelationService().get_relationship(actor.key, question.key) if not answer.key in relation.no_help_answers: relation.no_help_answers.append(answer.key) relation.put()
def from_mongo(cls, mongo_questions: Dict): qid: str = mongo_questions["qid"] questions: List[Question] = [ Question(question, qid) for question in mongo_questions["questions"] ] return cls(mongo_questions["qid"], questions, mongo_questions["answers"])
def addQuestion(): # html文件修改为新建题目的文件 if request.method == "GET": return render_template("提交题目.html") elif request.method == "POST": req = request.values # 暂时略过合法性检测 questionInfo = req['questionInfo'] answer = req['answer'] diseaseName = req['diseaseName'] score = req['score'] choiceA = req['choiceA'] choiceB = req['choiceB'] choiceC = req['choiceC'] choiceD = req['choiceD'] questionInfoD = Question.query.filter_by( questionInfo=questionInfo).first() if questionInfoD: return ops_renderErrJSON(msg="相同题干已存在,请再换一个试试") # 注册写入数据库 model_question = Question() model_question.questionInfo = questionInfo model_question.choiceA = choiceA model_question.choiceB = choiceB model_question.choiceC = choiceC model_question.choiceD = choiceD model_question.answer = answer model_question.score = score model_question.diseaseName = diseaseName db.session.add(model_question) db.session.commit() # json化data temp = {} temp["questionInfo"] = questionInfo temp["answer"] = answer temp["choiceA"] = choiceA temp["choiceB"] = choiceB temp["choiceC"] = choiceC temp["choiceD"] = choiceD temp["score"] = score temp["diseaseName"] = diseaseName data = [] data.append(temp) return ops_renderJSON(msg="添加成功", data=data) return "添加成功"
def create(cls, question_id, user_email, comment, **__): question = Question.get(question_id, user_email) command = DB.comments.insert( dict( q_id=question_id, owner_email=user_email, content=comment, score=0, )) DB.ex(command) User.get(user_email) # forces a user check / creation question = Question.get(question_id, user_email) ## increment comment count comments = Comment.get_all_for_question(question, override_auth=True) return { "question": question, "comments": comments, }
def get_questions() -> 'list[Question]': with open('encrypted-questions/encrypted-questions.json', encoding='utf-8-sig') as file_json: dictQuestions: list[dict] = json.load(file_json) questions = [] # type: list[Question] for x in dictQuestions: questions.append(Question(x)) return questions
def remove_answer_from_question(self, question_id, answer_id): question = Question.get_by_id(int(question_id)) if not question: return answer = Answer.get_by_id(int(answer_id), parent = question.key) if not answer: return answer.key.delete() self.update_answer_num(question.key) return question
def we_have_the_following_quizes(context): questions = {} for row in context.table: question_set_id = row['question_set_id'] question = row['question'] options = ast.literal_eval(row['options']) expected_answers = ast.literal_eval(row['expected_answers']) if question_set_id in questions: questions[question_set_id].append( Question(question, options, expected_answers)) else: questions[question_set_id] = [ Question(question, options, expected_answers) ] for key, value in questions.items(): print("Quiz {}".format(key)) print("\nQuestions:\n%s" % ('\n'.join( str(question) for question in value))) context.questions = questions pass
def add_question(self, question: Question): # if there are no categories, add one if not self._train_data: question.qid = question.question self._questions_database.add_question_category(question.qid) else: # use classifier self._classifier_lock.acquire() qid: str = self._classifier.classify(question.question.lower()) self._classifier_lock.release() similarity_percentage: float = self._fuzzy_check( question.question.lower(), qid) if similarity_percentage >= self._pass_percentage: question.qid = qid else: question.qid = question.question self._questions_database.add_question(question)
def ask_qna(users_database: UserDatabase, questions_database: QuestionsDatabase, immediate_subsystem: ImmediateSubsystem, qna_subsystem: QNASubsystem): user_id = request.get_json().get("UserIdentifier") user: User = User.from_user_id(user_id) user: User = users_database.find_user(user) message: str = request.get_json().get("CurrentInput") question: Question = Question(message) qna_subsystem.ask_question(user, question) return Response(status=200)
def answer_question(self, question_str): question = Question() question.set_question(question_str) question = self.__question_classifier.classify(question) logging.info('开始处理Question:' + question.question_string + question.question_type.value) logging.info(question.body + question.medicine + question.disease) if question.question_type == QuestionType.Medicine: answer = self.kb_based_answer_question(question) if not answer: answer = self.ir_based_answer_question(question) elif question.question_type == QuestionType.Definition \ and len(question.body+question.medicine+question.disease) == 1: answer = self.baike_based_answer_question( (question.body + question.medicine + question.disease)[0]) if not answer: answer = self.ir_based_answer_question(question) else: answer = self.ir_based_answer_question(question) del question logging.info('候选答案: ' + answer) return answer
def search_by_tags(tags): with SQLite() as db: query = ''' SELECT DISTINCT q.content, q.answer, q.user, q.category, q.id FROM question as q JOIN question_tag as qt on qt.question_id = q.id JOIN tag as t on t.id = qt.tag_id where t.content IN ({}) '''.format(", ".join("?" for _ in tags)) result = db.execute(query, tags) questions = result.fetchall() if questions is None: return [] return [Question(*q) for q in questions]
def voteup_answer(self, actor, question_id, answer_id): question = Question.get_by_id(int(question_id)) answer = Answer.get_by_id(parent = question.key, id = int(answer_id)) relation = AccountQuestionRelationService().get_relationship(actor.key, question.key) if answer.key in relation.up_voted_answers: relation.up_voted_answers = [ a for a in relation.up_voted_answers if a != answer.key ] answer.up_voted_users = [ u for u in answer.up_voted_users if u != actor.key ] else: relation.up_voted_answers.append(answer.key) answer.up_voted_users.append(actor.key) relation.down_voted_answers = [ a for a in relation.down_voted_answers if a != answer.key ] answer.down_voted_users = [ u for u in answer.down_voted_users if u != actor.key ] answer.put() relation.put()
def update_answer(self, question_id, answer_id, source): current_question = Question.get_by_id(int(question_id)) if not current_question: return answer = Answer.get_by_id(int(answer_id), parent = current_question.key) #TODO: raise 404 error. if not answer: return #TODO: filter desc content using hlper method. content = source.replace("\n", "<br />") answer.content = content answer.source = source answer.put()
@staticmethod def get_evidence(question_str): logging.info('获取支持证据开始') evidences = [] elements = WhooshDataSource.index_open(question_str) for item in elements: evidence = CqaEvidence() evidence.set_question(item[0]) evidence.set_snippet(item[1]) evidences.append(evidence) logging.info('获取支持证据结束') return evidences if __name__ == '__main__': a = Question() que_list = [ '我今天吃了一个麻辣烫,很辣很热,到了晚上肚子疼,闹肚子,想吐,要怎么办', # '牙疼,牙龈红肿肿胀,口角气泡,牙龈经常出血怎么办', # '感冒,发烧流鼻涕,昨天还咳嗽,天气太冷了,怎么办', # '昨天吃西瓜,今天拉肚子了,不停怎么办,有什么方法', '昨天骑车摔倒了,腿磕破了,有点出血很痛' ] conn = mysql.connector.connect(**mqa_config.MYSQL) cursor = conn.cursor() for i in que_list: b = WhooshDataSource.index_open(i) print(b) c = WhooshDataSource.index_open_mysql(cursor, i) print(c)
def question1(): return Question("what is the dog's name", { 'A': 'Jack', 'B': 'Jango' }, ['A'])
def save_answer(data): print("save_answer") user = User.find_by_name(str(data['username'])) question = Question.find_most_recent_by_user(user.match) print(question.content) Question.update_answer_by_content(str(data['answer']), question.content)
def display_question(data): print("display") user = User.find_by_name(str(data['username'])) question = Question.find_most_recent_by_user(user.match) emit('display', {'question': question.content})
def decline_question(self, declining_user: User): asking_user: User = self._users_database.find_user(User.from_user_id(declining_user.asking_user_id)) self.ask_question(asking_user, Question(declining_user.asked_question), 1, [declining_user], True) self._users_database.update_user(declining_user, {"answer_qid": None, "asking_user_id": None, "asked_question": None})
def test_that_question_with_wrong_expected_answers_list_raises_exception(): with pytest.raises(Exception): Question("what is the cat name", {'A': 'Jack', 'B': 'Jango'}, ['D'])
def focus_question_(self, is_focus, account_key, question_id): question = Question.get_by_id(int(question_id)) relation = AccountQuestionRelationService().get_relationship(account_key, question.key) relation.focused = is_focus relation.put()
def add_question(self, question: str): quest: Question = Question(question, self.qid) self.questions.append(quest) return quest
def cancel_no_help(self, actor, question_id, answer_id): question = Question.get_by_id(int(question_id)) answer = Answer.get_by_id(parent = question.key, id = int(answer_id)) relation = AccountQuestionRelationService().get_relationship(actor.key, question.key) relation.no_help_answers = [ a for a in relation.no_help_answers if a != answer.key ] relation.put()
def get_answers_by_question_id(self, question_id): #don't need call entity service for single get operation question = Question.get_by_id(int(question_id)) answers = Answer.query(ancestor = question.key).fetch() return answers
def add_question(self, question_title, answers): self.questions.append(Question(question_title, answers))
:param question_a: 问题类 """ logging.info('问句相似度开始') question1 = question_a.word_list question2 = question_b.word_list class_score = class_sim(question_a.question_type, question_b.question_type) key_score = key_sim(question_a, question_b) wmd_score = wmd_sim(question1, question2) # semantic_score = semantic_sim(question1, question2) word_score = word_sim(question1, question2) order_score = order_sim(question1, question2) char_tfidf_score = char_tfidf_sim(question_a.question_string, question_b.question_string) score = weights['class_weight']*class_score + weights['key_weight']*key_score + weights['wmd_weight']*wmd_score + \ weights['word_weight']*word_score + weights['order_weight']*order_score + \ weights['char_tfidf_weight']*char_tfidf_score logging.info('问句相似度结束,得分为{}\n\n'.format(score)) return score if __name__ == '__main__': q = Question() q.set_question('感冒了怎么办') que = input() while que != 'end': q2 = Question() q2.set_question(que) # q.set_question_type(QuestionType.Doctor) combination_sim() que = input()
from typing import Optional from fastapi import FastAPI from model.answer import Answer from model.question import Question app = FastAPI() db = {} db[1] = Question(1, 'BMW', [ Answer(1, 'England', False), Answer(2, 'USA', False), Answer(3, 'Germany', True), Answer(4, 'Japan', False) ]) db[2] = Question(2, 'Toyota', [ Answer(1, 'England', False), Answer(2, 'USA', False), Answer(3, 'Germany', False), Answer(4, 'Japan', True) ]) db[3] = Question(3, 'Mini', [ Answer(1, 'England', True), Answer(2, 'USA', False), Answer(3, 'Germany', False), Answer(4, 'Japan', False) ]) db[4] = Question(4, 'General Motors', [ Answer(1, 'England', False),
def archive(): return render_template("archive.html", questions=Question.all_questions())
def get(cls, question_id, comment_id, user_email, **__): Question.get(question_id, user_email) # forces a permission check comment_command = DB.comments.select( (DB.comments.columns.id == comment_id) & (DB.comments.columns.q_id == question_id)) return r2d(DB.ex(comment_command).fetchone())
def delete_question(self, question_id): question = Question.get_by_id(int(question_id)) if not question: return question.key.delete()
def question3(): return Question("what is the bird's name", { 'A': 'Jack', 'B': 'Mark' }, ['B'])
def list_questions(): result = [] for question in Question.all(): result.append(question.to_dict()) return jsonify(result), 201
def add_question_category(self, qid: str): question_category: QuestionsCategory = QuestionsCategory( qid, [Question(qid, qid)], []) self._collection.insert_one(question_category.to_mongo())
def add_question(text): session = db.Session() question = Question(text=text) session.add(question) session.commit() return question.format()