Esempio n. 1
0
    def renderResponseForQuery(self):  # constructs a response based on the user's query intent
        self.__response = "Sorry, I didn't understand that" # (1) initialize default response message
        self.__scope = Scope(self.__db_handler.checkCurrentScope(self.__activity.getConversationID()))  # (2) init scope

        # (3) Check for a CLARIFICATION object:
        clarification = self.__db_handler.getCacheForClarification(self.__activity.getConversationID())
        if clarification is not None:  # clarification exists!
            entity_type = clarification[2]  # check what entity type we SHOULD be getting
            if len(self.findMatchingEntity(of_type=entity_type)) > 0:  # check that we received at least 1 such entity
                self.__topIntent = Intent(clarification[0])  # recreate old top scoring intent & overwrite
                updated_e = [Entity(e) for e in clarification[1]]  # create old entities
                for e in self.__entities:  # add the NEW entities to the END of the existing list (*to preserve order!*)
                    updated_e.append(e)
                self.__entities = updated_e  # overwrite the entities object
                self.__is_clarification = True  # set indicator (needed for findObject logic)
            # *If no entities of specified type are found, simply treat query normally & ignore clarification!*

        e = self.findMatchingEntity("query")  # *(4) check for a QUERY entity AFTER the clarification!*
        query_word = e[0] if len(e) > 0 else ""  # store FIRST query that is found (b/c entities are sent IN ORDER)

        # Non-Historical Intents:
        if self.__topIntent.intent == "None":  # receptacle for unwanted questions ***
            pass
        elif self.__topIntent.intent == "Greeting":
            name = self.__activity.getUserName()  # check if user's name is defined
            self.__response = "Hello, {}".format(name[1]) if name else "Hello"
        elif self.__topIntent.intent == "GetName":  # asking for name
            self.__response = "I am the Diagnostic Bot"

        # Recognizer Intents:


        # (LAST) Persist the scope object & then render the bot's response:
        self.__db_handler.persistCurrentScope(self.__activity.getConversationID(), self.__scope.getScopeForDB())
        self.__activity.sendTextMessage(text="{}".format(self.__response))  # send msg
Esempio n. 2
0
 def eval(self, s: Scope) -> Value:
     env: Scope = Scope(s)
     ext: Scope = Scope(s)
     for i, _ in enumerate(self.patterns):
         binder.define(ext, self.patterns[i].identifier,
                       self.exprs[i].eval(env))
     return self.body.eval(ext)
Esempio n. 3
0
    def __init__(self, is_intaractive_run, an_errhandler):
        """ EvalVisitorを初期化して応答する.
        """
        self.is_test = False
        self.is_intaractive_run = is_intaractive_run
        self.errhandler = an_errhandler
        self.scopes = ScopeList()
        self.is_break = False
        self.is_return = False
        self.return_value = UnitXObject(value=None, varname=None, unit=None, token=None, is_none=True)

        this_dir, _ = os.path.split(__file__)
        data_path = os.path.join(this_dir, Constants.SYSTEM_UNIT_DATA)
        self.unit_manager = UnitManager(data_path) # Sets a database(data/unit_table.dat) for calculating units.
        self.stdlib = Stdlib()
        self.NULL_UNITX_OBJ = UnitXObject(value=None, varname=None, is_none=True, unit=Unit(), token=None)
        
        #
        # Sets a mediator to each classes for a management,
        # because this class is a mediator class.
        # Also, UnitXObject, Unit, Scope classes have to create many new instances.
        # So, We set a mediator by using classmethod.
        #
        self.scopes.set_mediator(self)
        self.unit_manager.set_mediator(self)
        self.stdlib.set_mediator(self)
        UnitXObject.set_mediator(self)
        Unit.set_mediator(self)
        Scope.set_mediator(self)
        DefinedFunction.set_mediator(self)

        UnitXObject.manager = self.get_unit_manager()
        UnitXObject.scopes = self.get_scopes()
Esempio n. 4
0
def resolveFunction(node: Node, parentScope: Scope):
    for child in node.getChildNodes():
        if child.nodeType == NodeType.FUNCTION:
            child.parentScope = parentScope
            name = child.getChild('name')

            if parentScope.classType:
                if name != '__init__':
                    name = parentScope.classType.name + '__' + name
                else:
                    name = parentScope.classType.name + name

            type_ = getFunctionReturnType(child)
            symbol = Symbol(name, type_)
            child.symbol = symbol
            child.resolvedType = type_
            global_ = parentScope
            while global_.parent != None:
                global_ = global_.parent

            global_.define(symbol)

            scope = Scope(parentScope)
            scope.isFunction = True
            scope.classType = parentScope.classType
            child.scope = scope
Esempio n. 5
0
File: test.py Progetto: kusha/dialog
    def test_update_parsed(self):

        scope = Scope()

        phrase = 'changeable value is `changeable`'
        phrase = Phrase(phrase, scope)
        phrase._update_parsed()
        self.assertEqual(phrase.latest, "changeable value is True")
        # no exception

        scope.change()
        phrase._update_parsed()
        self.assertEqual(phrase.latest, "changeable value is False")
        # no exception

        scope.change()
        scope.raise_error()
        self.assertRaises(KeyError, phrase._update_parsed)
    
        # also test not changed, with exception 
        scope = Scope()
        phrase = 'changeable value is `changeable`'
        phrase = Phrase(phrase, scope)
        phrase._update_parsed()
        self.assertEqual(phrase.latest, "changeable value is True")
        scope.raise_error()
        self.assertRaises(KeyError, phrase._update_parsed)
Esempio n. 6
0
class TestScope(unittest.TestCase):
    def setUp(self):
        sample = SC.StandardSample()
        obj = SC.WaterObjectiveLens60x()
        px = SC.PixelSizeCalibrationUm()
        px = 0.11
        self.scope = Scope(px, obj, sample)

    def test_scope_integrity(self):
        self.assertEqual(self.scope.parameters['mounting_medium_RI'], 1.33)
        self.assertEqual(
            self.scope.parameters['immersion_medium_refractive_index'], 1.33)
        self.assertEqual(self.scope.parameters['pixel_size_um'], 0.11)
        self.assertEqual(self.scope.parameters['numerical_aperture'], 1.2)

    def test_scope_pupilFunc(self):
        self.scope.init_pupil()
        self.assertEqual(self.scope.pupilMask.NA, 1.2)

        self.pupilFunc = self.scope.pupilFunc
        psf = self.pupilFunc.gen_PSF(0, 0, 0, 100, 0, 32)
        self.assertEqual(psf.shape, (32, 32), 'Shape is wrong')
        self.assertAlmostEqual(psf.sum(),
                               100,
                               delta=1.,
                               msg='Intensity is wrong')
Esempio n. 7
0
 def test_match_sentence(self):
     pattern = [FirstToken('Test'), WordToken('value')]
     to_match = Sentence(pattern + [PeriodToken()])
     code = None
     test_def = Definition(pattern, code)
     scope = Scope(None)
     scope.add_definition(test_def)
     self.assertIs(test_def, scope.match_sentence(to_match))
