Exemplo n.º 1
0
 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(), [])
Exemplo n.º 2
0
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"
Exemplo n.º 3
0
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)
Exemplo n.º 4
0
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)
Exemplo n.º 5
0
def makeExam(options):
    data = open(options.source, encoding="utf-8").read()
    if options.xml:
        examXML = data
        options.resources = []
        options.extensions = []
    else:
        try:
            exam = Exam.fromstring(data)
            examXML = exam.tostring()
            options.resources = exam.resources
            options.extensions = exam.extensions
        except examparser.ParseError as err:
            print("Failed to compile exam due to parsing error.")
            raise
        except:
            print("Failed to compile exam")
            raise
    options.examXML = examXML
    options.xmls = xml2js(options)

    if options.zip:
        compileToZip(options)
    else:
        compileToDir(options)
Exemplo n.º 6
0
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
Exemplo n.º 7
0
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 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
Exemplo n.º 9
0
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')
Exemplo n.º 10
0
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)
Exemplo n.º 11
0
 def __init__(self,**kwargs):
     super(Level, self).__init__(**kwargs)
     self.register_event_type('on_pass')
     self.name="level"
     main_layout=BoxLayout(orientation='vertical')
     labels=BoxLayout(orientation="horizontal",size_hint=(1,.1))
     labels.add_widget(Label(text="Valid",background_color=(0,1,0,1)))
     labels.add_widget(Label(text="Invalid",background_color=(1,0,0,1)))
     history=BoxLayout(orientation="horizontal",spacing=100)
     self.enter_label=Label(text="Enter your sequence:",size_hint=(1,.2))
     self.valid_history=CaterpillarList()
     self.invalid_history=CaterpillarList()
     history.add_widget(self.valid_history)
     history.add_widget(self.invalid_history)
     self.buttons=BoxLayout(orientation="vertical")
     self.exam=Exam()
     self.exam.bind(on_answer=self.chain_entered)
     self.exam.bind(on_finish=self.finish)
     self.input_chain=InputCaterpillar()
     self.input_chain.bind(on_input=self.chain_entered)
     self.exam_button=Button(text="I know the rule and ready for test!")
     self.exam_button.bind(on_press=self.to_exam_mode)
     main_layout.add_widget(labels)
     main_layout.add_widget(history)
     self.to_game_mode()
     main_layout.add_widget(self.buttons)
     self.add_widget(main_layout)
Exemplo n.º 12
0
 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_
Exemplo n.º 13
0
 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
Exemplo n.º 14
0
 def set(self, results):
     self.total = len(results)
     self.correct = 0
     self.wrong = []
     for result in results:
         is_correct, expect, actual = Exam.check_answer(result[Exam.VERB], result)
         if is_correct:
             correct += 1
         else:
             self.wrong.append((expect, actual, result))
     self.__score_label = None
Exemplo n.º 15
0
 def show(self):
     resp = self.dialog.run()
     self.dialog.hide()
     if resp == Gtk.ResponseType.OK:
         self.providers.configuration_done()
         exam_name = self.exam_name_entry.get_text()
         csv_file = self.exam_students.get_filename()
         if not osp.exists(csv_file):
             raise FileNotFoundError()
         return Exam.from_csv(csv_file, exam_name, settings.base_dir,
                              self.providers)
     else:
         return None
Exemplo n.º 16
0
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)
Exemplo n.º 17
0
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')
Exemplo n.º 18
0
    def load_exams(self):
        self.exams = []
        for folder in pathlib.Path(settings.base_dir).glob('*/'):
            try:
                ex = Exam.load(str(folder))
                self.exams.append(ex)
            except FileNotFoundError:
                pass

        for ex in self.exams:
            row = WelcomeExamListRow(ex)
            print(ex)
            self.exam_list.add(row)

        self.exam_list.show_all()
Exemplo n.º 19
0
 def parse_exam(self):
     """
         Parse an exam definition from the given source
     """
     try:
         self.exam = Exam.fromstring(self.options.source)
         self.examXML = self.exam.tostring()
         self.resources = self.exam.resources
         self.extensions = self.exam.extensions
     except ExamError as err:
         raise CompileError('Error constructing exam:\n%s' % err)
     except examparser.ParseError as err:
         raise CompileError("Failed to compile exam due to parsing error.\n%s" % err)
     except:
         raise CompileError('Failed to compile exam.')
