Esempio n. 1
0
    def readReportFile(self, fileName, usedPolls):
        number = 0
        with open(fileName, 'r', encoding='utf-8') as file:
            reader = csv.reader(file)
            poll1 = Poll("poll1", [], [])
            for row in reader:
                questions = []
                for i in range(4, len(row) - 1):
                    if i % 2 == 0:
                        # Create a question and add the answer
                        question = Question("".join(row[i].splitlines()))
                        question.setAnswer(row[i + 1])
                        questions.append(question)
                        poll1.questions.append(question)

                # find which student, and which poll then create that poll and add the student's polls
                for student in self.students:
                    if student.checkStudent(row[1]):
                        for poll in self.allPolls:
                            if poll.checkPoll(questions):

                                if poll.answerKeys[0].used == False:
                                    temp_poll = Poll(poll.pollName,
                                                     poll.answerKeys,
                                                     poll.questions)
                                    usedPolls.append(temp_poll)
                                count = 0
                                for poll in usedPolls:
                                    if poll.pollName == usedPolls[
                                            len(usedPolls) - 1].pollName:
                                        count = count + 1
                                if poll.answerKeys[0].used == False:
                                    if count > 1:
                                        usedPolls[
                                            len(usedPolls) -
                                            1].pollName = usedPolls[
                                                len(usedPolls) -
                                                1].pollName + "-" + str(count)
                                poll.answerKeys[0].used = True

                                number = number + 1
                                temp = Poll(temp_poll.pollName,
                                            temp_poll.answerKeys,
                                            temp_poll.questions)
                                temp.questions = poll1.questions
                                temp.setDate(row[3])
                                student.addPoll(temp)

                poll1.questions = []
            for poll in self.allPolls:
                poll.answerKeys[0].used = False
Esempio n. 2
0
def __findStudentAnswers__(students, polls):
    global firstQuestion, answer, answerStartIndex, answerFinishIndex
    for student in students:
        for stdPoll in student.pollDict:  # POLL1 POLL1* POLL3
            QuestionAndAnswer = []
            index = 0
            tempPollName = stdPoll
            if type(tempPollName) is int:
                tempPollName = "UNNAMED"
            while tempPollName[len(tempPollName) - 1] == '§':
                tempPollName = tempPollName[0:len(tempPollName) - 1]
            for poll in polls:  # POLL1 POLL3
                if poll.pollName == tempPollName:
                    allText = student.pollDict.get(stdPoll)
                    questions_arr = list(reversed(poll.QuestionAndAnswers))
                    i = 0
                    while i < len(questions_arr):
                        if allText.find(questions_arr[i].get(
                                'Q')) != -1:  # ilk soruyu buldu
                            firstQuestion = questions_arr[i].get('Q')
                            answerStartIndex = allText.find(
                                questions_arr[i].get('Q')) + len(
                                    questions_arr[i].get('Q')) + 1
                            j = i + 1
                            isfind = 0
                            while j < len(questions_arr):
                                if allText.find(
                                        questions_arr[j].get('Q')) != -1:
                                    isfind = 1
                                    answerFinishIndex = allText.find(
                                        questions_arr[j].get('Q')) - 1
                                    answer = allText[
                                        answerStartIndex:answerFinishIndex]
                                    break
                                else:
                                    j += 1
                            if isfind == 0:
                                answer = allText[answerStartIndex:-1]
                            isCorrect = 0
                            if answer == questions_arr[i].get('A'):
                                isCorrect = 1
                            answer_arr = answer.split(";")
                            for ans in answer_arr:
                                poll.__addAllAnswers__(firstQuestion, ans)
                            questionanswer = {
                                'Q': firstQuestion,
                                'A': answer_arr,
                                'C': isCorrect
                            }
                            QuestionAndAnswer.insert(index, questionanswer)
                            index += 1
                        i += 1
            newPoll = Poll(stdPoll, QuestionAndAnswer)
            student.__initPollNameAndQuestionAndAnswer__(newPoll)