Esempio n. 8
0
 def __call__(self, scope, *args):
     # if scope.has_key("recur") and scope["recur"] == self:
     # This is recursion, don't create a new scope
     # local = scope
     # else:
     # Calling scope -> creating scope -> local scope
     # Clone creation scope so its parent can be set to calling scope
     creation = Scope()
     creation.bindings = self.scope.bindings
     creation.parent = scope
     # Create a new scope
     local = Scope(creation)
     # Bind `recur` to self (to alow for recursion from anonymous functions)
     local["recur"] = self
     # Bind each argument to a binding
     bi = ai = 0
     bindings = self.bindings.data[:-1]
     while bi != len(bindings) and ai != len(bindings):
         # Optional argument
         if bindings[bi] == Symbol("?"):
             if ai >= len(args):
                 if bindings[bi + 1].__class__ == List:
                     # A default value is supplied
                     local[bindings[bi + 1].car().data] = bindings[bi + 1].cdr().car().evaluate(local)
                 else:
                     # Nothing supplied for this optional and no default value
                     local[bindings[bi + 1].data] = List([])
                 ai -= 1
                 bi += 1
             else:
                 if bindings[bi + 1].__class__ == List:
                     # A default value is supplied, replace with just the symbol
                     local[bindings[bi + 1].car().data] = args[ai].evaluate(scope)
                 else:
                     local[bindings[bi + 1].data] = args[ai].evaluate(scope)
                 bi += 1
                 # continue
         # Rest argument
         elif bindings[bi] == Symbol("&"):
             if ai == len(args):
                 # raise TypeError("expected at least %d arguments, got %d" % (bi + 1, ai))
                 local[bindings[bi + 1].data] = List([])
             else:
                 local[bindings[bi + 1].data] = List([x.evaluate(scope) for x in args[ai:]] + [[]])
             break
         # Normal argument
         else:
             # Too many or too few arguments
             if bi >= len(bindings) or ai >= len(args):
                 raise TypeError("expected %d arguments, got %d" % (len(bindings), len(args)))
             local[bindings[bi].data] = args[ai].evaluate(scope)
         ai += 1
         bi += 1
     # Evaluate each expression in the body (in local function scope)
     for expression in self.body[:-1]:
         expression.evaluate(local)
     # Return the evaluated last expression
     return self.body[-1].evaluate(local)
Esempio n. 9
0
 def eval(self, s: Scope) -> Value:
     env: Scope = Scope(s)
     ext: List[Scope]
     for i in range(len(self.patterns)):
         ext.append(Scope(env))
         binder.define(ext[i], self.patterns[i].identifier, self.exprs[i].eval(env))
     for x in ext:
         env.put_all(x)
     return self.body.eval(env)
Esempio n. 10
0
 def eval_function(scope, *args):
     if len(args) != len(params):
         raise LSRunningError('Incorrect number of arguments. expected: ' +
                              str(len(params)) + ' actual: ' +
                              str(len(args)))
     local_scope = Scope(scope)
     for (param, arg) in zip(params, args):
         new_def = Definition(param, arg)
         local_scope.add_definition(new_def)
     # Head should be defined in the parent scope.
     return evaluate(body, local_scope)
Esempio n. 11
0
    def test_compare(self):

        input_string = "my name is John"
        input_parsed = link_parser.parse(input_string)

        phrase = 'my name is `name~Mark`'
        phrase = Phrase(phrase, Scope())
        self.assertEqual(phrase.compare(input_parsed), 0.8)  #4/5 simlar links

        phrase = 'hello'
        phrase = Phrase(phrase, Scope())
        self.assertEqual(phrase.compare(input_parsed), 0)
Esempio n. 12
0
def resolveClass(node: Node, parentScope: Scope):
    for child in node.getChildNodes():
        if child.nodeType == NodeType.CLASS:
            name = child.getChild('name')
            type_ = Type(name, True)
            symbol = Symbol(name, type_, SymbolKind.CLASS)
            child.symbol = symbol
            child.resolvedType = type_
            parentScope.define(symbol)

            scope = Scope(parentScope)
            scope.classType = type_
            child.scope = scope
Esempio n. 13
0
    def test_erase_routine_requests(self):

        phrase = self.fake_class('Hello world `my_var:32` `name~John`',
                                 Scope())
        Phrase._erase_routine_requests(phrase)
        self.assertEqual(phrase.phrase, 'Hello world `my_var:32` `name~John`')

        phrase = self.fake_class(
            'Hello world `routine1<"stop"` `my_var:32` `routine1<"stop"` `name~John`',
            Scope())
        Phrase._erase_routine_requests(phrase)
        self.assertEqual(phrase.phrase,
                         'Hello world  `my_var:32`  `name~John`')
Esempio n. 14
0
def main():
    server_port = 15151
    client_list = set()

    argc = len(sys.argv)
    if argc < 3 or argc > 4:
        usage()
        sys.exit(-1)

    scope_port = sys.argv[1]
    controls_port = sys.argv[2]

    if argc == 4:
        server_port = int(sys.argv[3])

    scope = Scope(scope_port)
    scope.set_preamp(Scope.CHANNEL_A, high=True)
    scope.set_preamp(Scope.CHANNEL_B, high=True)
    #scope.set_sample_rate_divisor(0x7)
    #scope.set_trigger_level(1.0)  # default trigger at 1v

    data_sender = ScopeDataSender(client_list)

    control_panel = make_control_panel(controls_port, scope, data_sender)

    scope_read_thread = ScopeReadThread(scope, data_sender)
    control_panel_thread = ControlPanelThread(control_panel)

    def stop_server_and_exit(signum, frame):
        print '\rStopping server'
        scope_read_thread.stop()
        control_panel_thread.stop()
        print 'Joining control panel thread...'
        control_panel_thread.join()
        print 'Joining scope read thread... ',
        print 'If this takes too long, kill with ^\\'
        scope_read_thread.join()
        reactor.stop()

    def status_message(msg):
        print msg

    signal.signal(signal.SIGINT, stop_server_and_exit)
    scope_read_thread.start()
    control_panel_thread.start()

    scope_factory = ScopeFactory(client_list, scope, control_panel)
    reactor.listenTCP(server_port, scope_factory)
    reactor.callWhenRunning(
            status_message, 'Server started on port %d' % server_port)
    reactor.run()
Esempio n. 15
0
 def test_new_define_scope(self):
     outer_scope = Scope()
     outer_scope.add_definition(
         Definition(string_to_signature('Define Head. to be a built in.'),
                    None))
     inner_scope = outer_scope.new_define_scope(
         string_to_signature(
             'Check that The Sentences. given. are Defined. .'))
     # raises on missing sentence.
     inner_scope.match_sentence(
         string_to_signature('Check that Things. are Something. .'))
     inner_scope.match_sentence(string_to_signature('The Things. given.'))
     inner_scope.match_sentence(string_to_signature('Defined.'))
     with self.assertRaises(NoDefinitionError):
         inner_scope.match_sentence(string_to_signature('Sentences.'))
Esempio n. 16
0
    def test_erase_flexible_setters(self):

        phrase = self.fake_class('Hello world `my_var:32` `routine1<"stop"`',
                                 Scope())
        Phrase._erase_flexible_setters(phrase)
        self.assertEqual(phrase.phrase,
                         'Hello world `my_var:32` `routine1<"stop"`')

        phrase = self.fake_class(
            'Hello world `name~John` `my_var:32` `name~Mike` `routine1<"stop"`',
            Scope())
        Phrase._erase_flexible_setters(phrase)
        self.assertEqual(
            phrase.phrase,
            'Hello world John `my_var:32` Mike `routine1<"stop"`')
