Example #1
0
def main():
    q1 = question.Question("What was the first planet that the covenant invaded?", "Harvest", "Earth",
                           "Reach", "Onyx", "A")
    q2 = question.Question("What year did the Human-Covenant war start?", "2020", "2457", "2525", "2552", "C")
    q3 = question.Question("What was the way the Covenant destroyed human worlds?", "Infection", "Glassing",
                           "Overwhelming Forces", "Both B and C", "D")
    q4 = question.Question("What was the name of the Spartan that saved humanity?", "Kat-B320", "Lucy-B901",
                           "John-117", "Jorge-052", "C")
    q5 = question.Question("What event was the beginning of the end for the Covenant empire?", "The Great Break",
                           "The Great Schism", "The Grunt Rebellion", "The Great Journey", "B")
    q6 = question.Question("What was the name of the forces of Humanity?", "UNSC", "USMC", "UEDF", "EDFC", "A")
    q7 = question.Question("What species of alien lead the Covenant?", "Prophets", "Elites", "Brutes", "Grunts", "A")
    q8 = question.Question("What was the name of the AI(Artificial intelligence) that helped saved humanity?",
                           "Linda", "Henry", "Cortana", "Jessamine", "C")
    q9 = question.Question("What alien super-weapon was the Covenant going to fire to wipe all life out in the galaxy?",
                           "Ring", "Halo", "Journey", "Laser", "B")
    q10 = question.Question("What was the name of the installation that Humanity defeated the Covenant at?", "Installation 00",
                            "Installation 01", "Installation 04", "Installation 07", "A")

    all_the_questions = (q1, q2, q3, q4, q5, q6, q7, q8, q9, q10)
    print("---Player 1---")
    player_1 = ask(all_the_questions)
    print("---Player 2---")
    player_2 = ask(all_the_questions)

    if player_1 == player_2:
        print("It's a tie!!")
    elif player_1 > player_2:
        print("Player one wins!!")
    else:
        print("Player two wins!!")
Example #2
0
def get_questions():

    questions = []

    # Create questions and add to list.
    question1 = question.Question('How many days are in a ' + \
                                  'lunar year?', '354', '365', \
                                  '243', '379', 1)
    questions.append(question1)
    question2 = question.Question('What is the largest planet?', \
                                  'Mars', 'Jupiter', 'Earth', \
                                  'Pluto', 2)
    questions.append(question2)
    question3 = question.Question('What is the largest kind of ' + \
                                  'whale?', 'Orca whale', \
                                  'Humpback whale', \
                                  'Beluga whale', 'Blue whale', 4)
    questions.append(question3)
    question4 = question.Question('Which dinosaur could fly?', \
                                  'Triceratops', 'Tyranosaurus Rex', \
                                  'Pteranodon', 'Diplodocus', 3)
    questions.append(question4)
    question5 = question.Question('Which of these Winnie the Pooh ' + \
                                  'characters is a donkey?', \
                                  'Pooh', 'Eeyore', 'Piglet', \
                                  'Kanga', 2)
    questions.append(question5)
    question6 = question.Question('What is the hottest planet?', \
                                  'Mars', 'Pluto', 'Earth', \
                                  'Venus', 4)
    questions.append(question6)
    question7 = question.Question('Which dinosaur had the ' + \
                                  'largest brain compared to body' + \
                                  ' size?', 'Troodon', 'Stegosaurus', \
                                  'Ichthyosaurus', 'Gigantoraptor', 1)
    questions.append(question7)
    question8 = question.Question('What is the largest type ' + \
                                  'of penguins?', \
                                  'Chinstrap penguins', \
                                  'Macaroni penguins', \
                                  'Emperor penguins', \
                                  'White-flippered penguins', 3)
    questions.append(question8)
    question9 = question.Question("Which children's story " + \
                                  'character is a monkey?', \
                                  'Winnie the Pooh', \
                                  'Curious George', 'Horton', \
                                  'Goofy', 2)
    questions.append(question9)
    question10 = question.Question('How long is a year on Mars?', \
                                   '550 Earth days', \
                                   '498 Earth days', \
                                   '126 Earth days', \
                                   '687 Earth days', 4)
    questions.append(question10)

    return questions