Esempio n. 3
0
    def create_poll(self, channel_id, poll_args, msg_id):
        logger.info("Creating new poll with arguments %s"  % poll_args)
        if len(poll_args) < 2:
            usage = "Error, usage: @botname poll <poll_title> <option_1> .. <option_10>"
            self.send_message(msg=usage, channel_id=channel_id)
            logger.info("Not enough arguments provided, aborting poll creation.")
            return
        title = poll_args[0]
        vote_options = poll_args[1:]
        poll = Poll(poll_title=title, vote_options=vote_options)
        poll.creation_msg = msg_id
        message,attachments = poll.create_message()
        callback = self.send_message(msg=message, channel_id=channel_id,attachments=None).json()
        poll.poll_msg = callback['message']['_id']
        # add reaction for each vote_option.
        for reaction, option in poll.reaction_to_option.items():
            self.api.chat_react(msg_id=poll.poll_msg, emoji=reaction)
        # add +1,+2,+3,+4
        for reaction in EmojiStorage.DEFAULT_PEOPLE_EMOJI_TO_NUMBER.keys():
            self.api.chat_react(msg_id=poll.poll_msg, emoji=reaction)

        self.msg_to_poll[poll.poll_msg] = poll
        pickle.dump(self.msg_to_poll,file=open(self.dump_file,'wb'))
        return poll
Esempio n. 4
0
def vote_command():
    if request.method == "GET":
        return "The voting machine is up and running."

    token = request.form["token"]
    requested = request.form["text"]

    print("%s - %s:%s - %s" %
          (request.form["user_name"], request.form["channel_name"],
           request.form["channel_id"], request.form["text"]))

    if "register" in requested:
        command = requested.split(" ")
        slack_url = command[1]
        slack_token = command[2]
        result = Poll.register_slack_account(slack_url, slack_token)
        return result

    if not Poll.validate_token(token):
        return "This Slack Account hasn't been registered with the polling application.\n" \
               "Please run `/poll register [incoming webhook url] [slash command token]`"

    try:
        requested = request.form["text"]
        if "help" in requested:
            return "*Help for /poll*\n\n" \
                   "*Start a poll:* `/poll create [question] options [option1] --- [option2] --- [option3]`\n" \
                   "*End a poll:* `/poll close` (The original poll creator must run this)\n" \
                   "*Cast a Vote:* `/poll cast [option number]`\n" \
                   "*Get number of votes cast so far:* `/poll count`"

        if "create" in requested and "options" in requested:
            print "Creating a new poll"
            return Poll.create(token, request)

        elif "cast" in requested:
            print "Casting a vote"
            return Poll.cast(token, request)

        elif "count" in requested:
            print "Getting vote count"
            return Poll.count(token, request)

        elif "close" in requested:
            print "Closing a poll"
            return Poll.close(token, request)

        else:
            return "Unknown request recieved"
    except requests.exceptions.ReadTimeout:
        return "Request timed out :("
    except Exception as e:
        print traceback.format_exc()
        return "Oh no! Something went wrong!"
Esempio n. 5
0
def vote_command():
    if request.method == "GET":
        return "The voting machine is up and running."

    token = request.form["token"]
    requested = request.form["text"]

    print json.dumps(request.form, sort_keys=True, indent=4)
    print ("%s - %s:%s - %s" % (request.form["user_name"], request.form["channel_name"], request.form["channel_id"], request.form["text"]))

    if "register" in requested:
        command = requested.split(" ")
        slack_url = command[1]
        slack_token = command[2]
        result = Poll.register_slack_account(slack_url, slack_token)
        return result

    if not Poll.validate_token(token):
        return "This Slack Account hasn't been registered with the polling application.\n" \
               "Please run `/poll register [incoming webhook url] [slash command token]`"

    try:
        requested = request.form["text"]
        if "help" in requested:
            return "*Help for /poll*\n\n" \
                   "*Start a poll:* `/poll create [question] options [option1] | [option2] | [option3]`\n" \
                   "*End a poll:* `/poll close` (The original poll creator must run this)\n" \
                   "*Cast a Vote:* `/poll cast [option number]`\n" \
                   "*Get number of votes cast so far:* `/poll count`"

        if "create" in requested and "options" in requested:
            print "Creating a new poll"
            return Poll.create(token, request)

        elif "cast" in requested:
            print "Casting a vote"
            return Poll.cast(token, request)

        elif "count" in requested:
            print "Getting vote count"
            return Poll.count(token, request)

        elif "close" in requested:
            print "Closing a poll"
            return Poll.close(token, request)

        else:
            return "Unknown request recieved"
    except requests.exceptions.ReadTimeout:
        return "Request timed out :("
    except Exception as e:
        print traceback.format_exc()
        return "Oh no! Something went wrong!"
