Ejemplo n.º 1
0
    def __init__(self, comp_type, init):

        self.indent_modifier = [0, 0]

        name = init.get('name')
        block_type = 'class_methods'
        lines = init.get('_lines')

        statements = list()

        if init.get('import'):
            statements.append(init.get('import'))

        statements.append(
            Statement('definition',
                      block_type,
                      init={
                          'keyword': 'def',
                          'name': name,
                          'arguments': lines[0],
                      }))

        for line in lines[1:]:
            statements.append(
                Statement('line', block_type,
                          line='${indent}' + line.rstrip()))

        super(ClassMethodComponent,
              self).__init__(comp_type,
                             statements=statements,
                             outline_str='cls.' + name + ',')
Ejemplo n.º 2
0
    def create_outline(self):
        """Create the outline of the WorkChain."""
        block = Block('define_outline', 2)
        indent = 1

        block.add_statement(
            Statement('comment',
                      'define_outline',
                      init={'comment': 'spec.outline('}))

        for component in self._components:
            if component.type not in OUTLINE_COMPONENTS:
                # Component, that does not contribute to the outline.
                continue

            indent += component.indent_modifier[0]

            # Add the components outline string to the outline.
            block.add_statement(
                Statement('comment',
                          'define_outline',
                          indent=indent,
                          init={'comment': component.outline_str}))

            indent += component.indent_modifier[1]

        block.add_statement(
            Statement('comment', 'define_outline', init={'comment': ')'}))

        self.blocks['define_outline'] = block
Ejemplo n.º 3
0
 def __init__(self, name, base, decors):
     self.name = name
     self.base = base
     self.decors = decors
     self.isScope = True
     Statement.__init__(self)
     HasChildren.__init__(self)
     Scope.__init__(self)
Ejemplo n.º 4
0
 def __init__(self, name, base, decors):
     self.name = name
     self.base = base
     self.decors = decors
     self.isScope = True
     Statement.__init__(self)
     HasChildren.__init__(self)
     Scope.__init__(self)
Ejemplo n.º 5
0
    def test_execute(statements):
        executor = ThreadExecutor()

        for s, expected_state, expected_results in statements:
            statement = Statement(s, worksheet)
            statement._expected_state = expected_state
            statement._expected_results = expected_results
            statement._got_executing = False
            executor.add_statement(statement)

        loop = gobject.MainLoop()

        def on_statement_executing(executor, statement):
            if hasattr(statement, '_got_state'):
                statement._out_of_order = True
            statement._got_executing = True

        def on_statement_complete(executor, statement):
            statement._got_state = statement.state
            statement._got_results = statement.results
            statement._out_of_order = False

        def on_complete(executor):
            loop.quit()

        def interrupt():
            executor.interrupt()

        global timed_out
        timed_out = False
        def timeout():
            global timed_out
            timed_out = True
            loop.quit()

        executor.connect('statement-executing', on_statement_executing)
        executor.connect('statement-complete', on_statement_complete)
        executor.connect('complete', on_complete)

        if executor.compile():
            executor.execute()
            interrupt_source = gobject.timeout_add(500, interrupt)
            timeout_source = gobject.timeout_add(1000, timeout)
            loop.run()
            if timed_out:
                raise AssertionError("Interrupting ThreadExecutor failed")
            gobject.source_remove(interrupt_source)
            gobject.source_remove(timeout_source)

        for s in executor.statements:
            assert_equals(s._got_state, s._expected_state)
            assert_equals(s._got_results, s._expected_results)
            if s._out_of_order:
                raise AssertionError("ThreadExecutor sent 'statement-executing' after 'statement-complete'")
            if s._expected_state == Statement.INTERRUPTED and not s._got_executing:
                raise AssertionError("ThreadExecutor did not send 'statement-executing' within timeout")
Ejemplo n.º 6
0
 def fromText(text):
     state = State()
     for line in text.split('\n'):
         if not line:
             continue
         if line.startswith('*'):
             state.predictions.addStatement(Statement.fromText(line[1:]))
         else:
             state.statements.addStatement(Statement.fromText(line))
     return state
Ejemplo n.º 7
0
	def __init__(self,  stub,logger):
		"""PL/SQL exception"""
		Statement.__init__(self, stub, logger)
		self._type='EXCEPTION_SECTION'
		self._logger=logger
		self._stub=stub
		self._src=None
		if self._stub.has_key('exception'):
			self._src=self._stub['exception']
		self._el={} #exception list