Example #3
0
File: main.py Project: Oli-26/DST
    def __init__(self):
        Gtk.Window.__init__(self, title="Dynamic State Tracker")
        self.selected_file = None
        self.questions = list()
        self.time_interval = 100


        first_question = question.Question()
        first_question.question = "How confident were you?"
        first_question.type = "slider"
        self.questions.append(first_question)

        second_question = question.Question()
        second_question.question = "How scared were you?"
        second_question.type = "slider"
        self.questions.append(second_question)


        self.draw_area = Gtk.DrawingArea()
        self.draw_area.set_size_request(10, 50)

        # Create and assign action to start button
        self.start_button = Gtk.Button("        Start        ")
        self.start_button.connect("clicked", self.start)

        # Create and assign action to select video button
        self.select_video_button = Gtk.Button("Select video")
        self.select_video_button.connect("clicked", self.select_video)

        # Create and assign action to question settings button
        self.question_settings_button = Gtk.Button("Set questions")
        self.question_settings_button.connect("clicked", self.question_settings)

        self.analyse_button = Gtk.Button("Analyse Data")
        self.analyse_button.connect("clicked", self.analyse_data)

        # Create gtk box and pack all buttons into it. This box is at the bottom of the application
        self.hbox = Gtk.Box(spacing=6)
        self.hbox.pack_start(self.start_button, True, True, 0)
        self.hbox.pack_start(self.select_video_button, True, True, 0)
        self.hbox.pack_start(self.question_settings_button, True, True, 0)
        self.hbox.pack_start(self.analyse_button, True, True, 0)

        # Create gtk box containing title and video selected information and the gtk box above
        self.vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        self.vbox.pack_start(Gtk.Label("Dynamic State Tracker"), True, True, 0)
        self.selected_label = Gtk.Label("Video selected: ")
        self.vbox.pack_start(self.selected_label, True, True, 0)
        self.add(self.vbox)
        self.vbox.pack_start(self.draw_area, True, True, 0)
        self.vbox.pack_start(self.hbox, False, False, 0)
Example #4
0
    def get_asks(self):
        """
            By ecsys (https://github.com/ecsys)
            增加了获取某用户所有赞过答案的功能 #29
            (https://github.com/egrcc/zhihu-python/pull/29)
        """
        if self.user_url == None:
            print "I'm anonymous user."
            return
            yield
        else:
            asks_num = self.get_asks_num()
            if asks_num == 0:
                return
                yield
            else:
                for i in xrange((asks_num - 1) / 20 + 1):
                    ask_url = self.user_url + "/asks?page=" + str(i + 1)
                    r = requests.get(ask_url)

                    soup = BeautifulSoup(r.content, "lxml")
                    for question in soup.find_all("a", class_="question_link"):
                        url = "http://www.zhihu.com" + question["href"]
                        title = question.string.encode("utf-8")
                        yield question.Question(url, title)
Example #5
0
    def parse_answer_keys(self):
        """
        docstring
        """
        answerkey_files = os.listdir(self._ANSWER_KEY_PATH)
        for f in answerkey_files:
            csv_file = pd.read_csv(os.path.join(self._ANSWER_KEY_PATH, f))

            poll_text = csv_file.columns[0]
            self.add_poll(poll_text)  # creating poll object
            self.format_poll_date(poll_text)

            # poll_file_name = poll_text[:-2]
            for question_text, answer in csv_file.values:
                if type(
                        answer
                ) == float:  # if the question in answer key has no answer it's a new poll
                    self.add_poll(question_text)
                    self.format_poll_date(question_text)
                    continue

                question_obj = self._question_list.get(question_text)
                if question_obj is None:
                    question_obj = question.Question(question_text)

                    answer_list = answer.split(';')
                    for ans in answer_list:
                        question_obj.add_answer_key(ans)

                self._polls[-1].add_question(
                    question_obj)  # add to the last poll in the list
                self._question_list.setdefault(
                    question_text,
                    question_obj)  # if not in dict already add the question