Esempio n. 17
0
    def test_parse(self):

        phrase = 'Hello `my_var` `my_var:32` `name~John` `routine1<"stop"`'
        phrase = Phrase(phrase, Scope())
        self.assertEqual(phrase.latest, 'Hello value  John ')
        self.assertEqual(phrase.phrase, 'Hello `my_var`  John ')
        self.assertEqual(phrase.substitute, [['my_var', 6, 14]])
        self.assertEqual(len(phrase.setters), 1)
        self.assertEqual(phrase.flexibles, [['name', 'John', 16, 20, None]])
        self.assertEqual(len(phrase.requests), 1)

        # exception raised by Scope module
        phrase = 'Hello `undefined_var`'
        phrase = Phrase(phrase, Scope())
        self.assertEqual(phrase.latest, None)
Esempio n. 18
0
 def make_test_scope(self):
     scope = Scope()
     scope.add_definition(Definition(string_to_signature('Unit.'), 0))
     scope.add_definition(Definition(
         string_to_signature('Something with Sub sentence. to parse.'), 1))
     scope.add_definition(Definition(
         string_to_signature('Define New thing. to be a new type.'), 2))
     return scope
Esempio n. 19
0
	def __init__(self):
		# all the appropriate scopes
		self.functions = Scope()
		self.synth_function = None
		self.variables = Scope()
		self.constraints = []
		self.system = None
Esempio n. 20
0
 def eval(self, env: Scope) -> Value:
     e: Scope = env
     for i, _ in enumerate(self.patterns):
         e = Scope(e)
         binder.define(e, self.patterns[i].identifier,
                       self.exprs[i].eval(e))
     return self.body.eval(e)
Esempio n. 21
0
 def __init__(self):
     scope = Scope()
     global_ = Node(None, 'Global')
     global_.children['files'] = []
     global_.scope = scope
     self.global_ = global_
     self.defineNativeTypes()
Esempio n. 22
0
    def test_erase_fixed_setters(self):

        # origin = 'Hello world `my_var:32` `name~John` `routine1<"stop"`'

        phrase = self.fake_class('Hello world `name~John` `routine1<"stop"`',
                                 Scope())
        Phrase._erase_fixed_setters(phrase)
        self.assertEqual(phrase.phrase,
                         'Hello world `name~John` `routine1<"stop"`')

        phrase = self.fake_class(
            'Hello world `my_var:32` `name~John` `my_var:32` `routine1<"stop"`',
            Scope())
        Phrase._erase_fixed_setters(phrase)
        self.assertEqual(phrase.phrase,
                         'Hello world  `name~John`  `routine1<"stop"`')
Esempio n. 23
0
 def __init__(self, path, default_chains=_default_chains):
     self.scope = YipScope()
     self.path = path
     self.tree = YipLoader.load(open(path))
     self.tables = {}
     self.chains = Scope({c: None for c in _default_chains})
     self.built = False
Esempio n. 24
0
    def test_evaluate(self):

        phrase = 'no substitutions'
        phrase = Phrase(phrase, Scope())
        self.assertEqual(phrase.evaluate(), "no substitutions")

        phrase = 'iteratable value is `iteratable`'
        phrase = Phrase(phrase, Scope())
        self.assertEqual(phrase.evaluate(),
                         "iteratable value is 2")  # 1 is passed by init call
        self.assertEqual(phrase.evaluate(), "iteratable value is 3")
        self.assertEqual(phrase.evaluate(), "iteratable value is 4")

        phrase = 'undefined value is `undefined_var`'
        phrase = Phrase(phrase, Scope())
        self.assertRaises(KeyError, phrase.evaluate)  # predicted behavior
Esempio n. 25
0
    def deepcopy(self, scope=None):
        _ = scope

        mother = self.get_mother().deepcopy()
        children = [x.deepcopy() for x in self.get_children()]

        copy = Rule(mother, children)

        Scope.deepcopy(self, copy)

        # I haven't thought through whether the next lines are necessary.
        # They don't hurt.
        copy.get_mother().set_scope(copy)
        for child in copy.get_children():
            child.set_scope(copy)

        return copy
Esempio n. 26
0
def make_test_scopes():
    scope0 = Scope(None)
    scope0.add_definition(
        Definition(string_to_signature('Fake sentence for testing.'), 0))
    scope0.add_definition(
        Definition(string_to_signature('Beginning Middle. end.'), 1))
    return [scope0, Scope(scope0)]
Esempio n. 27
0
 def transform_v_ident(self, scope):
     if not self.in_region:
         return scope
     if self.is_const(scope):
         value = scope.get_classical_value(scope.name)
         s = Scope(scope.line, scope.column, scope_payload=UIntPayload(value), super_scope=scope.super_scope)
         return s
     else:
         return scope
Esempio n. 28
0
    def test_accept(self):

        scope = Scope()
        phrase = '`var:13` my name is `name~Jack` `surname~Daniels` `strvar:"string"` `routine<1` `routine2<"ok"`'
        phrase = Phrase(phrase, scope)
        phrase.accept('my name is John Walker')
        self.assertEqual(scope.toset, {
            'var': 13,
            'name': 'example',
            'surname': 'example',
            'strvar': 'string'
        })
        self.assertEqual(scope.tosend, {'routine': 1, 'routine2': 'ok'})

        scope = Scope()
        phrase = Phrase("Hello world", scope)
        phrase.accept()
        self.assertEqual(scope.toset, {})
        self.assertEqual(scope.tosend, {})
Esempio n. 29
0
def repl_core(input_file, output_file):
    base_scope = create_built_in_scope()
    scope = Scope(base_scope)
    parser = Parser(file_token_stream(input_file))
    for paragraph in parser.iter_paragraph(scope):
        result = evaluate(paragraph, scope)
        if isinstance(result, Action):
            result.do(scope)
        else:
            print(result, file=output_file)
Esempio n. 30
0
    def create_new_scope(name, global_scope):
        """
        Helper function to create new scope
        :param name:
        :param global_scope:
        :return:
        """
        curr_scope = Scope(name, global_scope)

        return curr_scope
Esempio n. 31
0
def run_file(filename, check=False):
    """
    Executes the N file at the given file path. Returns a human-readable string
    if there was an error or None if everything went well.
    """

    file = None

    try:
        with open(filename, "r", encoding="utf-8") as f:
            file = File(f)
    except:
        print((Fore.RED + "Error" + Fore.RESET + ": Unable to read file " +
               Fore.YELLOW + "%s" + Fore.RESET) % filename)
        exit()

    file_path = path.abspath(filename)
    global_scope = Scope(base_path=path.dirname(file_path),
                         file_path=file_path)
    add_funcs(global_scope)

    try:
        tree = file.parse(n_parser)
    except lark.exceptions.UnexpectedCharacters as e:
        return format_error(e, file)
    except lark.exceptions.UnexpectedEOF as e:
        return format_error(e, file)

    try:
        errors, error_count, warning_count = type_check(
            global_scope, file, tree, check)
    except Exception as err:
        debug = os.environ.get("N_ST_DEBUG") == "dev"
        if debug:
            raise err
        return stack_trace.display(global_scope.stack_trace, False)

    if error_count > 0 or check:
        error_s = ""
        warning_s = ""
        if error_count != 1:
            error_s = "s"
        if warning_count != 1:
            warning_s = "s"
        return f"{errors}\n{Fore.BLUE}Ran with {Fore.RED}{error_count} error{error_s}{Fore.BLUE} and {Fore.YELLOW}{warning_count} warning{warning_s}{Fore.BLUE}.{Style.RESET_ALL}"

    try:
        asyncio.get_event_loop().run_until_complete(
            parse_tree(global_scope, tree, file))
        return global_scope
    except Exception as err:
        debug = os.environ.get("N_ST_DEBUG") == "dev"
        if debug:
            raise err
        return stack_trace.display(global_scope.stack_trace)
