def operation2(self, op, element):
        """ 
        similar to normal operation but it happens when we have a sign
        before the number - i.e. the operation happens to the top of 
        the stack
        """
        op_dict = { "+" : (lambda x, y : x + y),\
                    "-" : (lambda x, y : x - y),\
                    "/" : (lambda x, y : x // y),\
                    "%" : (lambda x, y : x % y),\
                    "*" : (lambda x, y : x * y),\
                    "^" : (lambda x, y : pow(x,y))}

        if self.stack_ok("Operation2"):
            if self.operation_ok(op, element):
                self.stack[-1] = self.saturate(op_dict[op](\
                                                    self.stack[-1],\
                                                    element))

            elif op == "/":
                return Result(RT.ER, Error(ERROR.DIV0))

            return Result(RT.OP, self.stack[-1])

        elif self.stack_ok("stack empty?"):
            """
            if the stack is empty then we just add the result to the
            stack
            """
            return Result(RT.ER, Error(ERROR.ST_UNDRF,2))

        else:
            return Result(RT.ER, Error(ERROR.ST_UNDRF))
 def action(self, action):
     """
     Defines the return for for 
     """
     if self.stack_ok("stack empty?"):
         actions = { "d" : Result(RT.DT, -2147483648),\
                 "=" : Result(RT.ER, Error(ERROR.ST_EMPTY))}
     else:
         actions = { "d" : Result(RT.DS, self.stack),\
                 "=" : Result(RT.DT, self.stack[-1])}
     return actions[action]
    def insert_data(self, data):
        """ 
        inserts data into the stack and returns a Result containing the
        last number inserted
        """
        if self.stack_ok("Insert"):
            data = self.saturate(data)
            self.stack.append(data)
            return Result(RT.IN,data)

        else: # stack overflow
            return Result(RT.ER,Error(ERROR.ST_OVRFL))
    def create_list(self, element):
        try:
                if self.is_number(element): # check if it is a number
                    # print("is number")
                    element = int(element)
                    result = self.insert_data(element)
                    self.prepare_response(result)

                elif self.is_op(element):   # check if it is an operation
                    self.prepare_response(self.operation(element))

                elif self.is_action(element): # check if it is an action
                    #print("is action")
                    self.prepare_response(self.action(element))

                elif self.is_eval(element): # check if it is a simple evaluation
                    #print("is eval")
                    element = self.prepare_eval(element)
                    self.prepare_response(self.evaluate(element))

                elif self.is_special_eval(element): 
                    response = self.sp_eval(element)
                    self.prepare_response(response)
                    if response.code == RT.ER and \
                            response.data == Error(ERROR.ST_UNDRF,2):
                        self.prepare_response(self.evaluate(element[1:]))

                else:
                    if element == "":
                        self.prepare_response(Result(RT.DO_NOTHING))

                    else:
                        for letter in element:
                            self.prepare_response(\
                                    Result(RT.ER, Error(ERROR.UNRECOGN, letter)))

        except Exception as e:
            print(e)
    def operation(self, op):
        op_dict = { "+" : (lambda x, y : x + y),\
                    "-" : (lambda x, y : x - y),\
                    "/" : (lambda x, y : x // y),\
                    "%" : (lambda x, y : x % y),\
                    "*" : (lambda x, y : x * y),\
                    "^" : (lambda x, y : pow(x,y))}

        if self.stack_ok("Operation"):
            if self.operation_ok(op):
                self.stack[-2] = self.saturate(op_dict[op](\
                                                    self.stack[-2],\
                                                    self.stack[-1]))
                self.stack.pop(-1)

            elif op == "/":
                return Result(RT.ER, Error(ERROR.DIV0))


            return Result(RT.OP, self.stack[-1])

        else:
            return Result(RT.ER, Error(ERROR.ST_UNDRF))
示例#6
0
文件: main.py 项目: pbexe/DQS
def quiz(category, save):
    """Allows the user to complete the quiz

    Arguments:
        school {School} -- The school that the quiz is currently set up for
        year {Year_Group} -- The year-group that the quiz is currently set up
        for
        category {str} -- The category that the questions shall be for
        save {Save} -- The save file that shall be saved to disk
    """

    while 1:
        school = None
        year = None
        if save.schools:
            school_choice = print_menu(
                "Please choose a school",
                [school.name for school in save.schools])
            school = save.schools[school_choice]
        else:
            print(
                "There are currently no schools to pick from. Please add a school to continue"
            )
            break
        if school:
            if school.year_groups:
                yeargroup_choice = print_menu(
                    "Please choose a year-group",
                    [year.year for year in school.year_groups])
                year = school.year_groups[yeargroup_choice]
            else:
                print(
                    "There are currently no year-groups to pick from with your current choice of school. Please add a yeargroup to continue"
                )
        else:
            print("Please set a school before setting a year-group")
        questions = []
        for question in save.questions:
            if question.question_category == category:
                questions.append(question)
        if len(questions) < 10:
            print("There are not enough questions for a quiz in this category")
            break
        else:
            questions = random.sample(questions, 10)
        student = Student(school, year)
        random.shuffle(questions)
        answers = []
        for question in questions:
            print()
            index = random.randint(0, 3)
            options = list(question.incorrect_answers)
            options.insert(index, question.correct_answer)
            choice = print_menu(question.question_text, options)
            clear_screen()
            if choice == index:
                answers.append((question, Answer(True)))
                print("\nCorrect!")
            else:
                answers.append((question, Answer(False)))
                print("\nIncorrect...")
                print("The correct answer is:", question.correct_answer)
        result = Result(answers, student)
        if save.results:
            save.results = save.results + [result]
        else:
            save.results = [result]
        print()
        print("Congratulations! You scored: " + str(
            len([answer for answer in answers if answer[1].correct is True])) +
              "/" + str(len(answers)))
        print()
        save_data(save)
        time.sleep(5)
        clear_screen()
示例#7
0
#routes
tweetsuite.add_url_rule('/',
                        view_func=MainLine.as_view('index'),
                        methods=["Get", "POST"])
tweetsuite.add_url_rule('/login',
                        view_func=Login.as_view('login'),
                        methods=["Get", "POST"])
tweetsuite.add_url_rule('/search/',
                        view_func=Search.as_view('search'),
                        methods=['GET', 'POST'])
tweetsuite.add_url_rule('/register/',
                        view_func=Register.as_view('register'),
                        methods=['GET', 'POST'])
tweetsuite.add_url_rule('/result/',
                        view_func=Result.as_view('result'),
                        methods=['GET'])
tweetsuite.add_url_rule('/logout',
                        view_func=Logout.as_view('logout'),
                        methods=['GET'])
tweetsuite.add_url_rule('/demo',
                        view_func=Demo.as_view('demo'),
                        methods=['GET'])


#handler to page not found - or incorrect URL
@tweetsuite.errorhandler(404)
def page_not_found(error):
    return flask.redirect(flask.url_for('login'))

示例#8
0
@author: Quantum Solutions
"""



from flask import Flask, request, redirect, url_for
from flask import render_template, session
from flask.views import MethodView
from classes.search import Search
from classes.result import Result
from classes.utils import InitializeTweepyAPI

tweetsuite = application = Flask(__name__)
tweetsuite.secret_key = "social"                 # needed for sessions

class Mainline(MethodView):
    def get(self):
        session.pop('query', None)              # Reset query value in session
        session.pop('username', None)           # Reset username value in session
        initialize = InitializeTweepyAPI()
        return render_template('index.html')


    
tweetsuite.add_url_rule('/', view_func=Mainline.as_view('index'))
tweetsuite.add_url_rule('/search', view_func=Search.as_view('search'))
tweetsuite.add_url_rule('/result', view_func=Result.as_view('result'))
 
   
if __name__ == '__main__':
    tweetsuite.run(debug=False)
#routes
tweetsuite.add_url_rule('/',
                 view_func=MainLine.as_view('index'),
                 methods=["Get","POST"])
tweetsuite.add_url_rule('/login',
                 view_func=Login.as_view('login'),
                 methods=["Get","POST"])
tweetsuite.add_url_rule('/search/',
                 view_func=Search.as_view('search'), 
                 methods=['GET','POST'])
tweetsuite.add_url_rule('/register/',
                 view_func=Register.as_view('register'), 
                 methods=['GET','POST'])
tweetsuite.add_url_rule('/result/',
                 view_func=Result.as_view('result'), 
                 methods=['GET'])
tweetsuite.add_url_rule('/logout',
                 view_func=Logout.as_view('logout'),
                 methods=['GET'])
tweetsuite.add_url_rule('/demo',
                 view_func=Demo.as_view('demo'),
                 methods=['GET'])

#handler to page not found - or incorrect URL
@tweetsuite.errorhandler(404)
def page_not_found(error):
    return flask.redirect(flask.url_for('login'))
    
if _platform == "win32":
    application.debug = True