Example #6
0
def load_category(cat):
    """Given a category, opens the downloaded archive, serializes the relevant information about tossups, and
    then deserializes it into a new json to be loaded up by the main program"""

    questions = []
    bonuses = []
    with open(cat + 'dl.json', encoding='utf8') as fop:
        data = json.load(fop)
    for tossup in data["data"]["tossups"]:
        questions.append(
            question.Question(tossup["text"], unescape(tossup["answer"]), cat,
                              tossup["tournament"]["name"],
                              tossup["formatted_text"],
                              unescape(tossup["formatted_answer"])))
    for bonus in data["data"]["bonuses"]:
        for i in range(0, 3):
            bonus["formatted_answers"][i] = unescape(
                bonus["formatted_answers"][i])
            bonus["answers"][i] = unescape(bonus["answers"][i])
        bonuses.append(
            question.Bonus(bonus["leadin"], bonus["texts"], bonus["answers"],
                           cat, bonus["tournament"]["name"],
                           bonus["formatted_texts"],
                           bonus["formatted_answers"]))
    q_list = [obj.__dict__ for obj in questions]
    b_list = [obj.__dict__ for obj in bonuses]
    final = {"tossups": q_list, "bonuses": b_list}
    with open(cat + '.json', 'w', encoding='utf8') as fop:
        json.dump(final, fop)
Example #7
0
def get_ms_qs():
    questionlist = []
    pdf_names = []
    for year in range(2010, 2013):
        for i in range(1, 11):
            # pdf_names.append("round" + str(i) + ".txt")
            filename = "/round" + str(i) + ".txt"
            with open("MS/" + str(year) + filename) as f:
                text = f.read()
            if year == 2010:
                packet = text.split("Round")[0].split("Tossups")[1]
            else:
                packet = text.split("Round")[0]
            text = '1. '.join(re.split(r'1\.\s', text)[1:])
            text = "1. " + text
            text = text.split("Bonuses")[0]
            questions = re.split(r'[0-9]+\.\s', text)[1:]
            m = re.search(r'[0-9]+\.\s.*', text)
            while m:
                print(m.group())
                q = re.split(r'[0-9]+\.\s', m.group().split("ANSWER: ")[0])[1]
                a = m.group().split("ANSWER:")[1].strip()
                if '[' in a:
                    a = a.split('[')[0].strip()
                questionlist.append(question.Question(q, a, None, packet))
                text = text.replace(m.group(), "")

                m = re.search(r'[0-9]+\.\s.*', text)
            print("Packet " + str(i) + " complete!")
        print("year " + str(year) + " complete!")

    dick_list = [obj.__dict__ for obj in questionlist]
    with open('test2.json', 'w') as f:
        json.dump(dick_list, f)
    return questionlist
Example #8
0
def get_questions():
    questionlist = []
    pdf_names = []
    for i in range(1, 9):
        pdf_names.append("Round 0" + str(i) + ".pdf")
    for pdf_name in pdf_names:
        pdf_obj = open(pdf_name, "rb")
        pdf_reader = PyPDF2.PdfFileReader(pdf_obj)
        packet = ""
        for page in range(1, 7):
            page1 = pdf_reader.getPage(page)
            if page == 1:
                arr3 = re.split(r'(1\.\s)', page1.extractText())
                packet = arr3[0].split("-")[0]
                arr3[2] = arr3[1] + arr3[2]
                arr2 = re.split(r'<[A-Z][a-z]*>', arr3[2])

            else:
                arr2 = re.split(r'<[A-Z][a-z]*>', page1.extractText())
            arr2 = arr2[:arr2.__len__() - 1]

            for string in arr2:
                split_arr = string.split("ANSWER: ")
                ques = re.split(r'[0-9]\.\s',
                                split_arr[0].replace("\n", ""),
                                maxsplit=1)[1]
                answer = split_arr[1].replace("\n", "")
                if "[" in answer:
                    answer = answer.split("[")[0]
                questionlist.append(question.Question(ques, answer, packet))
    return questionlist
Example #9
0
 def get_questions_obj(self, root):
     qlist = self.get_questions()
     ret = []
     for elem in qlist:
         quest = question.Question(elem, root, self.get_sub_reg(elem))
         ret.append(quest)
     return ret
Example #10
0
    def prepare(self, confer_name):

        if Election().is_hes():
            self.root = 'hes'
        elif Election().is_hlr():
            self.root = 'hlr'
        else:
            raise Exception('Vigane serveritüüp')

        if not ElectionState().can_replace_candidates():
            print 'Selles hääletuse faasis (%s) valikuid muuta ei saa'\
                % ElectionState().str()
            return False

        self.reg = Election().get_sub_reg(self.elid)
        AppLog().set_app(confer_name, self.elid)
        AppLog().log('Valikute nimekirja välja vahetamine: ALGUS')
        self.quest = question.Question(self.elid, self.root, self.reg)

        self._ed = inputlists.Districts()
        self._ed.load(self.root, self.reg)

        self._backup_old_choices()
        print 'Valimised: ' + self.elid
        return True
