async def organize(self, ctx, quiz_type: str = None, team_size: str = None): if ctx.channel.name != text(CHANNEL_SETUP): return if quiz_type not in ['normal', 'jeopardy', 'only connect']: quiz_type = 'normal' if not team_size: team_size = 2 team_size = min(max(int(team_size), 2), 8) self._quiz = Quiz(quiz_type, ctx.message.author, team_size) self._quiz_message = await ctx.send(self._quiz.organization_text()) await self._quiz_message.add_reaction(EMOJI_OK) await self._quiz_message.add_reaction(EMOJI_ACCEPT) await self._quiz_message.add_reaction(EMOJI_DECLINE) try: for team_id in range(1, team_size + 1): role = await self._management.get_or_create_role('Team ' + str(team_id)) team = Team(role, team_id) self._quiz.add_team(team) await self._quiz_message.add_reaction(EMOJI_TEAM[team_id - 1]) except Exception as e: print(e) await ctx.message.delete()
def settings(): if not current_user.is_authenticated: flash('Please Login to continue..') return redirect('/login') user = current_user form = SettingsForm() form.name.render_kw = {'placeholder': user.name} form.username.render_kw = {'placeholder': user.username} form.email.render_kw = {'placeholder': user.email} if request.method == 'GET': if request.path == '/settings/delete': return render_template('confirm_remove.html') return render_template('settings.html', user=user, form=form) elif request.method == 'POST': if request.path == '/settings/delete': Quiz.remove_player(user.username) flash('Sorry to see you go :(') flash('You will be missed..') return redirect('/') if form.validate(): if form.name.data.strip() and user.name != form.name.data.strip(): user.name = form.name.data.strip() form.name.render_kw = {'placeholder': form.name.data} user.update_user_info() flash('Name Updated Successfully!') if form.username.data.strip( ) and user.username != form.username.data.strip(): user.username = form.username.data.strip().lower() form.username.render_kw = { 'placeholder': form.username.data.strip().lower() } user.update_user_info() flash('Username Updated Successfully!') if form.email.data.strip( ) and user.email != form.email.data.strip(): user.email = form.email.data.strip().lower() form.email.render_kw = { 'placeholder': form.email.data.strip().lower() } user.update_user_info() flash('Email Address Updated Successfully!') if form.password.data and len( form.password.data) in [i for i in range(8, 17)]: user.password = form.password.data user.update_user_info(settings=True) flash('Password Updated Successfully!') form.email.data = form.name.data = form.username.data = "" return render_template('settings.html', user=user, form=form) return render_template('404.html')
def put(self, quiz_id): session = authorize(request.headers["Authorization"]) put_request = Quiz.quiz_from_dict(put_parser.parse_args()) criteria = { "createdBy": session.get('user').get('login'), "_id": int(quiz_id) } quiz = Quiz.quiz_from_dict(mongo.db.quiz.find_one_or_404(criteria)) for qst in put_request.questions: self.add_question(qst, quiz) return {"message": "modified % s" % quiz_id}, 200
def test_question_model(self): """Test basic question model""" q = Quiz(num_questions=10, family='Test2 family') db.session.add(q) for i in range(10): question = Question(url='test_url', correct_answer='right answer', wrong_answer_1='wrong one', wrong_answer_2='wrong too', wrong_answer_3='wrong 3', slug='test-slug') q.questions.append(question) db.session.commit() qq = q.questions[0] self.assertEqual(len(q.questions), 10) self.assertEqual(qq.url, 'test_url') self.assertEqual(qq.correct_answer, 'right answer') self.assertEqual(qq.wrong_answer_2, 'wrong too') self.assertEqual(qq.search_slug, 'test+slug') self.assertEqual(len(Question.query.all()), 30) self.assertEqual( len(Question.query.filter(Question.url == 'test_url').all()), 10) self.assertEqual(len(qq.part_of), 1) self.assertEqual(qq.part_of[0].id, q.id)
def post(self, quiz_id, contact_group=None): session = authorize(request.headers["Authorization"]) if contact_group is None: contact_group = "default" contacts = self.get_contacts(contact_group, session.get("user").get("login")) if contacts is None: return {"message": "no contact to send"}, 400 criteria = {"createdBy": session.get('user').get('login'), "_id": int(quiz_id)} quiz = Quiz.quiz_from_dict(mongo.db.quiz.find_one_or_404(criteria)) for contact in contacts: c = Contact.contact_from_dict(contact) p = Publication() p._id = get_id("publication") p.creationDate = datetime.now() p.hash = hashlib.sha256("%d.%s" % (p._id, str(p.creationDate))).hexdigest() p.by = session.get('user').get('login') p.quiz = quiz p.to = c mongo.db.publications.insert(p.format()) self.send_email(quiz.title, p.hash, c.email, c.language) return {"message": "quiz %s published to %d contacts" % (quiz.title, len(contacts))}, 200
def test_quiz_can_be_added(self): self.test_quiz_2 = Quiz("2020-02-02", 10, "MEDIUM", "Geography", []) self.assertEqual("2020-02-02", self.test_quiz_2.date) self.assertEqual(10, self.test_quiz_2.number_of_questions) self.assertEqual("MEDIUM", self.test_quiz_2.difficulty) self.assertEqual("Geography", self.test_quiz_2.topic) self.assertEqual([], self.test_quiz_2.question_list)
async def load_quiz(self, ctx): io = BytesIO() await ctx.message.attachments[0].save(io) with session_scope() as session: instances = [Quiz(**instance) for instance in json.load(io)] session.add_all(instances) await ctx.send(f"`{len(instances)}`개 데이터를 추가했습니다.")
def player_dashboard(pid=None): if current_user.is_authenticated and current_user.is_admin: players = User.get_all_users() if request.path == '/admin/dashboard/Players/view': return render_template('view_players.html', players=players) elif pid and len(pid) < 100 and (pid.replace('-', '').isalnum() or pid.replace('_', '').isalnum()): if not User.get_user_info(username=pid): flash('Can\'t find player') return redirect('/admin/dashboard/Players/view') if request.method == "POST": Quiz.remove_player(pid) flash('Player Removed!') return redirect('/admin/dashboard/Players/view') return render_template('remove_player.html', players=players) return render_template('view_players.html', players=players) return render_template('404.html')
def select_all(): quizzes = [] sql = "SELECT * FROM quizzes" results = run_sql(sql) for result in results: difficulty = difficulty_repository.select(result["difficulty_id"]) topic = topic_repository.select(result["topic_id"]) quiz = Quiz(result["date"], result["number_of_questions"], difficulty, topic, result["question_list"], result["id"]) quizzes.append(quiz) return quizzes
def select(id): quiz = None sql = "SELECT * FROM quizzes WHERE id = %s" values = [id] result = run_sql(sql, values)[0] difficulty = difficulty_repository.select(result["difficulty_id"]) topic = topic_repository.select(result["topic_id"]) if result is not None: quiz = Quiz(result["date"], result["number_of_questions"], difficulty, topic, result["question_list"]) return quiz
def create_quiz(self, source, difficulty=None, category=None, max_questions=None): """creates a new quiz and adds it to the store""" # Get the lowest available code code = 1 if len(self.questions) is not 0: code = max([quiz.code for quiz in self.quizes.values()]) + 1 new_quiz = Quiz(source, code, difficulty, category, max_questions) self.quizes[new_quiz.quiz_id] = new_quiz return new_quiz.quiz_id
def add_questions(file_path, family): """Add new quizzes to existing database from CSV of questions""" with open(f'{file_path}', newline="") as csvfile: questions = DictReader(csvfile) count = 0 for question in questions: if count % 10 == 0: new_quiz = Quiz(family=family, num_questions=10) db.session.add(new_quiz) new_question = Question(**question) new_quiz.questions.append(new_question) db.session.add(new_question) count += 1 db.session.commit()
def play_quiz(qid=None): form = Play() if not current_user.is_authenticated: flash('Please Login for playing Quiz..') return redirect('/login') if request.method == "POST": if form.validate(): if question := Quiz.get_question(form.qid.data): if Quiz.attempt_question(current_user, form.ans.data, question): session['score'] += 10 return redirect('/play') else: return redirect('/final_score') return render_template('404.html') else: errors = [] errors.append(form.qid.errors) errors.append(form.ans.errors) errors.append(form.current_score.errors) errors.append(form.correct_ans.errors) if qid: return redirect('/play/') return str(errors)
def test_next_question_causes_finish(): Quiz.max_time_in_seconds = 0.1 quiz = Quiz(FakeSource, 1234, "easy", "9", None) quiz.start() for _ in range(10): sleep(0.1) quiz.next_question() assert quiz.is_finished
def update_quiz(id): date = request.form["date"] number_of_questions = request.form["number_of_questions"] difficulty_id = request.form["difficulty_id"] difficulty = difficulty_repository.select(difficulty_id) topic_id = request.form["topic_id"] topic = topic_repository.select(topic_id) question_list = request.form["question_list"] quiz = Quiz(date, number_of_questions, difficulty, topic, question_list, id) quiz_repository.update(quiz) return redirect("/quizzes")
def test_quiz_model(self): """Test basic quiz model""" q = Quiz(num_questions=10, family='Test2 family') db.session.add(q) db.session.commit() self.assertEqual(len(q.questions), 0) self.assertEqual(q.num_questions, 10) self.assertEqual(q.family, 'Test2 family') self.assertEqual(len(Quiz.query.all()), 3) self.assertEqual( len(Quiz.query.filter(Quiz.family == 'Test2 family').all()), 1) self.assertEqual( len(Quiz.query.filter(Quiz.family == 'test family').all()), 2) self.assertEqual(q.num_by_family, 1)
def patch(self, quiz_id): session = authorize(request.headers["Authorization"]) patch_request = Quiz.quiz_from_dict( patch_parser.parse_args()).format_patch() if len(patch_request) == 0: abort(400) criteria = { "createdBy": session.get('user').get('login'), "_id": int(quiz_id) } mongo.db.quiz.find_one_or_404(criteria) mongo.db.quiz.update(criteria, {"$set": patch_request}) return {"message": "modified % s" % quiz_id}, 200
def post(self): session = authorize(request.headers["Authorization"]) quiz_input = creation_parser.parse_args() quiz = Quiz.quiz_from_dict(quiz_input) quiz.creationDate = datetime.now() quiz.createdBy = session.get('user').get('login') """ we create the quiz first """ quiz._id = int(get_id("quiz")) print "\n", quiz.format() mongo.db.quiz.insert(quiz.format()) """ we create questions as objects and we embbed them into the quiz""" for qst in quiz.questions: self.add_question(qst, quiz) return {"quiz_id": "%s" % (quiz._id)}, 201
def test_next_question(): Quiz.max_time_in_seconds = 0.1 quiz = Quiz(FakeSource, 1234, "easy", "9", None) quiz.start() start_question = quiz.current_question sleep(0.1) quiz.next_question() second_question = quiz.current_question assert start_question is second_question - 1
def create_quiz(): date = request.form["date"] number_of_questions = request.form["number_of_questions"] difficulty_id = request.form["difficulty"] difficulty = difficulty_repository.select(difficulty_id) topic_id = request.form["topic"] topic = topic_repository.select(topic_id) for question in number_of_questions: question_list.append(question) return question_list new_quiz = Quiz(date, number_of_questions, difficulty, topic, question_list) quiz_repository.save(new_quiz) return redirect("/quizzes")
def new_quiz(): """Create new quiz, available to users who have taken enough quizzes.""" if not g.user.is_new_quiz_eligible(): num = g.user.num_quizzes_created*10 + 10 - len(g.user.quizzes) flash(f"Take {num} more quizzes to create new quiz.") return redirect('/') form = QuizCreationForm() if form.validate_on_submit(): quiz = Quiz.create(form.family.data) if quiz: quiz.created_by = g.user.username g.user.num_quizzes_created += 1 db.session.commit() flash("Quiz successfully created!", "success") return redirect(f'/quiz/{quiz.id}') else: flash("Something went wrong. Please try again later.") return render_template('create_quiz.html', form=form)
def create_office_online(self): module = Module( 'onedrive-and-office-online', 'One Drive & Office Online', 'In this introduction to OneDrive and Office Online, pupils will learn to create, edit, save and upload documents in the cloud so that they can <b>create and edit documents from school or home</b>.', 'one-drive-office-online') lesson1 = Lesson( 'onedrive-and-office-online', 1, 'OneDrive & Office online', 'How to create, edit, save, upload and access documents using OneDrive and Office Online', 'None', 'None') lesson1.setLearningObjectiveIds('ss02', 'oo02*') lesson1.starter = """ <ul> <li>Work in groups of 2's or 3's</li> <li>Take one piece of paper per group.</li> <li>Discuss and identify 3 difficulties of <b>using thumb drives</b></li> </ul>""" lesson1.resources = [ { 'url': '', 'text': 'Lesson Slides' }, { 'url': '', 'text': 'Cheat Sheet' }, ] q1 = Quiz('q1', 'Using OneDrive?') q1.add_question(0, 'What is OneDrive?', [ 'A house with one drive', 'A software service that can store files.' ], [False, True]) q1.add_question(1, 'Which software company creates OneDrive?', ['Microsoft', 'BISAK', 'Google', 'DropBox'], [True, False, False, False]) q2 = Quiz('q2', 'Uploading Files.') q2.add_question(0, 'Test Question 1?', ['Answer 1', 'Answer 2.'], [False, True]) q2.add_question(1, 'Test Question 2?', ['Answer 1', 'Answer 2.'], [True, False]) lesson1.addActivities( Activity( 10, 'Starter', """ <h2>In pairs, create a list of the issues you may face when you use a thumbdrive to transport files to and from home.</h2> """), VideoActivity( 10, 'What is OneDrive?', 'https://www.dropbox.com/s/tkjpefa581rsibg/Internet%20Safety%20-%20Newsround%20Caught%20In%20The%20Web%20%289%20Feb%202010%29.mp4?raw=1' ), QuizActivity(10, 'What is OneDrive?', q1), Activity(15, 'Uploading and locating files in the Cloud.', content=""), QuizActivity(10, 'Test Quiz?', q2), Activity(0, '(Extension) What is OneDrive Version History?', content=""), RateProgressActivity(5, 'Rate your progress'), RecapActivity(10, 'Recap'), LoPuActivity(5, 'LoPu') #, # QuizItem ('00:45', f"CFU: {tlQuiz.title}", tlQuiz), # TimelineItem('00:50', BringItAllTogetherItem('Bring It All Together'), # TimelineItem('00:54', RateYourProgressItem('Rate Your Progress'), # TimelineItem('00:57', NailItDown('Nail It Down'), # TimelineItem('00:59', LOPU()), ) lesson1.homework = """From `vle""" module.add_lesson(lesson1) self.modules[module.id] = module
from json import load from models.quiz import Quiz content = load(open('json_quiz.json')) for question in content: Quiz(question=question.get('question'), options=question.get('options'), answer=question.get('answer')).save_quiz()
class QuizBot(commands.Cog): def __init__(self, bot): self._bot = bot self._guild = None self._management = None self._quiz_message = None self._quiz = None bot.add_cog(self) # Private async def _setup(self): # Create organization category or get the existing handle organization = await self._management.get_or_create_category( text(CHANNEL_CATEGORY)) await self._management.get_or_create_text_channel( text(CHANNEL_LOBBY), organization) await self._management.get_or_create_voice_channel( text(CHANNEL_LOBBY), organization) await self._management.get_or_create_text_channel( text(CHANNEL_SETUP), organization) # Create roles await self._management.get_or_create_role( text(QUIZ_MASTER), discord.Colour(COLOR_QUIZ_MASTER)) async def _tear_down(self): pass # Public def exit(self): pass # Commands and listeners @commands.Cog.listener() async def on_ready(self): self._guild = self._bot.guilds[0] self._management = ServerManagement(self._bot, self._guild) await self._setup() @commands.Cog.listener() async def on_disconnect(self): await self._tear_down() @commands.Cog.listener() async def on_command_error(self, ctx, error): if isinstance(error, commands.errors.CheckFailure): await ctx.message.author.send('Oops something went wrong!' + str(error)) @commands.Cog.listener() async def on_reaction_add(self, reaction, user): if reaction.message.id != self._quiz_message.id: return # Organizer reactions if Context.has_any_role(None, user, ROLES_ORGANIZER): # Start the quiz. if reaction.emoji == EMOJI_ACCEPT: await self._quiz_message.delete() self._quiz_message = None # Stop the quiz. elif reaction.emoji == EMOJI_DECLINE: await self._quiz_message.delete() self._quiz_message = None # Quiz master reactions if user == self._quiz.master: # Next question if reaction.emoji == EMOJI_FORWARD: pass # Next question elif reaction.emoji == EMOJI_BACKWARD: pass # Pause or restart timer elif reaction.emoji == EMOJI_PLAY_PAUSE: pass # Anyone else else: # Add a new participant. if reaction.emoji == EMOJI_OK: self._quiz.add_participant(user) await self._quiz_message.edit( content=self._quiz.organization_text()) # Join team elif reaction.emoji in EMOJI_TEAM: pass @commands.Cog.listener() async def on_reaction_remove(self, reaction, user): if reaction.message.id == self._quiz_message: # Remove a participant. if reaction.emoji == EMOJI_OK: self._quiz.remove_participant(user) await self._quiz_message.edit( content=self._quiz.organization_text()) # Leave team elif reaction.emoji in EMOJI_TEAM: pass @commands.command(name='quiz', aliases=['newquiz, organize'], help='Schedules a new quiz') @commands.has_any_role(*ROLES_ORGANIZER) async def organize(self, ctx, quiz_type: str = None, team_size: str = None): if ctx.channel.name != text(CHANNEL_SETUP): return if quiz_type not in ['normal', 'jeopardy', 'only connect']: quiz_type = 'normal' if not team_size: team_size = 2 team_size = min(max(int(team_size), 2), 8) self._quiz = Quiz(quiz_type, ctx.message.author, team_size) self._quiz_message = await ctx.send(self._quiz.organization_text()) await self._quiz_message.add_reaction(EMOJI_OK) await self._quiz_message.add_reaction(EMOJI_ACCEPT) await self._quiz_message.add_reaction(EMOJI_DECLINE) try: for team_id in range(1, team_size + 1): role = await self._management.get_or_create_role('Team ' + str(team_id)) team = Team(role, team_id) self._quiz.add_team(team) await self._quiz_message.add_reaction(EMOJI_TEAM[team_id - 1]) except Exception as e: print(e) await ctx.message.delete()
def test_finish_quiz(): quiz = Quiz(FakeSource, 1234, "easy", "9", None) quiz.finish() assert quiz.is_finished is True
def quiz_dashboard(qid=None): if not current_user.is_authenticated: flash('Login is Required for this action!') return redirect('/', 302) if not current_user.is_admin: flash('You need to be an Admin for Performing this action!') return redirect('/', 302) template = "_question.html" req_path = request.path.split('/')[-1] if qid and len(qid) > 24: return render_template('404.html') if req_path == qid: req_path = request.path.split('/')[-2] if req_path == 'add': form = AddQuestion() if request.method == "POST": if form.validate(): sol = { 1: form.option1.data, 2: form.option2.data, 3: form.option3.data, 4: form.option4.data, } Quiz(question=form.question.data, options=[ form.option1.data, form.option2.data, form.option3.data, form.option4.data, ], answer=sol.get(form.solution.data)).save_quiz() flash('Question Saved Successfully!') return redirect('/admin/dashboard/Quiz/edit') return render_template('add' + template, form=form) elif req_path == 'edit': if not qid: questions = Quiz.get_questions(userID=None, show_history=True, is_admin=True, limit=1000) for question in questions: question._id = str(question._id) return render_template('display_questions.html', questions=questions) form = EditQuestion() question = Quiz.get_question(qid) if request.method == "POST": if form.validate_on_submit(): if question: question.question = form.question.data question.options = [ form.option1.data, form.option2.data, form.option3.data, form.option4.data ] sol = { 1: form.option1.data, 2: form.option2.data, 3: form.option3.data, 4: form.option4.data, } question.answer = sol.get(form.solution.data) question.update_quiz_info() # print('Quiz updated!') flash('Question Edited Successfully!') return redirect('/admin/dashboard/Quiz/edit') else: flash('Unable to find Question in DB') return redirect('/') else: flash("Couldn't Validate form..") # print(form.validate_on_submit()) return render_template('edit' + template, form=form) if question: form.solution.default = question.options.index(question.answer) + 1 form.process() form.question.data = question.question form.option1.data = question.options[0] form.option2.data = question.options[1] form.option3.data = question.options[2] form.option4.data = question.options[3] # form.process() return render_template('edit' + template, form=form) elif req_path == 'delete' or qid: if request.method == "POST" and qid: # print(help(Quiz.DB.CURSOR.delete_one)) Quiz.DB.CURSOR.Quiz.delete_one({'_id': ObjectId(qid)}) flash('Question Deleted!') return redirect('/admin/dashboard/Quiz/delete') if not qid: questions = Quiz.get_questions(userID=None, show_history=True, is_admin=True, limit=1000) for question in questions: question._id = str(question._id) return render_template('display_questions.html', questions=questions) return render_template('delete_question.html') else: return render_template('404.html')
return redirect('/play') else: return redirect('/final_score') return render_template('404.html') else: errors = [] errors.append(form.qid.errors) errors.append(form.ans.errors) errors.append(form.current_score.errors) errors.append(form.correct_ans.errors) if qid: return redirect('/play/') return str(errors) if not qid: if question := Quiz.get_questions(current_user._id, sample=1): # question is a list with one element question = question[0] # accessing that element form.qid.data = str(question._id) if not form.current_score.data: form.current_score.data = 0 form.correct_ans.data = question.answer else: flash('Well Done! You have reached the end of the Quiz!') if session.get('score') != None and session.get('score') > 0: current_user.total_wins += 1 current_user.update_user_info() return redirect('/final_score') return redirect('/')
def setup(bot): bot.add_cog(Quiz(bot))
def get_single_quiz(self, quiz_id): res = mongo.db.quiz.find_one_or_404({"_id": int(quiz_id)}) quiz = Quiz.quiz_from_dict(res) return quiz
db.create_all() with open('generator/general_5.csv') as questions: db.session.bulk_insert_mappings(Question, DictReader(questions)) with open('generator/rose_3.csv') as questions: db.session.bulk_insert_mappings(Question, DictReader(questions)) with open('generator/aster_3.csv') as questions: db.session.bulk_insert_mappings(Question, DictReader(questions)) with open('generator/mint_3.csv') as questions: db.session.bulk_insert_mappings(Question, DictReader(questions)) with open('generator/pea_3.csv') as questions: db.session.bulk_insert_mappings(Question, DictReader(questions)) questions = Question.query.all() family = ['general'] * 5 + ['Rose family'] * 3 + ['Aster family'] * 3 family = family + ['Mint family'] * 3 + ['Pea family'] * 3 for i in range(len(family)): new_quiz = Quiz(family=family[i], num_questions=10) for j in range(10): questions[10 * i + j].family = family[i] new_quiz.questions.append(questions[i * 10 + j]) db.session.add(new_quiz) db.session.commit()