Esempio n. 6
0
def __readAnswerKeys__(filename):
    with open(filename) as csv_file:
        csv_reader = csv.reader(csv_file)
        line_count = 0
        pollName = ""
        question_answer_list = []
        for row in csv_reader:
            if line_count == 0:
                pollName = row[
                    0]  # poll name dönüyor, array olduğu için column 0. indexi alıyoruz
                pollName = __beautify__(pollName)

                line_count += 1
            else:
                i = 0
                for columns in row:
                    columns.replace(chr(8230), '')
                    arr = columns.split(';')
                    arr[0] = arr[0][1:-1]
                    arr[0] = __beautify__(arr[0])
                    aranswer = ""
                    control = 0
                    for ar in arr:
                        if control == 0:
                            control += 1
                            continue
                        if control == 1:
                            aranswer += ar
                        else:
                            aranswer = aranswer + ";" + ar
                        control += 1
                    aranswer = aranswer[1:-1]
                    aranswer = __beautify__(aranswer)
                    questionanswer = {'Q': arr[0], 'A': aranswer, 'U': set()}
                    question_answer_list.insert(i, questionanswer)
                    i += 1
                    line_count += 1
        pollNameArr = pollName.split(":")
        pollNameName = "".join(pollNameArr[0])
        print(pollNameName)
        pollObject = Poll(pollNameName, question_answer_list)
        return pollObject
Esempio n. 7
0
    def readAnswerKey(self, fileName):
        with open(fileName, 'r', encoding='utf-8') as file:
            keys = []
            questions = []
            reader = csv.reader(file)
            poll_name = ""
            is_first_line = True
            for row in reader:
                # Set the name of the poll
                if is_first_line:
                    poll_name = row[0]
                    is_first_line = False
                else:
                    # Get question text and create Question
                    questionKey = Question("".join(row[0].splitlines(
                    )))  # for question with correct answers
                    question = Question(
                        row[0]
                    )  # to add the question to the poll without any answers given
                    questions.append(question)

                    # Create an answer key for the poll
                    answer_key = AnswerKey(poll_name, questionKey,
                                           row[1:len(row)])
                    answer_key.trace()
                    # Keep the answer keys
                    keys.append(answer_key)

            if len(questions) != 0:
                if len(self.allPolls) == 0:
                    poll = Poll(poll_name, keys, questions)
                    poll.trace()
                    self.allPolls.append(poll)

                elif self.allPolls[0].pollName != answer_key.poll_name:
                    poll = Poll(poll_name, keys, questions)
                    poll.trace()
                    self.allPolls.append(poll)
    def assignPoll(self, Polls, answerkeyPolls, column, IndexOfanswerkeyPolls,
                   dateofpoll, students):
        w = 0

        answers = []
        pollName = answerkeyPolls[IndexOfanswerkeyPolls].pollName
        answerLength = int(answerkeyPolls[IndexOfanswerkeyPolls].answerLength)
        pollNumber = int(answerkeyPolls[IndexOfanswerkeyPolls].pollNumber)
        while w < answerLength:
            questionsInPoll = column[4 + w * 2].replace("\n", "")
            questionsInPoll = questionsInPoll.replace(" ", "")
            questionsInPoll = questionsInPoll.replace("\t", "")
            questionsInPoll = re.sub("[^0-9a-zA-Z]+", "", questionsInPoll)
            g = 0
            while g < len(answerkeyPolls[IndexOfanswerkeyPolls].answers):
                answerkeyquestionText = answerkeyPolls[
                    IndexOfanswerkeyPolls].answers[g].questionText.replace(
                        "\n", "")
                answerkeyquestionText = answerkeyquestionText.replace(" ", "")
                answerkeyquestionText = answerkeyquestionText.replace("\t", "")
                answerkeyquestionText = re.sub("[^0-9a-zA-Z]+", "",
                                               answerkeyquestionText)

                if questionsInPoll == answerkeyquestionText:
                    answer = Answer(
                        answerkeyPolls[IndexOfanswerkeyPolls].answers[g].
                        questionText, answerkeyPolls[IndexOfanswerkeyPolls].
                        answers[g].answer)
                    answers.append(answer)
                g += 1

            w += 1
        poll = Poll.Poll(answerLength, answers, pollName, pollNumber)
        dateofpoll.append(" ")
        k = 0
        while k < len(students):
            students[k].answerof.append([])
            k = k + 1
        Polls.append(poll)
        return Polls