Ejemplo n.º 8
0
def p_return(p):
    '''
    return_statement : RETURN
                     | RETURN expression
    '''
    if len(p) == 2:
        p[0] = Statement(StatementType.RETURN, p.lineno(1),
                         {'return_value': None})
    else:
        p[0] = Statement(StatementType.RETURN, p.lineno(1),
                         {'return_value': p[2]})
Ejemplo n.º 9
0
    def __init__(self, name, args, decors):
        Statement.__init__(self)
        HasChildren.__init__(self)
        Scope.__init__(self)
        self.name = name
        self.args = args
        self.decors = decors
        self.locals = []
        self.isScope = True
        a = self.locals.append

        for arg in self.args:
            a(arg.id)
Ejemplo n.º 10
0
    def __init__(self, name, args, decors):
        Statement.__init__(self)
        HasChildren.__init__(self)
        Scope.__init__(self)
        self.name = name
        self.args = args
        self.decors = decors
        self.locals = []
        self.isScope = True
        a = self.locals.append

        for arg in self.args:
            a(arg.id)
Ejemplo n.º 11
0
def p_class_instanciation(p):
    '''
    expression : NEW IDENT LP RP
               | NEW IDENT LP args RP
    '''
    if len(p) == 5:
        p[0] = Statement(StatementType.NEW_CLASS, p.lineno(1), {
            'class_name': p[2],
            'class_args': {}
        })
    else:
        p[0] = Statement(StatementType.NEW_CLASS, p.lineno(1), {
            'class_name': p[2],
            'class_args': p[4]
        })
Ejemplo n.º 12
0
def p_call_func(p):
    '''
    call_func : IDENT LP args RP
              | IDENT LP RP
    '''
    if len(p) == 5:
        p[0] = Statement(StatementType.FUNCTION_CALL, p.lineno(1), {
            'function_name': p[1],
            'args': p[3]
        })
    else:
        p[0] = Statement(StatementType.FUNCTION_CALL, p.lineno(1), {
            'function_name': p[1],
            'args': []
        })
def main():
    while (True):
        line = input("db > ")
        if (line[0] == "."):
            command_value = do_meta_command(line)
            if (command_value == MetaCommands.META_COMMAND_SUCCESS):
                continue
            elif (command_value ==
                  MetaCommands.META_COMMAND_UNRECOGNIZED_COMMAND):
                print("Unrecognized command {0} .\n".format(line))
                continue
            elif (command_value == MetaCommands.META_COMMAND_EXIT):
                print("~Goodbye")
                sys.exit()

        statement = Statement()
        statement_value = prepare_statement(line, statement)

        if (statement_value == PreparedStatements.PREPARE_SUCCESS):
            break
        elif (statement_value ==
              PreparedStatements.PREPARE_UNRECOGNIZED_STATEMENT):
            print("Unrecognized keyword at start of {0} .\n".format(line))
            continue

    execute_statement(statement)
    print("Executed")
Ejemplo n.º 14
0
    def Replace(self):
        # Get the rule
        value = self.value_edit.currentText().strip()
        # Add it to the logs
        self.valueLog.AddRule(self.question, value)
        # Propagate rule
        self.ruleHeap.Propagate(self.question, value)
        # If solutions are found, add them to logs and propagate them
        solutions = self.ruleHeap.GetSolutions()
        for sol in solutions:
            sol_st = Statement(sol)
            if (sol_st.root.sign):
                val = "T"
            else:
                val = "F"
            if (sol_st.root.symbol.mask not in ["T", "F"]):
                self.valueLog.AddRule(sol_st.root.symbol.mask, val)
                self.ruleHeap.Propagate(sol_st.root.symbol.mask, val)
                self.reasoned.append(sol_st.root.symbol.mask)

        self.UpdateValueLog()
        self.UpdateRuleHeap()
        if (self.ruleHeap.IsSolved()):
            # Enter finished state
            if (self.valueLog.RuleExists(self.objective)):
                self.Explain()
            else:
                self.Fail()
        else:
            try:
                self.SetNextQuestion()
            except:
                self.Fail()