Esempio n. 32
0
    def test_link_flexible_setters(self):

        # we can test linking at the initalization

        phrase = 'my name is not setted'
        phrase = Phrase(phrase, Scope())
        self.assertEqual(phrase.flexibles, [])

        phrase = 'my name is `name~Mark` and i do like `objects~cats`'
        phrase = Phrase(phrase, Scope())
        self.assertEqual(phrase.flexibles, \
            [['name', 'Mark', 11, 15, 4], ['objects', 'cats', 30, 34, 9]])
        # flexible setter is linked with #4 and #9 in sentence
        # my name is Mark and i do like cats

        # known bug
        phrase = '`object1~word` is `object2~word`'
        phrase = Phrase(phrase, Scope())
        self.assertEqual(phrase.flexibles, \
            [['object1', 'word', 0, 4, 1], ['object2', 'word', 8, 12, 3]])
Esempio n. 33
0
 def test_iter_paragraph(self):
     scope = Scope()
     with patch('parse.Parser.parse_paragraph', side_effect=[1, 2, 3],
             autospec=True) as paragraph_mock:
         with patch('parse.TokenStream.not_empty', autospec=True,
                 side_effect=[True, True, False]) as not_empty_mock:
             parser = fake_parser(['One', 'two'])
             for paragraph in parser.iter_paragraph(scope):
                 pass
     self.assertEqual(2, paragraph_mock.call_count)
     self.assertEqual(3, not_empty_mock.call_count)
Esempio n. 34
0
class test_scope(unittest.TestCase):
	def setUp(self):
		self.tree = makeTestNodeTree()
		self.scope = Scope(b.instances[0])
		
	def test_locating(self):
		self.assertEqual(self.scope.getTopmost(), b.instances[0])
		self.assertEqual(self.scope.getChildren(), 
			[c.instances[0], d.instances[0], c.instances[1]])
		# self.assertEqual(self.scope.topDown(), 
		# 	[c.instances[0], d.instances[0], c.instances[1]])
			
	def test_iterating(self):
		l = []
		for x in self.scope:
			l.append(x)
			
		self.assertEqual(l, [c.instances[0], d.instances[0], c.instances[1]])
		
		for x in self.scope:
			self.assertTrue(x in self.scope)
Esempio n. 35
0
def lex(fname):
    source = open(fname, "r").read().rstrip("\r\n")
    lexer = Lexer(fname, source)
    tokens, error = lexer.make_tokens()

    if error:
        return None, error

    parser = Parser(tokens)
    tree = parser.parse()

    if tree.error:
        return None, tree.error

    global_scope = Scope()
    global_scope.set("NULL", Number(0))
    global_scope.set("TRUE", Number(1))
    global_scope.set("FALSE", Number(0))

    interpreter = Interpreter()
    context = Context("<main>")
    context.scope = global_scope
    result = interpreter.visit(tree.node, context)

    return result.value, result.error
Esempio n. 36
0
    def __init__(self):

        self.server = OSCServer(("192.168.2.122", 5005))
        self.server.timeout = 0

        self.driver = DriverAdaMatrix(rows=32, chain=2)
        self.driver.SetPWMBits(6)

        self.led = LEDMatrix(self.driver, 64, 32, serpentine=False)

        self.modes = [
            self.mode_presets, self.color_presets, self.color_gradient,
            self.white_gradient, self.direct_control, self.arcade,
            self.mindfuck
        ]

        self.color = colors.Salmon
        self.wheel = ColorWheel()

        self.running = True

        self.joysticks = [0] * 5

        self.pong = Pong(self.led)

        self.scope = Scope(self.led, self.wheel)

        self.scheme = []

        # funny python's way to add a method to an instance of a class
        # import types
        # self.server.handle_timeout = types.MethodType(lambda: self.handle_timeout(self), self.server)
        self.server.addMsgHandler("/mode", self.mode_callback)
        self.server.addMsgHandler("/coin", self.coin_callback)
        self.server.addMsgHandler("/js", self.joystick_callback)
        self.server.addMsgHandler("/pot", self.pot_callback)
        self.server.addMsgHandler("/fad", self.fader_callback)
        self.server.addMsgHandler("/beam", self.beam_callback)
        self.server.addMsgHandler("/scheme", self.scheme_callback)
        self.server.addMsgHandler("/sleep", self.sleep_callback)
Esempio n. 37
0
def process(key, obj, session=None):
    __session = None;
    __emitter = False;
    __new_scope = False;

    if (session == None):
        __session = __connection__.session();
        __emitter = True;
    else:
        __session = session;

    if (obj == None) :
        return;

    # process list of objects with same key
    if (type(obj) == type([])):
        for i in obj:
            process(key, i);
    # process dictionary of multiple objects 
    elif (type(obj) == type({})):
        for i in obj.keys():
            
            if (i == 'scope'):
                Scope.push(obj);
                __new_scope = True;
            
            for i in __classes__:
                if (i.check(key)):
                    _scope, _children = i.inject(obj, __session);
                    for i in _children.keys():
                        process(i, i[key]);
                    break;
                
    if (__emitter) :
        __session.save();
        __session.close();
    
    if (__new_scope):
        Scope.pop();
    return;
Esempio n. 38
0
def main():
    server_port = 5000
    client_list = set()

    argc = len(sys.argv)
    if argc < 2 or argc > 3:
        usage()
        sys.exit(-1)

    serial_port = sys.argv[1]

    if argc == 3:
        server_port = int(sys.argv[2])

    data_sender = ScopeDataSender(client_list)
    scope = Scope(serial_port)
    scope.set_big_preamp(Scope.CHANNEL_A)
    scope.set_big_preamp(Scope.CHANNEL_B)
    scope.set_sample_rate_divisor(0x7)
    scope_read_thread = ScopeReadThread(scope, data_sender)

    def stop_server_and_exit(signum, frame):
        print '\rStopping server'
        scope_read_thread.stop()
        scope_read_thread.join()
        reactor.stop()

    def status_message(msg):
        print msg

    signal.signal(signal.SIGINT, stop_server_and_exit)
    scope_read_thread.start()

    reactor.listenTCP(server_port, ScopeFactory(client_list))
    reactor.callWhenRunning(
            status_message, 'Server started on port %d' % server_port)
    reactor.run()