Esempio n. 9
0
  File "<pyshell#3>", line 1, in <module>
    from polls.model import Poll, Choice
ImportError: No module named model
>>> from polls.models import Poll, Choice
>>> Polls.objects.all()

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    Polls.objects.all()
NameError: name 'Polls' is not defined
>>> Poll.objects.all()
[]
>>> 
from django.utils import timezone
>>> p = Poll(question="What's new?", pub_date=timezone.now())
>>> p.id
>>> p.save()
>>> p.id
1L
>>> p.question
"What's new?"
>>> p.pub_date
datetime.datetime(2013, 7, 17, 0, 58, 57, 952743, tzinfo=<UTC>)
>>> p.question = "what's up?"
>>> p.save()
>>> Poll.objects.all()
[<Poll: Poll object>]
>>> ================================ RESTART ================================
>>> from polls.models import Poll,Choice

Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    def read_and_assign_answerkey(self, answerkeyPolls, name, QuestionTypes,
                                  AllAnswerTextIncludes, AllPollTextIncludes,
                                  AnswerKeyCont):
        whichRow = 0
        numOfAllPolls = 0
        inWhichPoll = -1
        PollsA = []
        pollname = ""
        pollNumber = 0
        polllength = 0
        inWhichQuestion = -1
        pollquestions = ""
        pollanswers = []
        pollanswersForEachQuestion = []
        inputAnswer = Answer("", "")
        try:
            file = open(name + AnswerKeyCont, "r", encoding="utf-8")
            for i in file:  # Tıpkı listeler gibi dosyanın her bir satırı üzerinde geziniyoruz.
                if i != "\n":
                    if whichRow == 0:
                        str = i
                        str = inputAnswer.getNumbers(str)
                        numOfAllPolls = str[0]

                    elif AllPollTextIncludes[0] and AllPollTextIncludes[1] in i:
                        inWhichPoll += 1
                        if inWhichQuestion != -1 and inWhichPoll != 0:
                            answer = Answer(pollquestions,
                                            pollanswersForEachQuestion)
                            pollanswers.append(answer)
                            pollquestions = ""
                            pollanswersForEachQuestion = []

                        if inWhichPoll != 0:
                            poll = Poll.Poll(polllength, pollanswers, pollname,
                                             pollNumber)
                            PollsA.append(poll)
                            pollanswers = []
                            polllength = 0
                            pollname = ""
                            inWhichQuestion = -1
                        str = i
                        str = str.split(":")
                        pollNumber = str[0].split()
                        pollNumber = pollNumber[-1]
                        str = str[1].split("\t")
                        pollname = str[0]
                        str = str[1].split()
                        polllength = str[0]

                    elif (QuestionTypes[0] in i) or (QuestionTypes[1] in i):
                        inWhichQuestion += 1
                        if inWhichQuestion != 0:
                            answer = Answer(pollquestions,
                                            pollanswersForEachQuestion)
                            pollanswers.append(answer)
                            pollquestions = ""
                            pollanswersForEachQuestion = []

                        str = i
                        str = str.split(". ", 1)
                        if QuestionTypes[0] in str[1]:
                            str = str[1].split(QuestionTypes[0])
                        elif QuestionTypes[1] in str[1]:
                            str = str[1].split(QuestionTypes[1])
                        pollquestions = str[0]

                    elif AllAnswerTextIncludes[0] and AllAnswerTextIncludes[
                            1] in i:
                        str = i
                        str = str.split(" ", 2)
                        str = str[2].split("\n")
                        pollanswersForEachQuestion.append(str[0])

                    else:
                        str = i
                        str = inputAnswer.getNumbers(str)
                    whichRow += 1
            file.close()
        except FileNotFoundError:
            print("File is not found....")

        if (inWhichQuestion != -1) and inWhichPoll != 0:
            answer = Answer(pollquestions, pollanswersForEachQuestion)
            pollanswers.append(answer)
            pollquestions = ""
            pollanswersForEachQuestion = []
        if inWhichPoll != 0:
            poll = Poll.Poll(polllength, pollanswers, pollname, pollNumber)
            PollsA.append(poll)

        answerkeyPolls = PollsA
        return answerkeyPolls