Ejemplo n.º 15
0
    def get_clean_statement(self, worksheet):
        if self.statement_dirty:
            self.statement = Statement(self.tokenized.get_text(), worksheet)
            self.statement.chunk = self
            self.statement_dirty = False

        return self.statement
Ejemplo n.º 16
0
 def create_statement(self):
     """
     @rtype: Statement
     """
     self._putMessageId(protocol.CREATE)
     self._exchangeMessages()
     return Statement(self.getInt())
Ejemplo n.º 17
0
def p_loop_statement(p):
    '''
    loop_statement : LOOP LP condition_statement RP block
                   | LOOP LP IDENT COLON expression RP block
    '''
    if len(p) == 6:
        p[0] = Statement(StatementType.LOOP, p.lineno(1), {
            'condition': p[3],
            'statementlist': p[5]
        })
    else:
        p[0] = Statement(StatementType.LOOP, p.lineno(1), {
            'ident': p[3],
            'loop_count': p[5],
            'statementlist': p[7]
        })
Ejemplo n.º 18
0
def p_if_statement(p):
    '''
    if_statement : IF LP condition_statement RP block
                 | IF LP condition_statement RP block ELSE statement
    '''
    if len(p) == 6:
        p[0] = Statement(StatementType.IF, p.lineno(1), {
            'condition': p[3],
            'statementlist': p[5]
        })
    else:
        p[0] = Statement(StatementType.IF, p.lineno(1), {
            'condition': p[3],
            'statementlist': p[5],
            'else_statementlist': [p[7]]
        })
Ejemplo n.º 19
0
    def __init__(self, ast_node, prog):
        self.ast_node = ast_node
        # Reference to the program
        self.prog = prog

        # Get the function properties
        name, params, localvars, statements = ast_node.children

        # The name of the function
        self.name = name.text

        # Dictionaries for variables and parameters
        self.params = {
            p.text: VecParam(p.text, i)
            for i, p in enumerate(params.children)
        }

        self.localvars = {
            v.text: LocalVar(v.text, i)
            for i, v in enumerate(localvars.children)
        }

        # Run statements
        self.statements = [Statement(s, self) for s in statements.children]

        self.before = FUNC_START_ASM
        self.after = FUNC_END_ASM
Ejemplo n.º 20
0
def p_decrement(p):
    '''
    assign_statement : IDENT DECREMENT
    '''
    p[0] = Statement(StatementType.ASSIGN, p.lineno(1), {
        'variable_name': p[1],
        'type': 'decrement'
    })
Ejemplo n.º 21
0
def p_instance_method(p):
    '''
    call_func : IDENT DOT IDENT LP RP
              | IDENT DOT IDENT LP args RP
    '''
    if len(p) == 6:
        p[0] = Statement(StatementType.CALL_METHOD, p.lineno(1), {
            'variable_name': p[1],
            'method_name': p[3],
            'method_args': {}
        })
    else:
        p[0] = Statement(StatementType.CALL_METHOD, p.lineno(1), {
            'variable_name': p[1],
            'method_name': p[3],
            'method_args': p[5]
        })
Ejemplo n.º 22
0
def p_define_class(p):
    '''
    define_class : CLASS IDENT LC newline define_class_properties newline define_methods newline RC
                 | CLASS IDENT LC newline define_methods newline RC
    '''
    if len(p) == 8:
        p[0] = Statement(StatementType.CLASS_DEFINE, p.lineno(1), {
            'class_name': p[2],
            'properties': [],
            'methods': p[5]
        })
    else:
        p[0] = Statement(StatementType.CLASS_DEFINE, p.lineno(1), {
            'class_name': p[2],
            'properties': p[5],
            'methods': p[7]
        })
Ejemplo n.º 23
0
def p_define_func(p):
    '''
    define_function : FUNCTION IDENT LP RP block
                    | FUNCTION IDENT LP define_function_args RP block
    '''
    if len(p) == 6:
        p[0] = Statement(StatementType.FUNCTION_DEFINE, p.lineno(1), {
            'function_name': p[2],
            'function_args': [],
            'statementlist': p[5]
        })
    else:
        p[0] = Statement(StatementType.FUNCTION_DEFINE, p.lineno(1), {
            'function_name': p[2],
            'function_args': p[4],
            'statementlist': p[6]
        })