Exemplo n.º 20
0
 def parse_exam(self):
     """
         Parse an exam definition from the given source
     """
     try:
         self.exam = Exam.fromstring(self.options.source)
         self.examXML = self.exam.tostring()
         self.resources = self.exam.resources
         self.extensions = self.exam.extensions
     except ExamError as err:
         raise Exception('Error constructing exam:\n%s' % err)
     except examparser.ParseError as err:
         raise Exception("Failed to compile exam due to parsing error.\n%s" % err)
     except:
         raise Exception('Failed to compile exam.')
Exemplo n.º 21
0
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)
Exemplo n.º 22
0
def makeExam(options):
    data = open(options.source, encoding='utf-8').read()
    if (options.xml):
        examXML = data
        options.resources = []
        options.extensions = []
    else:
        exam = Exam.fromstring(data)
        examXML = exam.tostring()
        options.resources = exam.resources
        options.extensions = exam.extensions
    options.examXML = examXML
    options.xmls = xml2js(options)

    if options.zip:
        compileToZip(options)
    else:
        compileToDir(options)
Exemplo n.º 23
0
def makeExam(options):
	data = open(options.source,encoding='utf-8').read()
	if(options.xml):
		examXML = data
		options.resources=[]
		options.extensions=[]
	else:
		exam = Exam.fromstring(data)
		examXML = exam.tostring()
		options.resources = exam.resources
		options.extensions = exam.extensions
	options.examXML = examXML
	options.xmls = xml2js(options)


	if options.zip:
		compileToZip(options)
	else:
		compileToDir(options)
Exemplo n.º 24
0
    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
Exemplo n.º 25
0
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')
Exemplo n.º 26
0
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
Exemplo n.º 27
0
    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
Exemplo n.º 28
0
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)
Exemplo n.º 29
0
class Level(Screen):

    def __init__(self,**kwargs):
        super(Level, self).__init__(**kwargs)
        self.register_event_type('on_pass')
        self.name="level"
        main_layout=BoxLayout(orientation='vertical')
        labels=BoxLayout(orientation="horizontal",size_hint=(1,.1))
        labels.add_widget(Label(text="Valid",background_color=(0,1,0,1)))
        labels.add_widget(Label(text="Invalid",background_color=(1,0,0,1)))
        history=BoxLayout(orientation="horizontal",spacing=100)
        self.enter_label=Label(text="Enter your sequence:",size_hint=(1,.2))
        self.valid_history=CaterpillarList()
        self.invalid_history=CaterpillarList()
        history.add_widget(self.valid_history)
        history.add_widget(self.invalid_history)
        self.buttons=BoxLayout(orientation="vertical")
        self.exam=Exam()
        self.exam.bind(on_answer=self.chain_entered)
        self.exam.bind(on_finish=self.finish)
        self.input_chain=InputCaterpillar()
        self.input_chain.bind(on_input=self.chain_entered)
        self.exam_button=Button(text="I know the rule and ready for test!")
        self.exam_button.bind(on_press=self.to_exam_mode)
        main_layout.add_widget(labels)
        main_layout.add_widget(history)
        self.to_game_mode()
        main_layout.add_widget(self.buttons)
        self.add_widget(main_layout)

    def start_game(self,func):
        self.func=func
        self.input_chain.func=self.func
        self.valids,self.invalids=get_valid_invalid(func)
        valids_sample=get_n(7,self.valids)
        invalids_sample=get_n(7,self.invalids)
        self.valid_history.reset()
        self.invalid_history.reset()
        for e in valids_sample:
            self.valid_history.add(e)
        for e in invalids_sample:
            self.invalid_history.add(e)
        self.to_game_mode()



    def chain_entered(self,instance,chain):
        if self.func(chain):
            self.valid_history.add(chain)
        else:
            self.invalid_history.add(chain)

    def finish(self,instance,passed):
        self.to_game_mode()
        if passed:
            self.dispatch('on_pass')


    def on_pass(self,*args):
        pass

    def to_exam_mode(self,*args):
        self.buttons.clear_widgets()
        self.exam.start_exam(self.valids,
                             self.invalids,
                             self.valid_history.caterpillars,
                             self.invalid_history.caterpillars)
        self.buttons.add_widget(self.exam)

    def to_game_mode(self,*args):
        self.buttons.clear_widgets()
        self.buttons.add_widget(self.enter_label)
        self.buttons.add_widget(self.input_chain)
        self.buttons.add_widget(self.exam_button)
Exemplo n.º 30
0
 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
Exemplo n.º 31
0
 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_