Esempio n. 11
0
def main(debug=False, disabledCommands=[], reloaded=False):
    if not reloaded:
        h=logging.StreamHandler()
        h.setLevel(logging.DEBUG)
        f=logging.Formatter("[%(name)s] (%(asctime)s) %(levelname)s: %(message)s")
        h.setFormatter(f)
        log.addHandler(h)
        log.setLevel(logging.INFO)
    #We need some special settings. Set it
    Global.set_script_settings()
    for x in dir(LadderLogHandlers):
        if not x[0].isupper():
            continue
        if inspect.isfunction(getattr(LadderLogHandlers,x)):
            x="".join([i.upper() if i.islower() else "_"+i for i in x])
            Armagetronad.SendCommand("LADDERLOG_WRITE"+x+" 1") # X has already a underscore at beginning.
    if not reloaded:
        if Global.debug:
            log.info("Starting in debug mode.")
            Player.enableLogging(logging.DEBUG)
            Team.enableLogging(logging.DEBUG)
            LadderLogHandlers.enableLogging(logging.DEBUG)
            Poll.enableLogging(logging.DEBUG)
        else:
            Player.enableLogging(logging.WARNING)
            Team.enableLogging(logging.WARNING)
            LadderLogHandlers.enableLogging(logging.INFO)
            Poll.enableLogging(logging.WARNING)

    Commands.disabled=Commands.disabled+disabledCommands    
    #Init
    AccessLevel.load()
    if not reloaded:
        log.info("Script started")    
        Armagetronad.PrintMessage("0xff0000Script started")
    else:
        log.info("Script reloaded")
    #We need to refresh player list
    Global.reloadPlayerList()
    while(True):
        line=""
        if Global.handleLadderLog==False:
            time.sleep(1)
            continue
        try:
            line=input()
        except KeyboardInterrupt:
            log.info("Exiting")
            break
        line=line.strip()
        keywords=line.split(" ")
        command=keywords[0]
        args=keywords[1:]
        del keywords
        #make command name CamelCase
        real_commandname=command.upper()
        command=command.lower()
        command=command.replace("_"," ")
        command=command.title()
        command=command.replace(" ","")
        #call handler
        if(hasattr(LadderLogHandlers,command) ):
                getattr(LadderLogHandlers,command)(*args)
        if real_commandname in LadderLogHandlers.extraHandlers:
            for extraHandler in LadderLogHandlers.extraHandlers[real_commandname]:
                try: extraHandler(*args)
                except TypeError as e: 
                    log.error("Extension "+extraHandler.__package__+" registered a wrong ladderlog handler. This is a bug.")
                    if debug: raise e
Esempio n. 12
0
name=" "
line_count=0
with open(str(readPath) + ".csv", encoding='utf-8') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    for column in csv_reader:
        if line_count <= 3:
            if line_count==3:
                name=column[0]
            print(f'Column names are {", ".join(column)}')
        line_count += 1


#READING ANSWER KEYS AND ASSIGN IT TO answerkeyPolls
answerkeyPolls = inputAnswer.read_and_assign_answerkey(answerkeyPolls,name,QuestionTypes,AllAnswerTextIncludes,AllPollTextIncludes,AnswerKeyCont)

inputPoll =Poll.Poll("", "", "","")
inputPoll2=Global.Global("", "")

line_count = 0


attendancedate=""

with open(str(readPath) + ".csv", encoding='utf-8') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    for column in csv_reader:
        if line_count <= 5:
            print(f'Column names are {", ".join(column)}')
            line_count += 1
        else:
            pollFullname = column[1]
Esempio n. 13
0
def fiveMinPoll(sec):
	while True:
		Poll.run(sensor)
		sleep(sec)