Ejemplo n.º 24
0
 def IsSolved(self):
     regex = "^[\w]+$"
     undef = []
     for rule in self.rules:
         rule_st = Statement(rule)
         if(rule_st.root.symbol.mask in ["T", "F"]):
             undef.append(rule)
     return len(undef) == len(self.rules)
Ejemplo n.º 25
0
def p_if_statement_else(p):
    '''
    if_statement : IF LP condition_statement RP block ELSE block
    '''
    p[0] = Statement(StatementType.IF, p.lineno(1), {
        'condition': p[3],
        'statementlist': p[5],
        'else_statementlist': p[7]
    })
Ejemplo n.º 26
0
def p_assign_statement(p):
    '''
    assign_statement : IDENT ASSIGN expression
    '''
    # variables[p[1]] = p[3]
    p[0] = Statement(StatementType.ASSIGN, p.lineno(1), {
        'variable_name': p[1],
        'expression': p[3]
    })
Ejemplo n.º 27
0
    def test_execute(statements):
        executor = ThreadExecutor()

        for s, expected_state, expected_results in statements:
            statement = Statement(s, worksheet)
            statement._expected_state = expected_state
            statement._expected_results = expected_results
            executor.add_statement(statement)

        loop = gobject.MainLoop()

        def on_statement_complete(executor, statement):
            statement._got_state = statement.state
            statement._got_results = statement.results

        def on_complete(executor):
            loop.quit()

        def interrupt():
            executor.interrupt()

        global timed_out
        timed_out = False
        def timeout():
            global timed_out
            timed_out = True
            loop.quit()

        executor.connect('statement-complete', on_statement_complete)
        executor.connect('complete', on_complete)

        if executor.compile():
            executor.execute()
            interrupt_source = gobject.timeout_add(500, interrupt)
            timeout_source = gobject.timeout_add(1000, timeout)
            loop.run()
            if timed_out:
                raise AssertionError("Interrupting ThreadExecutor failed")
            gobject.source_remove(interrupt_source)
            gobject.source_remove(timeout_source)

        for s in executor.statements:
            assert_equals(s._got_state, s._expected_state)
            assert_equals(s._got_results, s._expected_results)
Ejemplo n.º 28
0
	def get_src(self):
		self._map_src = self._map_src.strip('EXCEPTION').strip('END;').strip()
		#sys.exit(1)
		out_src="""
		EXCEPTION
		WHEN OTHERS THEN
		%s
	END;""" % Statement.get_src(self)
		
		return out_src
Ejemplo n.º 29
0
 def load(cls, root, path):
     ts, rev, hash = path.split("_")
     t = Transaction(rev)
     t.ts = ts
     f = open(root + '/transaction/%s' % path)
     d = f.read()
     for i in d.split('\n'):
         i = i.strip()
         if i:
             t.statements.append( Statement.from_json(i) )
     return t
Ejemplo n.º 30
0
 def update_expression(self, cell_pos, attrib, expression, save=False):
     #cell = self.cell_dict[cell_pos]
     
     new_json = self.files[attrib].apply_statements(self.config, self.cell_dict, [Statement(attrib, [CellRange((cell_pos[0], cell_pos[0] + 1), (cell_pos[1], cell_pos[1] + 1))], Expression(expression))])
     #new_json = cell.update_expression(attrib, Expression(expression), self.config, self.cell_dict)
     new_json = {str(key)[1:-1]: value for key, value in new_json.items()}
   
     if save: self.files[attrib].write_to_file()
   
     self.data["cells"].update(new_json)
     return json.dumps(self.data)
Ejemplo n.º 31
0
    def Propagate(self, item, value):
        """Replaces a variable with a specific value, either T or F"""
        if(item == ""):
            return
        # Only valid values are our True of False (T,F)
        value = value.strip()
        if(value not in ["T", "F"]):
            raise ValueError

        print("Rules before propagation")
        print(self)

        i = 0
        while(i < len(self.rules)):
            rule_st = Statement(self.rules[i])
            rule_st.ReplaceWithValue(item,value)
            self.rules[i] = str(rule_st)
            i += 1;

        print("Rules after propagation")
        print(self)