Example #11
0
def test_Question_load_simple():
    """
    Test de lecture d'un fichier simple  avec des mutli lines sans fichier
    """
    mysetup("bob== hhh\ndes truc\n==\naa=bb\nccccccc=k\nbxb==xx\n\n\nxxx yyyy\n# des trucs \n==\n# doit pas apparaitre")
    q=question.Question("qtest.pl",root=".")
    myteardown()
    assert json.loads(q.json) == {"bob": "des truc\n", "ccccccc": "k", "bxb": "\n\nxxx yyyy\n# des trucs \n", "aa": "bb",'url': 'qtest.pl',}
def solve_trivia():
    try:
        question, answers = get_img_labels()
        question = q.Question(question)
        question.set_answers(answers)
        # print(question + answers)
        solve_question_answers(question)
    except:
        print('uh oh')
def getQuestion(questionNumber):
    global QUESTION_LIST_OF_DICTS
    loadQuestionData()
    if questionNumber >= len(QUESTION_LIST_OF_DICTS):
        raise utilities.OutOfQuestionsException(
            "There are only " + str(len(QUESTION_LIST_OF_DICTS)) +
            " questions available in category IRCWiki but you asked for question "
            + str(questionNumber))
    questionHash = QUESTION_LIST_OF_DICTS[questionNumber]
    correctAnswer = questionHash["Answer"]

    #make it into an integer if it's a written out integer like "twelve"
    correctAnswer = utilities.replaceTextIntegerWithInteger(correctAnswer)
    #print "correctAnswer", correctAnswer
    if isinstance(correctAnswer, (int, long)):
        answerType = "number"
        questionText = questionHash["Question"] + "  (a number)"
    else:
        correctAnswer = correctAnswer.lower()
        if correctAnswer.startswith("the "): correctAnswer = correctAnswer[4:]
        if correctAnswer.startswith("an "): correctAnswer = correctAnswer[3:]
        if correctAnswer.startswith("a "): correctAnswer = correctAnswer[2:]
        correctAnswer = correctAnswer.strip()
        if len(correctAnswer) == 0: raise Exception("Empty correctAnswer!")
        answerType = "text"
        words = wordCount(correctAnswer)
        questionText = questionHash["Question"]
        if words == 1:
            questionText += "  (" + str(words) + " word)"
        else:
            questionText += "   (format: " + utilities.fillNonBlanksWithX(
                correctAnswer) + ")"
            #questionText += "  (" + str(words) + " words)"
    questionPieces = [
        questionHash["Subcategory"], questionHash["Question"], answerType,
        correctAnswer
    ]
    explanationText = "The correct answer is '" + str(correctAnswer) + "'."
    difficulty = 1
    return question.Question(questionText=questionText,
                             correctAnswer=correctAnswer,
                             explanationText=explanationText,
                             answerType=answerType,
                             difficulty=difficulty,
                             questionPieces=questionPieces,
                             questionNumber=questionNumber,
                             category="irc trivia",
                             subCategory=questionHash["Subcategory"],
                             preambleText="",
                             answerOptions="",
                             answerScale="",
                             imageFile="",
                             explanationImageFile="",
                             imageUploadClient=None)
Example #14
0
    def get_question(self):
        if hasattr(self, "question"):
            return self.question
        else:
            if self.soup == None:
                self.parser()
            soup = self.soup
            question_link = soup.find("h2", class_="zm-item-title zm-editable-content").a
            url = "http://www.zhihu.com" + question_link["href"]
            title = question_link.string.encode("utf-8")

            question = question.Question(url, title)
            return question
