def test_shuffle_from_csv(tmp_path): data_file = tmp_path / "data.csv" save_mono_question_data(data_file) data = CSVReader(str(data_file)) rows = data.to_dictlist() exam = Exam() exam.attribute_selector = ( "question", "subject", "image", "void", "A", "void", "B", "void", "C", "void", "D", "void", ) exam.load(rows) exam.add_path_parent(data_file) random.seed(1) exam.shuffle() for question in exam.questions: assert question.correct_answer.text == "a" assert exam.questions[0]._answers[0].text == "d" assert exam.questions[1]._answers[0].text == "d"
def parse_exams(f): nr_exams = parse_int_from_header(f.readline()) exams = {} for i in range(nr_exams): vals = list(map(int, f.readline().split((',')))) exams[i] = Exam(vals[0], vals[1:]) return exams
def parse(dataset='data/exam_comp_set1.exam'): with open(dataset) as f: indices = {} lines = [] for i, line in enumerate(f): if line.startswith('['): indices[determine_header(line)] = i lines.append(line.strip()) exams = parse_data(lines, indices[EXAMS_HEADER], indices[PERIOD_HEADER], lambda x: Exam(int(x[0]), [int(i) for i in x[1:]])) periods = parse_data( lines, indices[PERIOD_HEADER], indices[ROOM_HEADER], lambda x: Period(x[0], x[1], int(x[2]), int(x[3]))) rooms = parse_data(lines, indices[ROOM_HEADER], indices[PERIOD_CONSTRAINTS_HEADER], lambda x: Room(int(x[0]), int(x[1]))) period_constraints = parse_constraint( lines, indices[PERIOD_CONSTRAINTS_HEADER], indices[ROOM_CONSTRAINTS_HEADER], lambda x: PeriodHardConstraint( PeriodHardEnum.fromstring(x[1]), int(x[0]), int(x[2])), PeriodHardEnum) room_constraints = parse_constraint( lines, indices[ROOM_CONSTRAINTS_HEADER], indices[INSTITUTIONAL_CONSTRAINTS_HEADER], lambda x: RoomHardConstraint(RoomHardEnum.fromstring(x[1]), int(x[0])), RoomHardEnum) institutional_constraints = parse_constraint( lines, indices[INSTITUTIONAL_CONSTRAINTS_HEADER], len(lines), lambda x: InstitutionalConstraint( InstitutionalEnum.fromstring(x[0]), [int(i) for i in x[1:]]), InstitutionalEnum) return exams, periods, rooms, period_constraints, room_constraints, institutional_constraints
def parse_exam(day, session_times, exam_name): # If a line in the table contains the forbidden keywords, it's actually an exam instruction. # Also, if a day contains " to " (with spaces so we don't reject October dates), it is a # date range, meaning no exams are scheduled (it's just VCAA telling people to look at their # advice slips). Don't attempt parsing if any of these conditions apply. if " to " in day or any(keyword in exam_name for keyword in non_exam_keywords): return None current_year = datetime.today().year start_time = datetime.strptime(session_times[0], "%I.%M%p") end_time = datetime.strptime(session_times[1], "%I.%M%p") start_date = datetime.strptime(day, "%A %d %B") start_date = start_date.replace(year=current_year, hour=start_time.hour, minute=start_time.minute) end_date = datetime.strptime(day, "%A %d %B") end_date = end_date.replace(year=current_year, hour=end_time.hour, minute=end_time.minute) # Uses format of Friday 2 November, 2.00pm – 3.45pm # Localise locale = pytz.timezone("Australia/Melbourne") start_date = locale.localize(start_date) end_date = locale.localize(end_date) exam = Exam(exam_name, start_date, end_date) return exam
def exam_edit_page(exam_key): db = current_app.config["db"] exam = db.get_exam(exam_key) form = ExamEditForm() if form.validate_on_submit(): examname = form.data["examname"] numberofquestions = form.data["numberofquestions"] question = form.data["question"] a = form.data["a"] b = form.data["b"] c = form.data["c"] d = form.data["d"] e = form.data["e"] exam = Exam(examname, numberofquestions, question, a, b, c, d, e) db.update_exam(exam_key, exam) flash("Exam updated.") return redirect(url_for("exam_page", exam_key=exam_key)) form.examname.data = exam.examname form.numberofquestions.data = exam.numberofquestions form.question.data = exam.question form.a.data = exam.a form.b.data = exam.b form.c.data = exam.c form.d.data = exam.d form.e.data = exam.e x = datetime.now() date = x.strftime("%x") day_name = x.strftime("%A") time = x.strftime("%X") return render_template("exam_edit.html", form=form, date = date, day_name = day_name, time = time)
def get_exam(self, exam_key): with dbapi2.connect(self.dbfile) as connection: cursor = connection.cursor() query = "SELECT examname, numberofquestions, question, a, b, c, d, e FROM exam WHERE (examno = ?)" cursor.execute(query, (exam_key,)) examname, numberofquestions, question, a, b, c, d, e = cursor.fetchone() exam_ = Exam(examname, numberofquestions, question, a, b, c, d, e) return exam_
def test_Exam_addQuestion_bad_question(self): myExam = Exam() try: myExam.addQuestion(self.myBadQuestion) except ValueError: pass # When input is bad, nothing should be added. self.assertEqual(myExam.getQuestions(), [])
def get_exams(self): exams = [] with dbapi2.connect(self.dbfile) as connection: cursor = connection.cursor() query = "SELECT examno, examname, numberofquestions, question, a, b, c, d, e FROM exam ORDER BY examno" #SELECT examno, examname, numberofquestions, question, a, b, c, d, e FROM exam; cursor.execute(query) for exam_key, examname, numberofquestions, question, a, b, c, d, e in cursor: exams.append((exam_key, Exam(examname, numberofquestions, question, a, b, c, d, e))) return exams
def student_login(): global stu if request.method=='GET' and stu==None: return render_template('studentlogin.html') exams=None if stu!=None: er=ExamRegister(stu) e=er.get_registered_exams() if e!=None: exams=[] for i in e: exam=Exam() exam.get_exam(i[0]) exams+=[exam] if request.method=='GET' and stu !=None: print(exams) return render_template('studenthome.html',exams=exams) if request.method=='POST': roll=request.form['rollno'] password=request.form['password'] s=Student() if s.student_login(roll,password): stu=s er=ExamRegister(s) e=er.get_registered_exams() if e!=None: exams=[] for i in e: exam=Exam() exam.get_exam(i[0]) exams+=[exam] print(exams) return render_template('studenthome.html',exams=exams) return '<script>alert("Details given were wrong")</script>'+render_template('studentlogin.html')
def student_viewexam(): global stu if stu is None: return '<script>alert("You are not logged in")</script>'+render_template('home.html') if request.method=='GET': e=Exams() es=e.get_exams() #subjectname,subjectcode,domain,examfee,examdate return render_template('studentviewexams.html',exams=es) subcode=request.form['subjectcode'] e=Exam() if e.get_exam(subcode): return render_template('studentviewexam.html',exam=e)
def student_registerexam(): global stu if stu is None: return '<script>alert("You are not logged in!")</script>'+render_template('home.html') if request.method=='POST': subcode=request.form['subjectcode'] er=ExamRegister(stu) e=Exam() e.get_exam(subcode) es=Exams() exams=es.get_exams() if er.register(e): return '<script>alert("Exam registered successfully!")</script>'+render_template('studentviewexams.html',exams=exams) return '<script>alert("Error! Exam already registered!")</script>'+render_template('studentviewexams.html',exams=exams)
def createExam(questions_file): try: # Exam questions qs = getQuestions(False, "./questions/" + questions_file + ".json") number_questions = int(request.args.get('n', len(qs))) seed = request.args.get('s', 0) myExam = Exam(qs) version = myExam.getVersion(number_questions, seed) version['seed'] = seed except: return (jsonify({'message': 'Failed to load questions'})) return jsonify(version)
def addexam(): global examcontroller if examcontroller==None: return '<script>alert("You are not logged in")</script>'+render_template('home.html') if request.method=='GET': return render_template('examcontrolleraddexam.html') subjectcode=request.form['subjectcode'] subjectname=request.form['subjectname'] domain=request.form['domain'] examfee=request.form['examfee'] examdate=request.form['examdate'] print(examdate) e=Exam() if e.add_exam(subjectcode,subjectname,domain,examfee,examdate): return '<script>alert("Successfully added!")</script>'+render_template('examcontrolleraddexam.html') return '<script>alert("Retry !")</script>'+render_template('examcontrolleraddexam.html')
def examcontroller_viewexam(): global examcontroller if examcontroller==None: return '<script>alert("You are not logged in")</script>'+render_template('home.html') if request.method=='GET': e=Exams() examins=e.get_exams() #subjectname,subjectcode,domain,examfee,examdate return render_template('examcontrollerviewexams.html',exams=examins) subcode=request.form['subjectcode'] e=Exam() er=ExamRegister() details=er.get_registered_students(subcode) if e.get_exam(subcode): return render_template('examcontrollerviewexam.html',exam=e,registered=details)
def add(self, subject): """ Add exam with this subject name. Parameters ---------- subject : str Exam subject name. Must have from 4 to 56 characters inclusive. In addition to the letters of the alphabet, it can contain double quotes, spaces, and hyphens. Returns ------- Exam Added exam. """ new_exam = Exam(subject) self._exams.append(new_exam) return new_exam
def dummy_exam(): q1 = MultiChoiceQuest("question 1: correct is n. 2", "subject 1", Path("resources/a.png")) a1 = MultiChoiceAnswer("answer 1", Path("resources/b.png")) a2 = MultiChoiceAnswer("answer 2", Path("resources/c.png")) a3 = MultiChoiceAnswer("answer 3", Path("resources/a.png")) q1.answers = (a1, a2, a3) q1.correct_option = "B" q2 = MultiChoiceQuest("question 2: correct is n. 1", "subject 1", Path("resources/a.png")) a1 = MultiChoiceAnswer("answer 1") a2 = MultiChoiceAnswer("answer 2") a3 = MultiChoiceAnswer("answer 3") q2.answers = (a1, a2, a3) q3 = TrueFalseQuest("question 3: correct is True (first)") a1 = TrueFalseAnswer(True) a2 = TrueFalseAnswer(False) q3.answers = (a1, a2) q4 = MultiChoiceQuest("question 4: no answer", "subject 2", Path("resources/b.png")) q5 = TrueFalseQuest("question 5: correct is False (first))") a1 = TrueFalseAnswer(False) a2 = TrueFalseAnswer(True) q5.answers = (a1, a2) q6 = MultiChoiceQuest("question 6: correct is n. 3", "subject 4", Path("resources/c.png")) a1 = MultiChoiceAnswer("answer 1") a2 = MultiChoiceAnswer("answer 2") a3 = MultiChoiceAnswer("answer 3") a4 = MultiChoiceAnswer("answer 4") q6.add_answer(a1) q6.add_answer(a2) q6.add_answer(a3, is_correct=True) q6.add_answer(a4) dummy_ex = Exam(q1, q2, q3, q4, q5, q6) return dummy_ex
def student_signup(): global stu if request.method=='GET' and stu==None: return render_template('studentsignup.html') roll=request.form['rollno'] passwd=request.form['password'] name=request.form['name'] s=Student() if s.student_signup(name,roll,passwd): stu=s er=ExamRegister(s) e=er.get_registered_exams() exams=None if e!=None: exams=[] for (i) in exams: exam=Exam() exam.get_exam(i) exams+=[exam] return render_template('studenthome.html') return '<script>alert("Retry")</script>'+render_template('studentsignup.html')
def find(self, subject): """ Finds the exma by the subject name. Parameters ---------- subject : str Exam subject name. Must have from 4 to 56 characters inclusive. In addition to the letters of the alphabet, it can contain double quotes, spaces, and hyphens. Raises ------ ValueError Exam not with this subject name not in exist. Returns ------- Exam Exam with this subject name. """ index = self._exams.index(Exam(subject)) exam = self._exams[index] return exam
def exam_add_page(): if not current_user.is_admin: abort(401) form = ExamEditForm() if form.validate_on_submit(): examname = form.data["examname"] numberofquestions = form.data["numberofquestions"] question = form.data["question"] a = form.data["a"] b = form.data["b"] c = form.data["c"] d = form.data["d"] e = form.data["e"] exam = Exam(examname, numberofquestions, question, a, b, c, d, e) db = current_app.config["db"] exam_key = db.add_exam(exam) flash("Exam added.") return redirect(url_for("exam_page", exam_key=exam_key)) x = datetime.now() date = x.strftime("%x") day_name = x.strftime("%A") time = x.strftime("%X") return render_template("exam_edit.html", form=form, date = date, day_name = day_name, time = time)
from students import AbstractStudent, DefaultStudent, MemberOfStudentCouncil, NerdStudent from group import Group from exam import Exam from grades import Grades stud1 = DefaultStudent('A A A', [('Math', [4, 4, 4])]) stud1.addSubjectAndGrade('Physics', [3, 4, 3]) stud2 = DefaultStudent('B B B', [('Math', [2, 2, 2]), ('Physics', [5, 5, 5])]) stud3 = NerdStudent('CCC', [('Math', [2, 2, 2]), ('Physics', [2, 2, 2])]) group = Group('8888', 20, [stud1, stud2, stud3]) exam = Exam(group, 'Math') exam1 = Exam(group, 'Physics') exam.checkGrades() exam.examination() exam.examination() exam.examination() print(group)
def test_Exam_addQuestion_good_question(self): myExam = Exam() myExam.addQuestion(self.myGoodQuestion) self.assertEqual(myExam.getQuestions(), [self.myGoodQuestion])
def test_Exam_removeQuestion_valid(self): myExam = Exam() # Seems to reuse myExam from earlier...? myExam.removeQuestion(search=0, questionIndex=True) self.assertEqual(myExam.getQuestions(), [])
import pandas as pd #To read information from the Excel sheet name_of_file_with_questions = str( input( "Please insert the name of the file where the questions are located at (include .xlsx extention): " )) header = str(input("Please insert the header for the exam: ")) subheader = str(input("Please insert the subheader: ")) file = pd.read_excel(name_of_file_with_questions, index_col=None, header=0) file = file.fillna( {'Pregunta': ''} ) #If there is empty cells in the questions row, we fill them with an empty string. how_many_questions = file.count()['Pregunta'] exam = Exam(header, subheader, how_many_questions ) #We instance an exam object with the basic information given #Initial values used for adding questions and sections to the exam inside the following loop topic = file.at[0, 'Tema'] question_num = 0 section_num = 1 exam.add_section(topic, section_num) current_question_num = None current_topic = None #We iterate through every row in the .xlsx (each containing a question with its respective information) """ row[0] contains the topic to which the question belongs to row[1] contains the question number (which teachers will use to keep control of the questions numbering in the Excel file) row[2] contains the string with the question to be printed in the file row[3] contains the name of the file of the figure that is used in the current question (if any)
def add_information(self, info, r, students): self.exam = Exam(info['exam_id'], info['start_at'], info['end_at'], r) for s in info['students']: stu = self.find_student_based_on_id(students, s['id']) self.students.append(StudentExamInfo(stu, s['chair_number']))
exam_values = {} for exam in exam_names: if "Examination" in exam: pieces = exam.split(" Examination") subject_name = pieces[0] exam_values[subject_name] = subject_name + "*" elif "GAT" in exam: continue else: exam_values[exam] = exam return exam_values with open("exam_schedule.csv", "r") as file: reader = csv.reader(file) exams = [Exam(name, session, day) for name, session, day in reader] client_exam_values = setup_client_exam_values(exams) def generate_calendar(exams): cal = Calendar() cal.add('prodid', '-//VCE//VCE Exam Schedule//') cal.add('version', '2.0') cal.add('X-WR-CALNAME', 'VCE Exam Schedule') for exam in exams: event = Event() event.add('summary', "{} Exam".format(exam.name)) event.add('dtstart', dateutil.parser.parse(exam.start_date).replace(tzinfo=aus_tz)) event.add('dtend', dateutil.parser.parse(exam.end_date).replace(tzinfo=aus_tz)) event.add('dtstamp', datetime.today()) cal.add_component(event)
def get_exam(self, exam_key): exam = self.exams.get(exam_key) if exam is None: return None exam_ = Exam(exam.exam_name, numberofquestions=exam.numberofquestions, question=exam.question, a=exam.a, b=exam.b, c=exam.c, d=exam.d, e=exam.e ) return exam_
def get_exams(self): exams = [] for exam_key, exam in self.exams.items(): exam_ = Exam(exam.exam_name, numberofquestions=exam.numberofquestions, question=exam.question, a=exam.a, b=exam.b, c=exam.c, d=exam.d, e=exam.e ) exams.append((exam_key, exam_)) return exams
def to_pdf(self, input_file: Path, output_folder: Path): rows = self._get_rows(input_file) if not rows: LOGGER.warning("Empty rows.") self.errorbox("Invalid data") return try: exam = Exam() exam.attribute_selector = ( "question", "subject", "image", "void", "A", "void", "B", "void", "C", "void", "D", "void", ) exam.load(rows) exam.add_path_parent(input_file) serial_exam = SerializeExam(exam) for number in range(int(self.parameters["number"])): if self.parameters["not_shuffle"] is False: exam.shuffle() output_file_name_exam = Path(f"{self.parameters['exam']}_{number}.pdf") if self.parameters["page_heading"] != "": exam_heading = f"{self.parameters['page_heading']} file n. {number}" else: exam_heading = "" exam_footer = self.parameters["page_footer"] to_pdf_interface = RLInterface( serial_exam.assignment(), output_file_name_exam, destination=output_folder, heading=exam_heading, footer=exam_footer, ) to_pdf_interface.build() output_file_name_correction = Path( f"{self.parameters['correction']}_{number}.pdf" ) to_pdf_interface = RLInterface( serial_exam.correction(), output_file_name_correction, destination=output_folder, top_item_bullet_type="A", sub_item_bullet_type="1", heading=output_file_name_exam.name, ) to_pdf_interface.build() except Exception as err: LOGGER.critical("CSVReader failed: %s %s", err.__class__, err) self.errorbox(exception_printer(err)) raise self.infobox("Avviso", "Conversione effettuata") self.data_queue.put("end")
"На полке лежала пачка макаронов", "Эти кремы просрочены", "На ней не было чулок" ], "Зеленый пигмент, окрашивающий листья растений, называется:": ["Хлорофилл", "Хлоропласт", "Хлорофиллипт"], "Желчь образуется в:": ["Печени", "Желчном пузыре", "Поджелудочной железе"], "Сколько хромосом в геноме человека?": ["46", "42", "44"] } user = {"id": 1231412, "name": "Lik Eduard"} # Initialization exam TestManager("exam.db").add_test(name="Test 1", test=test, time=30, point=1) exam = Exam("exam.db") exam.choose_test(user, "Test 1") exam.get_question(user) #exam.get_testlist() ''' # Telegram Block token = open("token.txt", "r").read() bot = telebot.TeleBot(token) me = bot.get_me() #--- Functions ---# def setKeyBoard(*args): if args is None: return telebot.types.ReplyKeyboardRemove() kb = telebot.types.ReplyKeyboardMarkup()
from exam import Exam from examWithProperty import ExamWithProperty e = Exam(60) print(e.get_score()) e.set_score(70) print(e.get_score()) e = ExamWithProperty(60) print(e.score) e.score = 70 print(e.score)