Esempio n. 39
0
    def __init__(self):
        
        self.server = OSCServer( ("192.168.2.122", 5005) )
        self.server.timeout = 0

        self.driver = DriverAdaMatrix(rows=32, chain=2)
        self.driver.SetPWMBits(6)

        self.led = LEDMatrix(self.driver, 64, 32, serpentine=False)

        self.modes = [self.mode_presets, self.color_presets,
                      self.color_gradient, self.white_gradient,
                      self.direct_control, self.arcade, self.mindfuck]

        self.color = colors.Salmon
        self.wheel = ColorWheel()

        self.running = True

        self.joysticks = [0] * 5
        
        self.pong = Pong(self.led)
        
        self.scope = Scope(self.led, self.wheel)

        self.scheme = []
        
        # funny python's way to add a method to an instance of a class
        # import types
        # self.server.handle_timeout = types.MethodType(lambda: self.handle_timeout(self), self.server)
        self.server.addMsgHandler("/mode", self.mode_callback)
        self.server.addMsgHandler("/coin", self.coin_callback)
        self.server.addMsgHandler("/js", self.joystick_callback)
        self.server.addMsgHandler("/pot", self.pot_callback)
        self.server.addMsgHandler("/fad", self.fader_callback)
        self.server.addMsgHandler("/beam", self.beam_callback)
        self.server.addMsgHandler("/scheme", self.scheme_callback)
        self.server.addMsgHandler("/sleep", self.sleep_callback)
Esempio n. 40
0
    def run(self):
        if len(self.code) == 0:
            return

        stack = []
        table = Scope() 
        addresses = []
        #print self.code
        i = 0

        while i < len(self.code):
            current = self.code[i]
            if current == 'LOAD_CONST':
                i += 1
                current = self.code[i]
                stack.append(current)
            elif current == 'STORE':
                try:
                    i += 1
                    current = self.code[i]
                    table[current] = stack.pop()
                except IndexError:
                    msg = "Index: %s - Current: %s" % (str(i), str(current))
                    raise errors.EmptyStackException(msg)
            elif current == 'LOAD':
                i += 1 
                current = self.code[i]
                stack.append(table[current])
            elif current == 'PRINT':
                print stack.pop()
            elif current == 'CJUMP':
                """
                JNE
                <absoluter offset>
                Springt zum offset, falls der aktuelle Wert auf dem Stack 
                ´False´ ist. 
                """
                i += 1
                offset = int(self.code[i])
                condition = stack.pop()
                if not condition:
                    i = offset # sprung
                    continue
            elif current == 'JUMP':
                """
                JUMP
                <absoluter offset>
                Bedingungsloser Sprung zum offset.
                """
                i += 1
                offset = int(self.code[i])
                i = offset # sprung
                continue
            elif current in operations:
                try:
                    val1 = int(stack.pop())
                    val2 = int(stack.pop())
                except ValueError:
                    msg = """ Index: %s - Invalid operand for arithmetical 
                              operation: %s %s""" % (str(val1), str(val2))
                    raise errors.InvalidOperandException(msg)
                except IndexError:
                    msg = "Index: %s - Current: %s" % (str(i), str(current))
                    raise errors.EmptyStackException(msg)
                res = operations[current](val1, val2)
                stack.append(res)
            elif current == "EOF":
                return
            elif current == "PUSH_SCOPE":
                table.push({})
            elif current == "POP_SCOPE":
                table.pop()
            elif current == "PUSH_ADDRESS":
                i += 1
                offset = int(self.code[i])
                addresses.append(offset)
            elif current == "RET":
                assert addresses # Return without address doesn't make sense ;)
                offset = addresses.pop()
                i = offset
            else:
                try:
                    int(current)
                except ValueError:
                    msg = """Index: %s - 
                             Invalid Opcode: %s""" % (str(i), str(current))
                    raise errors.InvalidOpcodeException(msg) 
            i += 1
Esempio n. 41
0
class Task(object):
	def __init__(self):
		# all the appropriate scopes
		self.functions = Scope()
		self.synth_function = None
		self.variables = Scope()
		self.constraints = []
		self.system = None
	def add_system(self, s):
		self.system = s
	def parse(self, sexpr):
		# now let's process the file
		for cmd, *args in sexpr:
			if cmd == "set-logic":
				self.logic = args[0]
			elif cmd == "define-fun":
				func = Function(*args, self.functions.zoom())
				self.functions[func.name] = func
			elif cmd == "synth-fun":
				if self.synth_function != None:
					raise Exception("We only support a single function")
				self.synth_function = SynthFun(*args, self.functions.zoom())
			elif cmd == "declare-var":
				var = Variable(*args)
				self.variables[var.name] = var
			elif cmd == "constraint":
				self.constraints.append(args[0])
			elif cmd == "check-synth":
				return self.synthesize()
			else:
				pass
	def synthesize(self):
		# let's make some solvers
		#synth_solver = Solver()
		#verify_solver = Solver()
		# get our spec constraint
		scope = self.functions.update(mapping)
		constraint = Constraint(self.constraints, self.synth_function, self.variables, scope)
		# define some search parameters
		if DEBUG:
			print(self.constraints)
			print(constraint.constraints)
			print(constraint.input)
			input("Hit enter to start synthesis")
		breadth = 1
		while breadth < MAX_BREADTH:
			components = {}
			# create components based on breadth:
			for component in self.synth_function.components:
				if component.is_constant:
					comp_id = "{}.const".format(component._id)
					components[comp_id] = component
				else:
					for b in range(breadth):
						comp_id = "{}.{}".format(component._id, b)
						components[comp_id] = component
			if DEBUG: 
				print("Starting synthesis with breadth {}...".format(breadth))
				print("Components map:")
				pprint(components)
			# now actually synthesize
			solution = self.synthesize_with_components(components, constraint, self.system)
			if solution:
				if DEBUG: print("Found solution.")
				return self.extract_program(solution, components)
			else:
				if DEBUG: print("No solution at that size.")
				breadth += 1
	def synthesize_with_components(self, components, constraint, system):
		# components maps unique comp_ids to component objects
		# not one-to-one, but def. onto
		# step 0: some useful values
		card_I, N = len(self.synth_function.parameters), len(components)
		# step 1: make some solvers
		synth_solver = Solver()
		verify_solver = Solver()
		# step 2: initialize examples
		S = []
		# step 2b: create location variables and location constraints
		initial_constraints = []
		L = create_location_variables(components)
		if system:
			patterns = create_pattern_constraints(L, components, system)
			initial_constraints.append(patterns)
		wfp = create_wfp_constraint(L, N)
		initial_constraints.append(wfp)
		# step 3: looooooooop
		while True:
			# step 4: assert L constraint
			synth_solver.assert_exprs(*initial_constraints)
			# step 5: start the looooop
			for i, X in enumerate(S):
				I, O, T = [], [], []
				for w in range(constraint.width):
					# step 6: create I, O, T for synth at width i
					I_w = create_input_variables(self.synth_function.parameters, i, w)
					O_w = create_output_variables(self.synth_function.output, i, w)
					T_w = create_temp_variables(components, i, w)
					# step 7: assert library and connection constraints
					lib = create_lib_constraint(T_w, I_w, components)
					# for conn constraint, need map from component_id to l value
					locations = create_location_map(O_w, T_w, L, N)
					conn = create_conn_constraint(O_w, T_w, locations)
					synth_solver.assert_exprs(lib, conn)
					I += I_w
					O += O_w
					T += T_w
				# step 8: once we've got all the I, O, we can assert the spec constraint
				conn_spec, spec = create_spec_constraint(I, O, X, constraint)
				synth_solver.assert_exprs(conn_spec, spec)
			# get a model, or just bail
			if synth_solver.check() == unsat:
				if DEBUG: print("Failed to find a model.")
				return None
			model = synth_solver.model()
			curr_l = [l._replace(value=model[l.value]) for l in L]

			# step 9: need to verify the model we just found, so we'll construct verificatio constraint
			I, O, T = [], [], []
			for w in range(constraint.width):
				# same as above, but we only have a single example
				I_w = create_input_variables(self.synth_function.parameters, 0, w)
				O_w = create_output_variables(self.synth_function.output, 0, w)
				T_w = create_temp_variables(components, 0, w)
				lib = create_lib_constraint(T_w, I_w, components)
				locations = create_location_map(O_w, T_w, curr_l, N)
				conn = create_conn_constraint(O_w, T_w, locations)
				verify_solver.assert_exprs(lib, conn)
				I += I_w
				O += O_w
				T += T_w
			# now we need to create variables for X so we can check our spec
			X = create_spec_variables(constraint, self.variables)
			conn_spec, spec = create_spec_constraint(I, O, X, constraint)
			verify_solver.assert_exprs(conn_spec, Not(spec))
			# now we'll try and get a model of our exectution
			if verify_solver.check() == unsat:
				return curr_l
			model = verify_solver.model()
			example = [x._replace(value=model[x.value]) for x in X]
			S.append(example)
			if DEBUG:
				print("Found bad solution: ", [l.value.sexpr() for l in curr_l])
			# clear synthesizers and start anew
			synth_solver.reset()
			verify_solver.reset()
		return None
	def extract_program(self, L, components):
		N = len(components)
		# we need to work our way back through the program, all the way to the params
		worklist = [N - 1]
		components_used = []
		# pick up all the components used, and in which order
		while worklist:
			cur = worklist.pop()
			source = [l for l in L if l.value.as_long() == cur and l.type == "return"][0]
			for p, s in components[source.component].parameters:
				k = [l for l in L if l.component == source.component and l.parameter == p][0]
				worklist.append(k.value.as_long())
			components_used.append(components[source.component])
		left = []
		while components_used:
			cur = components_used.pop()
			if isinstance(cur, Component):
				arity = len(cur.parameters)
				args = {}
				for i in range(arity):
					args["PARAM.{}".format(i)] = left.pop()
				left.append(cur.eval_as_sexpr(args))
			else:
				left.append(cur)
		return ['define-fun', self.synth_function.name, self.synth_function.parameters, left[0]]