Example #15
0
    def get_response(self):
        import binascii

        # load a random BDOC from the ones available
        otp_key = htscommon.get_verification_key(self._vote_id)
        elids = self._rreg.read_string_value(otp_key, "elids")\
                .value.rstrip().split("\t")
        bdoc = self.__load_bdoc(random.choice(elids))
        evlog.log("Sending BDOC %s with vote ID %s for verification" %\
                (ksum.votehash(bdoc.get_bytes()), self._vote_id))

        # check consistency
        bdoc_set = set([doc.split(".")[0] for doc in bdoc.documents])
        elids_set = set(elids)
        if bdoc_set != elids_set:
            evlog.log_error("Votes in BDOC for vote ID %s are inconsistent " \
                    "with registry: %s, %s" % (self._vote_id, bdoc_set, elids_set))
            raise HTSVerifyException, evcommon.VERIFY_ERROR

        # create question objects
        questions = []
        for elid in elids:
            questions.append(question.Question(\
                    elid, "hts", Election().get_sub_reg(elid)))

        # start assembling the response
        ret = ""

        # append questions
        for quest in questions:
            ret += quest.qname() + ":" + str(quest.get_type()) + "\t"
        ret += "\n"

        # append election IDs and votes
        for votefile in bdoc.documents:
            elid = votefile.split(".")[0]
            ret += elid + "\t" + binascii.b2a_hex(
                bdoc.documents[votefile]) + "\n"
        ret += "\n"

        # append choices list
        for quest in questions:
            tv = quest.get_voter(self._voter_code)
            if tv:
                ret += quest.choices_to_voter(tv)
            else:
                evlog.log_error("Voter not found")

        self.__decrease_count()
        return ret
Example #16
0
 def new_question(self, el_id, el_type, el_desc):
     if formatutil.is_valimiste_identifikaator(el_id):
         key = ['questions', el_id, 'common']
         self.reg.ensure_key(key)
         self.reg.create_string_value(key, ELECTION_ID, el_id)
         quest = question.Question(el_id, None, \
             evreg.Registry(root=self.reg.path(['questions', el_id])))
         g_common_keys = ['common/rights']
         quest.create_keys(g_common_keys)
         quest.set_type(int(el_type))
         quest.set_descr(el_desc)
         return quest
     else:
         raise Exception('Vigase formaadiga valimiste identifikaator')
Example #17
0
def test_question_save_to_dir():
    mysetup("a=b\nfiles=@ fortest3.py\n\n# doit pas apparaitre\[email protected]\[email protected]","gommo.pl")
    mysetup("lefichier pout les test 1 \n nom unix fotest1.py","fortest1.py")
    mysetup("lefichier g\n\n\n\n\n\n\n\n\n\n\n\ny","fortest2.py")
    mysetup("lefichier grader.py","fortest3.py")
    q=question.Question("gommo.pl",root=".")
    myteardown("gommo.pl")
    myteardown('fortest1.py')
    myteardown('fortest2.py')
    myteardown('fortest3.py')
    dirname = q.createdir("print(4)")
    assert len([x for x in dirname.iterdir()]) == 5
    from shutil import rmtree
    rmtree(str(dirname))
Example #18
0
    def parse_answer_keys(self):
        # adding attendance question
        question_text = "Are you attending this lecture?"
        question_obj = question.Question(question_text)
        self._question_list.setdefault(question_text, question_obj)
        question_obj.add_answer_key("Yes")

        self.add_poll("Attending_poll")
        poll_obj = self._polls[-1]
        poll_obj.add_question(question_obj)

        answerkey_files = os.listdir(self._ANSWER_KEY_PATH)
        for file_name in answerkey_files:
            question_numbers = [
                '1.', '2.', '3.', '4.', '5.', '6.', '7.', '8.', '9.', '10.'
            ]
            file_path = os.path.join(self._ANSWER_KEY_PATH, file_name)
            with open(file_path, 'r', encoding='utf8') as f:
                line = f.readline()
                while line != '':
                    splitted_line = line.strip().split()
                    if splitted_line != []:
                        if splitted_line[0] == 'Poll':
                            poll_number = splitted_line[1].split(':')
                            poll_text = splitted_line[0] + "_" + poll_number[
                                0] + "_" + "_".join(poll_number[1].split('-'))
                            self.add_poll(poll_text)
                        elif splitted_line[0] in question_numbers:
                            question_text = ' '.join(splitted_line[1:-3])
                            question_obj = question.Question(question_text)
                            self._question_list.setdefault(
                                question_text, question_obj)
                            self._polls[-1].add_question(question_obj)
                        elif splitted_line[0] == 'Answer':
                            question_obj.add_answer_key(' '.join(
                                splitted_line[2:]))
                    line = f.readline()