def build_statements(fiscal_periods):

    statements = []

    for fiscal_period in fiscal_periods:

		for financial_statement in fiscal_period.Statement:

			header = financial_statement.FPHeader

			periodTypeCode = None
			periodTypeValue = None
			periodLength = None

			auditorNameCode = None
			auditorNameValue = None

			auditorOpinionCode = None
			auditorOpinionValue = None 

			sourceDate = None

			if hasattr(header, 'periodType'):
				periodTypeCode = header.periodType.Code
				periodTypeValue = header.periodType.Value
				periodLength = header.PeriodLength

			if hasattr(header, 'AuditorName'):
				auditorNameCode = header.AuditorName.Code
				auditorNameValue = header.AuditorName.Value

			if hasattr(header, 'AuditorOpinion'):
				auditorOpinionCode = header.AuditorOpinion.Code
				auditorOpinionValue = header.AuditorOpinion.Value				

			if hasattr(header.Source, 'Date'):
				sourceDate = header.Source.Date

			statement = Statement(fiscal_period.EndDate, fiscal_period.Type, 
								  fiscal_period.FiscalYear, 
								  financial_statement.Type,
								  periodTypeCode, periodTypeValue, periodLength, 
								  auditorNameCode, 
								  auditorNameValue,
								  header.Source.Value, sourceDate,
								  header.StatementDate,
								  header.UpdateType.Code, header.UpdateType.Value,
								  auditorOpinionCode, auditorOpinionValue, 
								  financial_statement.lineItem)
			statements.append(statement)

    return statements
Ejemplo n.º 33
0
    def __init__(self, director, filename):
        super().__init__(director)
        self.filename = filename
        #
        self.stms_list = Statement.create_stms(
            SceneHome.get_text(self.filename))

        director.screen.fill(SceneHome.BLACK1)

        self.visiable_start = 0
        self.visiable_end = 0
        self.magnifier = False
        self.display_text()
Ejemplo n.º 34
0
 def GetSolutions(self):
     """Check for a ruleset that became a solution through Modus Tollens"""
     #
     # A rule is a solution if there is only one variable left in the rule
     #
     regex = "^[\w]+$"
     solutions = []
     for rule in self.rules:
         rule_st = Statement(rule)
         if(rule_st.root.symbol.code == "IDENTIFIER"): 
             if(rule_st.root.symbol.mask not in ["T", "F"]):
                 solutions.append(rule)
     return solutions
Ejemplo n.º 35
0
def p_term(p):
    '''
    term : primary_expression
         | term MUL primary_expression
         | term DIV primary_expression
    '''
    if len(p) == 4:
        p[0] = Statement(StatementType.EXPRESSION, p.linno(2), {
            'left': p[1],
            'right': p[3],
            'op': p[2]
        })
    else:
        p[0] = p[1]
Ejemplo n.º 36
0
    def __init__(self, block_type, indent_level, init=None):

        self._type = block_type
        self._indent_level = indent_level

        self._statements = []

        # Add all the statements already contained in init.
        if init is None:
            init = []

        for statement_type, value in init:
            statement = Statement(statement_type, block_type, init=value)
            self.add_statement(statement)
Ejemplo n.º 37
0
def p_expression(p):
    '''
    expression : term
               | expression ADD term
               | expression SUB term
    '''
    if len(p) == 4:
        p[0] = Statement(StatementType.EXPRESSION, p.lineno(2), {
            'left': p[1],
            'right': p[3],
            'op': p[2]
        })
    else:
        p[0] = p[1]
Ejemplo n.º 38
0
    def replay_compacted(self):
        compacted_transactions = os.listdir(self.data_path + '/compact/')
        compacted_transactions.sort()

        cur_trans = None
        for i in compacted_transactions:
            f = open(self.data_path + '/compact/' + i)
            for j in f.readlines():
                j = j.strip()
                if j.startswith('begin'):
                    # start transaction
                    if cur_trans:
                        self.commit_transaction(cur_trans, is_replay=True)
                    ts, rev, hash = j.split(' ')[1].split("_")
                    cur_trans = Transaction(rev)
                    cur_trans.ts = ts
                else:
                    cur_trans.statements.append( Statement.from_json(j) )
        if cur_trans:
            self.commit_transaction(cur_trans)
Ejemplo n.º 39
0
 def statement(self) :
     cId = str(self.sender().objectName()).split('_')[1]
     print "1212",cId
     obj = Statement(self.query,cId)
     obj.exec_()