Esempio n. 42
0
 def getScope(self, line):
     scope = Scope()
     scope.name = self.getScopeName(line)
     scope.indentLevel = self.getIndentLevel(line)
     return scope
Esempio n. 43
0
 def __init__(self, ast):
     self.ast = ast
     self.classes = {}
     self.parents = defaultdict(set)
     self.scope = Scope()
Esempio n. 44
0
class Semant(object):
    """ Analyzes semantically the code. """

    def __init__(self, ast):
        self.ast = ast
        self.classes = {}
        self.parents = defaultdict(set)
        self.scope = Scope()

    def build(self):
        self.__create_default_classes()
        self.__create_symbol_tables()
        self.__check_undefined_classes()
        self.__check_inheritance_cycles()
        self.__check_inheritence_and_add_methods_in_children()

        for _class in self.classes.keys():
            self.__check_scope_and_type(self.classes[_class])

    def __create_default_classes(self):
        # Object there is no parent
        objc = Class("Object", None, [
            Method('abort', [], 'Object', None),
            Method('type_name', [], 'String', None),
            Method('copy', [], 'SELF_TYPE', None),
        ])
        # IO inherits from Object
        ioc = Class("IO", "Object", [
            Method('out_string', [('arg', 'String')], 'SELF_TYPE', None),
            Method('out_int', [('arg', 'Int')], 'SELF_TYPE', None),
            Method('in_string', [], 'String', None),
            Method('in_int', [], 'Int', None),
        ])
        # Interge inherits from Object
        intc = Class("Int", "Object", [
            Attr('variable', 'Int', Int(content=0))
        ])
        # String inherits from Object
        stringc = Class("String", "Object", [
            Method('length', [], 'Int', None),
            Method('concat', [('arg', 'String')], 'String', None),
            Method(
                'substr', [('arg1', 'Int'), ('arg2', 'Int')], 'String', None
            ),
        ])
        # Boolean inherits from Object
        boolc = Class("Bool", "Object", [
            Attr('variable', 'Bool', Bool(content=False))
        ])

        self.ast += [objc, ioc, intc, stringc, boolc]

    def __create_symbol_tables(self):
        """
            Create two tables:
            One with all the classes and another with all
            parents classes.
        """
        for _class in self.ast:
            if _class.name in self.classes:
                raise ClassAlreadyDefinedError(_class.name)

            else:
                self.classes[_class.name] = _class

            if _class.name != 'Object':
                self.parents[_class.parent].add(_class.name)

    def __check_undefined_classes(self):
        """
            Check if every parent is defined in classes table. (self.classes)
        """
        parents = self.parents.keys()

        for parent in parents:
            if parent not in self.classes:
                class_name = self.parents[parent]
                raise UndefinedParentError(class_name, parent)

    def __check_inheritance_cycles(self):
        """
            Check if every class has your right parent and children.

            First, set every class(including parents) as False.
            Then, visit each class and their children.
        """
        visited = {}
        for parent_name in self.parents.keys():
            visited[parent_name] = False
            for child_name in self.parents[parent_name]:
                visited[child_name] = False

        # Visit every class, recursively, starting with Object
        self.__visit_tree('Object', visited)

        # If some class has False value, means that the visitor
        # couldn't get in that class. So, some class is missing.
        for key, value in visited.items():
            if not value:
                raise InheritanceError(key)

    def __visit_tree(self, _class, visited):
        visited[_class] = True

        # If a _class is not in parents,
        # it is not a parent, so, don't have children. Get out.
        if _class not in self.parents.keys():
            return

        for child in self.parents[_class]:
            self.__visit_tree(child, visited)

    def __check_inheritence_and_add_methods_in_children(self, _class='Object'):
        """
            Check attributes and methods from inheritance and
            if it is ok, add them from parent to child.
        """
        cl = self.classes[_class]

        if cl.parent:
            _class_parent = self.classes[cl.parent]

            attrs_of_parent = self.__get_attributes(_class_parent)
            attrs_of_child = self.__get_attributes(cl)

            self.__check_same_attribute(
                attrs_of_parent, attrs_of_child, _class
            )

            methods_of_parent = self.__get_methods(_class_parent)
            methods_of_child = self.__get_methods(cl)

            method_signatures_of_parent = self.__get_signatures(
                methods_of_parent
            )
            method_signatures_of_child = self.__get_signatures(
                methods_of_child
            )

            self.__check_same_signature(
                methods_of_child,
                method_signatures_of_parent,
                method_signatures_of_child
            )

            self.__add_method_from_parent_to_child(
                cl, methods_of_parent, methods_of_child
            )

            self.__add_attr_from_parent_to_child(cl, attrs_of_parent)

        # Goes recursively to all children
        all_children = self.parents[_class]
        for child in all_children:
            self.__check_inheritence_and_add_methods_in_children(child)

    def __get_attributes(self, _class):
        return [i for i in _class.feature_list if isAttribute(i)]

    def __check_same_attribute(self, parent, child, _class):
        """
            It's illegal to redefine attribute names in child class.
        """
        for p_attr in parent:
            for c_attr in child:
                if p_attr.name == c_attr.name:
                    raise RedefinedAttributeError(_class)

    def __get_methods(self, _class):
        return [i for i in _class.feature_list if isMethod(i)]

    def __get_signatures(self, methods):
        method_signatures = {}
        for method in methods:
            method_signatures[method.name] = {}
            for formal in method.formal_list:
                # formal is a tuple that has 2 values:
                # The first one is the name of the argument;
                # The second, is the type of the argument (Int, Bool,...)
                method_signatures[method.name][formal[0]] = formal[1]
            method_signatures[method.name]['return'] = method.return_type
        return method_signatures

    def __check_same_signature(self, child_methods, sig_parent, sig_child):
        """
            If a class "B" inherits a method "m" from an ancestor class "A",
            then "B" may override the inherited definition of "m" provided
            the number of arguments, the types of the formal parameters,
            and the return type are exactly the same in both definitions.
        """
        for method in child_methods:
            if method.name in sig_parent:
                parent_signature = sig_parent[method.name]
                child_signature = sig_child[method.name]

                if parent_signature != child_signature:
                    raise RedefinedMethodError(method.name)

    def __add_method_from_parent_to_child(self, _cl, p_methods, c_methods):
        for method in p_methods:
            if method.name not in c_methods:
                copied_method = deepcopy(method)
                # Add at the beginning
                _cl.feature_list.insert(0, copied_method)

    def __add_attr_from_parent_to_child(self, _cl, attrs_of_parent):
        for attr in attrs_of_parent:
            # Add at the beginning
            _cl.feature_list.insert(0, deepcopy(attr))

    def __check_scope_and_type(self, _class):
        """
            Check scope and type for each class.

            If it's a method, goes recursively inside the body.

            When a scope is created?
            With a new block, let, case,

            OBS: Every attribute is protected and every method is public.
        """

        for feature in _class.feature_list:
            _type = returned_type(feature, _class)

            if isAttribute(feature):
                value_type = get_expression_type(
                    feature.body, _class, self.scope
                )

                if not value_type:
                    # If value_type is None, means that feature.body is
                    # a complex expression, need to be checked.
                    self.__check_children(feature.body, _class)

                # Test if the attribute value type is the same as declared.
                if feature.type != value_type:
                    raise AttributeTypeError(feature, value_type)

                self.scope.add(feature.name, _type)

            elif isMethod(feature):
                self.scope.add(feature.name, _type)

                # Add arguments to scope. name:type
                for formal in feature.formal_list:
                    self.scope.add(formal[0], formal[1])

                self.__check_children(feature.body, _class)

    def __check_children(self, expression, _class):
        if isinstance(expression, Block):
            self.scope.new()

            for expr in expression.body:
                self.__check_children(expr, _class)

            self.scope.destroy()

        elif isinstance(expression, Dispatch):
            self.__check_children(expression.body, _class)

            # Get return type
            if expression.body == 'self':
                _class_name = _class.name
            else:
                try:
                    _class_name = expression.body.return_type
                except AttributeError:
                    # If the expression is an Object and there is no
                    # return_type variable, so, need get the type.
                    _class_name = get_expression_type(
                        expression.body, _class, self.scope
                    )

            # Get the whole class' structure
            _class_content = self.classes[_class_name]

            called_method = False

            # Parse the structure untill match the method name
            for feature in _class_content.feature_list:
                if isMethod(feature) and feature.name == expression.method:
                    called_method = True

                    if len(feature.formal_list) != len(expression.expr_list):
                        raise NumberOfArgumentError(feature.name, _class_name)

                    formals = zip(
                        feature.formal_list, expression.expr_list,
                    )

                    # Test if the arguments types are not equals
                    for feat, called in formals:
                        expression_type = get_expression_type(
                            called, _class, self.scope
                        )
                        # feat[0] is the name and feat[1] the type
                        if feat[1] != expression_type:
                            raise ArgumentTypeError(feature, _class_name)

                    # For default, the method returns the host class. SELF_TYPE
                    last_type = _class_name

                    feature_type = returned_type(feature, _class)

                    # If exists a body, means that exists one or more
                    # expressions inside the method.
                    if feature.body:
                        try:
                            # If have a Block, must look the last expression,
                            # because it is the type that will be returned.
                            last_expression = feature.body.body[-1]
                        except AttributeError:
                            last_expression = feature.body

                        last_type = get_expression_type(
                            last_expression, _class, self.scope
                        )

                    # If the returns types are not equals, raise an error
                    if feature_type != last_type:
                        raise ReturnedTypeError(
                            feature.name, _class_name, feature_type, last_type
                        )

            # If didn't match the method name...
            if not called_method:
                raise UndefinedMethodError(expression.method, _class_name)

        elif isinstance(expression, Let):
            self.scope.new()
            self.scope.add(expression.object, expression.type)

            # Test if the declared type is the same type as
            # the given value
            value_type = get_expression_type(
                expression.init, _class, self.scope
            )
            if expression.type != value_type:
                raise DeclaredTypeError(expression.type, value_type)

            self.__check_children(expression.body, _class)

            self.scope.destroy()

        elif isinstance(expression, While):
            self.__check_children(expression.predicate, _class)
            self.__check_children(expression.body, _class)
            # If the methods above did not raise an error, means that
            # the body's type is Int or an Object.
            # If is an Object and the root type is not a Bool,
            # must raise an error.
            self.__raise_if_not_bool(expression, _class, 'While')

        elif isinstance(expression, Lt) or isinstance(expression, Le):
            first_type, second_type = self.__get_params_types(
                expression, _class
            )

            if first_type != 'Int' or second_type != 'Int':
                raise TypeCheckError(first_type, second_type, _class)

        elif isinstance(expression, Eq):
            """
                The comparison = is a special case.
                If either <expr1> or <expr2> has static type Int, Bool,
                or String, then the other must have the same static type.
            """
            first_type, second_type = self.__get_params_types(
                expression, _class
            )
            types = ['String', 'Int', 'Bool']
            if first_type not in types or second_type not in types:
                raise EqualTypeCheckError(first_type, second_type, _class)

            if first_type != second_type:
                raise EqualCheckError(first_type, second_type, _class)

        elif any(isinstance(expression, X) for X in [Plus, Sub, Mult, Div]):
            """
                The static types of the two sub-expressions must be Int.

                Cool has only integer division.
            """
            first_type, second_type = self.__get_params_types(
                expression, _class
            )

            if first_type != 'Int' or second_type != 'Int':
                raise ArithmeticError(first_type, second_type, _class)

        elif isinstance(expression, Assign):
            self.__check_children(expression.body, _class)
            # If the method above did not raise an error, means that
            # the body type is Int. Just need to test name type now.
            name_type = get_expression_type(
                expression.name, _class, self.scope
            )

            if name_type != 'Int':
                raise AssignError(name_type, 'Int', _class)

        elif isinstance(expression, If):
            self.__check_children(expression.predicate, _class)
            self.__check_children(expression.then_body, _class)
            self.__check_children(expression.else_body, _class)
            # If the methods above did not raise an error, means that
            # the body type is Int or an Object.
            # If is an Object and the root type is not a Bool,
            # must raise an error.
            self.__raise_if_not_bool(expression, _class, 'If')

    def __raise_if_not_bool(self, expression, _class, statement):
        if isinstance(expression.predicate, Object):
                obj_type = get_expression_type(
                    expression.predicate, _class, self.scope
                )
                if obj_type != 'Bool':
                    raise ConditionStatementError(statement, obj_type, _class)

    def __get_params_types(self, expression, _class):
        first_type = get_expression_type(
            expression.first, _class, self.scope
        )
        second_type = get_expression_type(
            expression.second, _class, self.scope
        )
        return first_type, second_type