Example #19
0
def test_question_load_withfiles():
    """
    Test de lecture d'un fichier avec des mutli lines
    """
    mysetup("a=b\nfiles=@ fortest3.py\n\n# doit pas apparaitre\[email protected]\[email protected]")
    mysetup("lefichier pout les test 1 \n nom unix fotest1.py","fortest1.py")
    mysetup("lefichier g\n\n\n\n\n\n\n\n\n\n\n\ny","fortest2.py")
    mysetup("lefichier grader.py","fortest3.py")
    
    q=question.Question("qtest.pl",root=".")
    myteardown()
    myteardown('fortest1.py')
    myteardown('fortest2.py')
    myteardown('fortest3.py')
    assert json.loads(q.json) == {"a": "b", "basefiles": {"fortest1.py": "lefichier pout les test 1 \n nom unix fotest1.py\n", "fortest3.py": "lefichier grader.py\n", "fortest2.py": "lefichier g\n\n\n\n\n\n\n\n\n\n\n\ny\n"},'url': 'qtest.pl'}
Example #20
0
def test_question_init_load_id(monkeypatch):
    """
    Ensure passing a load_id argument to the Question will find and load
    the kwargs from a JSON file and instantiate the question
    """
    def mock_load(file): # pylint: disable=unused-argument
        """ Mock previous replay lists """
        return [[], [question_kwargs()]]
    monkeypatch.setattr(question, "load", mock_load)
    monkeypatch.setattr('builtins.open', mock_open(read_data=b''))
    test_q = question.Question(is_replay=True, load_id=question_kwargs().get('questionId'))
    expected = question_kwargs()
    assert test_q.id == expected.get('questionId')
    assert test_q.text == expected.get('question')
    assert test_q.prediction == expected.get('prediction')
Example #21
0
    def load_from_file(self, dir):
        file = open(dir, "r")

        whole_file_string = file.read()
        segments = whole_file_string.split("//")

        self.video_dir = segments[0]
        self.time_interval = segments[1]
        for i in range(2, len(segments) - 1):
            partition = segments[i].split(" - ")
            temp_data = json.loads(partition[1])
            temp_question = question.Question()
            temp_question.set_question(partition[0])
            temp_question.set_data(temp_data)

            self.questions.append(temp_question)
Example #22
0
 def ajouterQuestion(self, idQuestion, enonce, reponse, idThemes,
                     idCompetences, discriminations, facilite):
     for k in self.competences:
         if not k in discriminations:
             if k in idCompetences:
                 discriminations[k] = 1
             else:
                 discriminations[k] = -1
     self.questions[idQuestion] = question.Question(
         idQuestion,
         enonce,
         reponse,
         themes=[self.themes[i] for i in idThemes],
         competences=[self.competences[i] for i in idCompetences],
         discriminations=discriminations,
         facilite=facilite)
Example #23
0
    def prepare(self, confer_name, server_root):

        self.root = server_root

        if not ElectionState().can_load_conf():
            print 'Selles hääletuse faasis (%s) valimisinfot laadida ei saa'\
                % ElectionState().str()
            return False

        self.reg = Election().get_sub_reg(self.elid)
        AppLog().set_app(confer_name, self.elid)
        AppLog().log('Valimiste failide laadimine: ALGUS')
        self.quest = question.Question(self.elid, self.root, self.reg)
        self.quest.reset_data()

        print 'Valimised: ' + self.elid
        return True