Exemplo n.º 32
0
        "На полке лежала пачка макаронов", "Эти кремы просрочены",
        "На ней не было чулок"
    ],
    "Зеленый пигмент, окрашивающий листья растений, называется:":
    ["Хлорофилл", "Хлоропласт", "Хлорофиллипт"],
    "Желчь образуется в:":
    ["Печени", "Желчном пузыре", "Поджелудочной железе"],
    "Сколько хромосом в геноме человека?": ["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()
Exemplo n.º 33
0
    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")
Exemplo n.º 34
0
def makeExam(options):
    try:
        exam = Exam.fromstring(options.source)
        examXML = exam.tostring()
        options.resources = exam.resources
        options.extensions = exam.extensions
    except ExamError as err:
        raise Exception('Error constructing exam:\n%s' % err)
    except examparser.ParseError as err:
        raise Exception("Failed to compile exam due to parsing error.\n%s" %
                        err)
    except:
        raise Exception('Failed to compile exam.')

    options.examXML = examXML
    options.xmls = xml2js(options)

    files = collectFiles(options)
    files[os.path.join('.', 'settings.js')] = io.StringIO(options.xmls)

    localePath = os.path.join(options.path, 'locales', options.locale + '.js')
    if not os.path.exists(localePath):
        raise Exception("Can't find locale " + options.locale)
    files[os.path.join('.', 'locale.js')] = io.StringIO(
        open(localePath, encoding='utf-8').read())

    if options.scorm:
        IMSprefix = '{http://www.imsglobal.org/xsd/imscp_v1p1}'
        manifest = etree.fromstring(
            open(os.path.join(options.path, 'scormfiles',
                              'imsmanifest.xml')).read())
        manifest.attrib['identifier'] = 'Numbas: %s' % exam.name
        manifest.find('%sorganizations/%sorganization/%stitle' %
                      (IMSprefix, IMSprefix, IMSprefix)).text = exam.name

        def to_relative_url(path):
            path = os.path.normpath(path)
            bits = []
            head, tail = os.path.split(path)
            while head != '':
                bits.insert(0, tail)
                head, tail = os.path.split(head)
            bits.insert(0, tail)
            return '/'.join(bits)

        resource_files = [to_relative_url(x) for x in files.keys()]

        resource_element = manifest.find('%sresources/%sresource' %
                                         (IMSprefix, IMSprefix))
        for filename in resource_files:
            file_element = etree.Element('file')
            file_element.attrib = {'href': filename}
            resource_element.append(file_element)

        files.update(collectFiles(options, [('scormfiles', '.')]))

        manifest_string = etree.tostring(manifest)
        try:
            manifest_string = manifest_string.decode('utf-8')
        except AttributeError:
            pass

        files[os.path.join('.',
                           'imsmanifest.xml')] = io.StringIO(manifest_string)

    stylesheets = [(dst, src) for dst, src in files.items()
                   if os.path.splitext(dst)[1] == '.css']
    for dst, src in stylesheets:
        del files[dst]
    stylesheets = [src for dst, src in stylesheets]
    stylesheets = '\n'.join(
        open(src, encoding='utf-8').read() if isinstance(src, basestring
                                                         ) else src.read()
        for src in stylesheets)
    files[os.path.join('.', 'styles.css')] = io.StringIO(stylesheets)

    javascripts = [(dst, src) for dst, src in files.items()
                   if os.path.splitext(dst)[1] == '.js']
    for dst, src in javascripts:
        del files[dst]

    javascripts = [src for dst, src in javascripts]
    numbas_loader_path = os.path.join(options.path, 'runtime', 'scripts',
                                      'numbas.js')
    javascripts.remove(numbas_loader_path)
    javascripts.insert(0, numbas_loader_path)
    javascripts = '\n'.join(
        open(src, encoding='utf-8').read() if isinstance(src, basestring
                                                         ) else src.read()
        for src in javascripts)
    files[os.path.join('.', 'scripts.js')] = io.StringIO(javascripts)

    if options.minify:
        for dst, src in files.items():
            if isinstance(src,
                          basestring) and os.path.splitext(dst)[1] == '.js':
                p = subprocess.Popen([options.minify, src],
                                     stdin=subprocess.PIPE,
                                     stdout=subprocess.PIPE,
                                     stderr=subprocess.PIPE)
                out, err = p.communicate()
                code = p.poll()
                if code != 0:
                    raise Exception('Failed to minify %s with minifier %s' %
                                    (src, options.minify))
                else:
                    files[dst] = io.StringIO(out.decode('utf-8'))

    if options.zip:
        compileToZip(exam, files, options)
    else:
        compileToDir(exam, files, options)
Exemplo n.º 35
0
    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)
Exemplo n.º 36
0
'''
Main application.  Does any setup required, including starting a GUI.
'''
from exam import Exam

exam = Exam()
exam.administer_exam()