Esempio n. 45
0
def KeyThread(modbus, scope):
	'''Thread to get command from console.'''
	global f;

	key = input("Press Enter to continue...\n> ");
	f.close();
	print("bye-bye");
	os.kill(os.getpid(), signal.SIGINT)

if __name__ == '__main__':
	global data;
	global f;
	global ReadingADC;

	modbus = Modbus("/dev/ttyUSB0", 115200, 5);
	scope = Scope();
	data = [[] for i in range(modbus.GetNumChannels())];
	rt = threading.Thread(target=ReadThread, args=(modbus, scope, 0.01));
	wt = threading.Thread(target=WriteThread, args=(scope,));
	kt = threading.Thread(target=KeyThread, args=(modbus, scope,));
	filename = "data-" + time.strftime("%Y%m%d%H%M%S") + ".txt";
	f = open(filename, "w");

	# Bind data to scope.
	scope.data = data;
	# Send start sample command to oscilloscope.
	modbus.StartSample();

	ReadingADC = False;

	# Start threads.
Esempio n. 46
0
	def setUp(self):
		self.tree = makeTestNodeTree()
		self.scope = Scope(b.instances[0])
Esempio n. 47
0
class Matrix(object):
    server = None
    driver = None
    led = None
    modes = []
    running = False
    color = None
    wheel = None

    pong = None
    scope = None

    mode = 0;

    joysticks = []

    pong_running = False
    scope_running = False

    def __init__(self):
        
        self.server = OSCServer( ("192.168.2.122", 5005) )
        self.server.timeout = 0

        self.driver = DriverAdaMatrix(rows=32, chain=2)
        self.driver.SetPWMBits(6)

        self.led = LEDMatrix(self.driver, 64, 32, serpentine=False)

        self.modes = [self.mode_presets, self.color_presets,
                      self.color_gradient, self.white_gradient,
                      self.direct_control, self.arcade, self.mindfuck]

        self.color = colors.Salmon
        self.wheel = ColorWheel()

        self.running = True

        self.joysticks = [0] * 5
        
        self.pong = Pong(self.led)
        
        self.scope = Scope(self.led, self.wheel)

        self.scheme = []
        
        # funny python's way to add a method to an instance of a class
        # import types
        # self.server.handle_timeout = types.MethodType(lambda: self.handle_timeout(self), self.server)
        self.server.addMsgHandler("/mode", self.mode_callback)
        self.server.addMsgHandler("/coin", self.coin_callback)
        self.server.addMsgHandler("/js", self.joystick_callback)
        self.server.addMsgHandler("/pot", self.pot_callback)
        self.server.addMsgHandler("/fad", self.fader_callback)
        self.server.addMsgHandler("/beam", self.beam_callback)
        self.server.addMsgHandler("/scheme", self.scheme_callback)
        self.server.addMsgHandler("/sleep", self.sleep_callback)

    # this method of reporting timeouts only works by convention
    # that before calling handle_request() field .timed_out is 
    # set to False
    def handle_timeout(self):
        self.timed_out = True

    # TODO: update this to take all the joysticks and send them off selectively
    def joystick_callback(self, path, tags, args, source):
        if self.pong_running:
            self.pong.update_sticks(args[0], args[4])
        elif self.scope_running:
            self.scope.update_sticks(args)

    def pot_callback(self, path, tags, args, source):
        if self.scope_running:
            self.scope.update_pots(args)

    def fader_callback(self, path, tags, args, source):
        if self.scope_running:
            self.scope.update_faders(args)

    def beam_callback(self, path, tags, args, source):
        if self.scope_running:
            self.scope.update_beam(args[0])

    def mode_callback(self, path, tags, args, source):
        self.scope_running = True
        self.led.all_off()
        if (self.mode == 5 and int(args[0]) != 5):
            self.pong_running = False
        self.mode =int(args[0])
        self.modes[self.mode]()
        self.led.update()
        sleep(1)

    def coin_callback(self, path, tags, args, source):
        self.led.all_off()
        self.led.update()
        count = 0
        while count < 5:
            self.led.drawText("Thank You!!", 4, 10, size=1, color=colors.Lavender)
            self.led.update()
            sleep(1)
            self.led.all_off()
            self.led.update()
            sleep(0.5)
            count += 1
        self.modes[self.mode]()
        self.led.update()

    def scheme_callback(self, path, tags, args, source):
        self.scheme = []
        for i in xrange(0, len(args), 3):
            self.scheme.append(args[i:i+3])
        self.wheel.setScheme(self.scheme)

    def sleep_callback(self, path, tags, args, source):
        print("sleep plz")
        self.scope_running = False
        self.pong_running = False
        self.led.all_off()
        self.led.update()

    # user script that's called by the game engine every frame
    def each_frame(self):
        # clear timed_out flag
        self.server.timed_out = False
        # handle all pending requests then return
        while not self.server.timed_out:
            self.server.handle_request()
            if self.pong_running:
                self.led.all_off()
                self.pong.step()
                self.led.update()
                sleep(0.05)
            elif self.scope_running:
                self.led.all_off()
                self.scope.step()
                self.led.update()
                sleep(0.05)

    def mode_presets(self):
        self.led.drawText("Mode", 6, 5, size=1, color=self.color)
        self.led.drawText("Presets", 6, 15, size=1, color=self.color)

    def color_presets(self):
        self.led.drawText("Color", 6, 5, size=1, color=self.color)
        self.led.drawText("Presets", 6, 15, size=1, color=self.color)

    def color_gradient(self):
        self.led.drawText("Color", 6, 5, size=1, color=self.color)
        self.led.drawText("Gradients", 6, 15, size=1, color=self.color)

    def white_gradient(self):
        self.led.drawText("White", 6, 5, size=1, color=self.color)
        self.led.drawText("Gradients", 6, 15, size=1, color=self.color)

    def direct_control(self):
        self.led.drawText("Direct", 6, 5, size=1, color=self.color)
        self.led.drawText("Control", 6, 15, size=1, color=self.color)

    def arcade(self):
        # self.led.drawText("Arcade", 6, 5, size=1, color=self.color)
        # self.led.drawText("Mode!!!", 6, 15, size=1, color=self.color)
        anim = ScrollText(self.led, "Arcade Mode!!!!!", 64, 13, size=1, color=self.color)
        anim.run(fps=30, untilComplete=True, max_cycles=1)
        self.pong.reset()
        self.scope_running = False
        self.pong_running = True
        

    def mindfuck(self):
        self.led.drawText("Y U NO", 6, 5, size=1, color=self.color)
        self.led.drawText("LISTEN?!", 6, 15, size=1, color=self.color)
        self.scope_running = False

    def run(self):
        while self.running:
            sleep(1)
            self.each_frame()
Esempio n. 48
0
 def __init__(self, mother, children):
     Scope.__init__(self)
     self.set_mother(mother)
     self.set_children(children)
Esempio n. 49
0
	def __call__(self, params, output, circuit_scope):
		scope = Scope.merge(circuit_scope, self.scope)
		arguments = dict_params_with(self.parameters, params)
		return evaluate_in_scope(self.sexpr, scope.update(arguments))