Example #24
0
 def handle_starttag(self, tag, attrs):
     dict = {}
     for value in attrs:
         dict[value[0]] = value[1]
     attrs = dict
     if(tag == 'form' and not self.submit_url):
         url = attrs['action']
         if(self.re_submit_url.search(url)):
             self.submit_url = url
             print(self.submit_url)
             self.capture_hidden = True
     elif(tag == 'div'):
         if('id' in attrs and 'class' in attrs and
             attrs['class'] == 'fb_frage'):
             print("Found question: " + attrs['id'])
             id = int(self.re_question_id.search(attrs['id']).group(0))
             self.current_question = question.Question(id)
             self.questions.append(self.current_question)
             self.capture_question_data = True
     elif(tag == 'input'):
         if(attrs['type'] == 'checkbox' and self.current_question):
             print("Found answer: " + attrs['id'])
             self.current_question.type = question.Question.Type.multiple_choice
             id = int(self.re_answer_id.search(attrs['id']).group(0))
             self.current_answer = question.Answer(id)
             self.current_question.answers.append(self.current_answer)
         elif(attrs['type'] == 'text' and self.current_question and
             'id' in attrs):
             print("Found input field for answer")
             id = int(self.re_answer_id.search(attrs['id']).group(0))
             self.current_answer = question.Answer(id)
             self.current_question.type = question.Question.Type.text
             self.current_question.answers.append(self.current_answer)
         elif(attrs['type'] == 'hidden' and self.capture_hidden):
             self.hidden_data[attrs['name']] = attrs['value']
     elif(tag == 'label'):
         if('id' in attrs and 'style' in attrs and 'for' in attrs):
             self.capture_answer_data = True
     elif(tag == 'video'):
         if(self.current_question and 'poster' in attrs and
             self.re_media_pic_url.search(attrs['poster'])):
             self.current_question.media = attrs['poster'];
     elif(tag == 'img'):
         if(self.current_question and 'src' in attrs and
             self.re_media_pic_url.search(attrs['src'])):
             self.current_question.media = attrs['src'];
Example #25
0
 def handle_starttag(self, tag, attrs):
     dict = {}
     for value in attrs:
         dict[value[0]] = value[1]
     attrs = dict
     if(tag == 'div'):
         if('id' in attrs and 'class' in attrs and
             attrs['class'] == 'fb_frage'):
             print("Found question: " + attrs['id'])
             id = int(self.re_question_id.search(attrs['id']).group(0))
             self.current_question = question.Question(id)
             self.questions.append(self.current_question)
             self.capture_question_data = True
         elif('class' in attrs and attrs['class'] == 'fb_frage_antwort'):
             print("Found answer: " + attrs['id'])
             id = int(self.re_answer_id.search(attrs['id'],
                 self.re_answer_id.search(attrs['id']).end()).group(0))
             self.current_answer = question.Answer(id)
             self.current_question.answers.append(self.current_answer)
         elif((not ('class' in attrs or 'id' in attrs)) and
             self.current_answer and not self.current_answer.answer and
             self.current_question.type == question.Question.Type.multiple_choice):
             self.capture_answer_data = True
     elif(tag == 'img'):
         if('src' in attrs and attrs['src'] ==
             '/fileadmin/fahrschulboegen/online/pics/checked_soll.gif' and
             self.current_question):
             self.current_question.type = question.Question.Type.multiple_choice
             print("Correct answer is " + str(self.current_answer.id))
             self.current_question.correct_answers.append(self.current_answer)
         elif(self.current_question and 'src' in attrs and
             self.re_media_pic_url.search(attrs['src'])):
             self.current_question.media = attrs['src'];
     elif(tag == 'b'):
         if(self.current_question and self.current_answer and
             not self.current_question.type):
             self.current_question.type = question.Question.Type.text
             self.capture_answer_data = True
     elif(tag == 'label'):
         if('id' in attrs and 'style' in attrs and 'for' in attrs):
             self.capture_answer_data = True
     elif(tag == 'video'):
         if(self.current_question and 'poster' in attrs and
             self.re_media_pic_url.search(attrs['poster'])):
             self.current_question.media = attrs['poster'];
def simpleMathQuestionA(questionNumber):
    utilities.setRandomSeed(questionNumber)

    while True:
        v = randomParameters()
        verifyStringOfFormula(
            v)  #check that our string representation hasn't failed
        equationStr = formulaString(v)
        trueValue = formulaCalculate(v)
        if trueValue > MIN_ALLOWED_ABS_VALUE and trueValue < MAX_ALLOWED_ABS_VALUE:
            break

    comparisonValue = generateComparisonValue(trueValue)
    comparisonWord, inequality, correctAnswer = utilities.pickComparisonDirection(
        trueValue, comparisonValue)
    difficulty = 1.0 / (abs(comparisonValue - trueValue + .00001) /
                        (trueValue + 1.0))

    questionText = equationStr + "   " + inequality + "   " + str(
        comparisonValue)

    correctInequaltiyText = getCorrectInequalityText(trueValue,
                                                     comparisonValue)

    questionPieces = [equationStr, trueValue, inequality, comparisonValue]
    explanationText = str(
        equationStr) + "  =  " + utilities.numberToReasonableRoundedString(
            trueValue
        ) + correctInequaltiyText + utilities.numberToReasonableRoundedString(
            comparisonValue)
    return question.Question(questionText=questionText,
                             correctAnswer=correctAnswer,
                             explanationText=explanationText,
                             answerType="true-false",
                             difficulty=difficulty,
                             questionPieces=questionPieces,
                             questionNumber=questionNumber,
                             category="simple math",
                             subCategory="A",
                             preambleText="",
                             answerOptions=["True", "False"],
                             answerScale="",
                             imageFile="",
                             explanationImageFile="",
                             imageUploadClient=None)
Example #27
0
    def submit(self, widget):
        try:
            self.parent.set_time(int(self.time_input.get_text()))
        except:
            self.parent.set_time(1000)

        while (not len(self.cur_questions) == 0):
            self.cur_questions.pop()
        for i in range(0, self.number_of_questions):
            print("(" + str(i) + ") Adding to current: " +
                  self.question_names[i].get_text())
            new_question = question.Question()
            new_question.set_question(self.question_names[i].get_text())
            if self.question_binary_buttons[i].get_active():
                new_question.set_type("binary")
            if self.question_slider_buttons[i].get_active():
                new_question.set_type("slider")

            self.cur_questions.append(new_question)
        print(" -------------------- ")
        self.destroy()
Example #28
0
 def restore_init_status(self):
     if self.is_hes():
         self.reg.truncate_value(['common'], evcommon.APPLICATION_LOG_FILE)
         self.reg.truncate_value(['common'], evcommon.ERROR_LOG_FILE)
         self.reg.truncate_value(['common'], evcommon.VOTER_LIST_LOG_FILE)
         self.reg.truncate_value(['common'], evcommon.DEBUG_LOG_FILE)
         self.reg.ensure_no_key(['common', 'nonewvoters'])
     if self.is_hts():
         self.reg.truncate_value(['common'], evcommon.APPLICATION_LOG_FILE)
         self.reg.truncate_value(['common'], evcommon.ERROR_LOG_FILE)
         self.reg.truncate_value(['common'], evcommon.OCSP_LOG_FILE)
         self.reg.truncate_value(['common'], evcommon.STATUSREPORT_FILE)
         self.reg.truncate_value(['common'], evcommon.VOTER_LIST_LOG_FILE)
         for i in self.get_questions():
             quest = question.Question(i, 'hts', self.get_sub_reg(i))
             quest.create_log_files()
             quest.create_revlog()
             self.reg.delete_sub_keys(['questions', i, 'hts', 'votes'])
             self.reg.delete_sub_keys(['questions', i, 'hts', 'output'])
     if self.is_hlr():
         pass
Example #29
0
def read_questions(snq_dir_path):
    question_list = []
    directory = os.fsencode(snq_dir_path)
    os.chdir(snq_dir_path)
    current_directory = os.getcwd()

    for question_file in os.listdir(current_directory):
        with open(question_file, "r") as current_file:
            lines = current_file.readlines()
        question_ID = str(lines[0][0:-1])
        data_string = str(lines[1][0:-1])
        question_string = str(lines[2][0:-1])
        correct_answer = str(lines[3][0:-1])

        question_dict = {}
        for answer_choice_line in lines[4:]:
            key = answer_choice_line[0:1]
            value  = answer_choice_line[4:-1]
            question_dict[str(key)] = value
        question_list.append(question.Question(question_ID, data_string, question_string, question_dict, correct_answer))
    return question_list
Example #30
0
 def __init__(self, running_sugar=True):
     self.running_sugar = running_sugar
     #Initialize questions - need to do lazy loading to speed up game init
     self.question_lists = []
     qfIO = question.QuestionFileIO()
     for question_file in QUESTION_FILES:
         try:
             #print question_file
             question_list = qfIO.Read_questions(data_path(question_file))
         except question.ParseError:
             print 'Problem parsing file, using random questions.'
             qs = []
             for j in range(100):
                 q = (random.randint(0,9),
                      random.randint(0,9))
                 question_string = '%i x %i = ?' % q
                 answer = '%i' % (q[0]*q[1])
                 qs.append(question.Question(question_string,
                                                          answer))
                 question_list = question.QuestionList(qs)
         self.question_lists.append(question_list)
     self.question_group = question.QuestionGroup(self.question_lists)