示例#1
0
    def add_node(self, prev, worker, gstate, do_hash=True):
        if do_hash:
            hash = gstate.compute_hash()
            if hash is not None:
                node = self.statespace.get_node_by_hash(hash)
                if node is not None:
                    return (node, False)
        else:
            hash = None
        uid = str(self.statespace.nodes_count)
        node = Node(uid, hash)
        logging.debug("New node %s", node.uid)

        if prev:
            node.prev = prev
        self.statespace.add_node(node)

        if self.debug_compare_states is not None \
                and node.uid in self.debug_compare_states:
            if self.debug_captured_states is None:
                self.debug_captured_states = []
            logging.debug("Capturing %s", node)
            self.debug_captured_states.append((gstate.copy(), worker))

        if self.statespace.nodes_count > self.max_states:
            logging.info("Maximal number of states reached")
            if self.debug_compare_states is not None:
                self.debug_compare()
            raise ErrorFound()

        if self.debug_state == uid:
            context = Context(self, node, None)
            context.add_error_and_throw(
                errormsg.StateCaptured(context, uid=uid))
        return (node, True)
示例#2
0
    def test(self):
        c = Context('Root')
        c.start()

        o0 = self.SampleObj()
        Dispatcher.add(obj=o0, parent_obj=None, context=c)

        o1 = self.SampleObj()
        Dispatcher.add(obj=o1, parent_obj=None, context=c)
        Dispatcher.add_listener(src_obj=o1, dst_obj=o0)

        Dispatcher.send(event=Event('1'), src_obj=o0, dst_obj=o1)
        assert str(o1.lastHandler) == 'on1'

        Dispatcher.queue(event=Event('2'), src_obj=o0, dst_obj=o1)
        #assert str(o1.lastHandler) == 'on2'

        Dispatcher.send(event=Event('3'), src_obj=o0, dst_obj=o1)
        #assert str(o1.lastHandler) == 'on3'

        Dispatcher.notify(event=Event('4'), src_obj=o1)
        #assert str(o1.lastHandler) == 'on4'
        Dispatcher.notify(event=Event('4'), src_obj=o1)
        #assert str(o1.lastHandler) == 'on4'

        c.stop()
示例#3
0
	def runTest( self ):

		context = Context( 'context' )
		context.start()

		listener = TestListener()
		listener.context = context

		node = System( 'system0', listener )
		node.addListener( listener )

		assert( node.currentState == 'Stopped' )

		node.process( Event( 'Start' ) )
		assert( node.currentState == 'Started' )

		sleep( 2 )

		node.process( Event( 'Pause' ) )
		assert( node.currentState == 'Paused' )

		node.process( Event( 'Continue' ) )
		assert( node.currentState == 'Started' )

		node.process( Event( 'Stop' ) )
		assert( node.currentState == 'Stopped' )
示例#4
0
def genBitfieldContexts(enums, bitfGroups):
    bitfieldEnums = [enum for enum in enums if enum.type == "GLbitfield"]
    maxLength = max([len(enumBID(enum)) for enum in bitfieldEnums])

    noneIdentifier = "GL_NONE_BIT"
    noneValue = "0x0"
    noneGroups = Context.listContext([g.name for g in bitfGroups], sortKey = lambda g: g)

    bitfieldContexts = []
    bitfieldContexts.append({"identifier": noneIdentifier,
                             "name": noneIdentifier,
                             "value": noneValue,
                             "spaces": " " * (maxLength - len(noneIdentifier)),
                             "generic": True,
                             "groups": noneGroups,
                             "primaryGroup": noneGroups["items"][0]["item"] if not noneGroups["empty"] else None,
                             "supported": (lambda feature, core, ext: True) })
    for enum in bitfieldEnums:
        groups = Context.listContext([g.name for g in enum.groups], sortKey = lambda g: g)
        bitfieldContexts.append({"identifier": enumBID(enum),
                                 "name": enum.name,
                                 "value": enum.value,
                                 "spaces": " " * (maxLength - len(enumBID(enum))),
                                 "generic": False,
                                 "groups": groups,
                                 "primaryGroup": groups["items"][0]["item"] if not groups["empty"] else None,
                                 "supported": supportedLambda(enum) })
    return bitfieldContexts
示例#5
0
    def run_keyword(self, name, args, kwargs):
        """
        RF Dynamic API hook implementation that maps method names to their actual functions.

        :param name: The keyword name from robot
        :type name: str
        :param args: the args from robot
        :type args: list
        :param kwargs: a dict of additional args
        :type kwargs: dict
        :return: callable function
        :rtype: callable
        """
        # Translate back from Robot Framework name to actual method
        ret = None

        func_mapping = KeywordManager().get_meth_mapping_from_robot_alias(self, name)
        meth = func_mapping.func
        try:
            if "${" in func_mapping.func_alias:
                args = self._parse_embedded_args(name, func_mapping.func_alias)
            ret = meth(self, *args, **kwargs)
        except Exception, e:
            Context.set_current_page("automationpages.Page")
            # Pass up the stack, so we see complete stack trace in Robot trace logs
            BuiltIn().fail(str(e))
示例#6
0
 def __init__(self, parent, frame_num=0):
     Context.__init__(self)
     self._parent = parent
     self._arguments = collections.OrderedDict()
     self._parent_parser = parent._parent_parser
     self._context = parent._context
     self._frame_num = frame_num
示例#7
0
文件: tests.py 项目: phonkee/vcontext
    def test_expand(self):
        """
        Test expand functionality
        :return:
        """

        data = [
            (
                {'range_value': {'__range__': [2]},},
                [{'range_value': 0}, {'range_value': 1}]
            ),
            (
                {'range_value': {'__range__': [1], '__format__': 'value_{value}'},},
                [{'range_value': 'value_0'}]
            ),
            (
                {'range_value': {'__range__': [2], '__format__': 'value_{value}', '__exclude__': [0]}},
                [{'range_value': 'value_1'}]
            ),
            (
                {'choice_value': {'__choices__': ['a', 'b'], '__format__': 'value_{value}'}},
                [{'choice_value': 'value_a'}, {'choice_value': 'value_b'}]
            ),
        ]

        for item in data:
            inp, expected = item
            context = Context(inp)
            self.assertEqual(list(context.expand()), expected)
示例#8
0
 def __init__(self, argnames, expr=None):
     self.argnames = argnames
     self.expr = expr
     self.funcontext = None
     self.strict = True
     Context.__init__(self)
     self['$'] = self
示例#9
0
 def make_context(self):
     c = Context()
     for name, recordset in self._db.items():
         for r in recordset:
             if hasattr(r, 'fixity'):
                 c.bind_operator(name, r.graph, r.assoc, r.prec, r.fixity)
             else:
                 c.bind(name, r.graph)
     return c
示例#10
0
 async def listen(self):
   # Start listening for incoming request on tcp socket
   self._open()
   while True:
     req = self._read()
     if not req:
       break
     ctx = Context(req)
     # This should run middleware in parallel?
     for fn in self.middleware:
       await fn(ctx)
     self._send(ctx.to_HTTP())
示例#11
0
    def test(self):
        events = [Event('event0'), Event('event1'), Event('event2')]

        o = SampleObj(events)

        c = Context('context0')

        for event in events:
            future = c.queue(event, o, o)
        time.sleep(0.1)

        c.poll()
示例#12
0
def get(domain, function=False, **kwargs):
    """
    Get a single piece of data. function needs to be true if you want
    a callable.
    """

    return Context.get_skin(function=function).get(domain, **kwargs)
示例#13
0
    def on_clipboard_owner_change(self, clipboard, event):
        text = clipboard.wait_for_text() or ""

        if etc.DEBUG: print "Clipboard change", "###" + etc.reduce_text(text,40) + "###"

        # Ignore clipboard selections made by keyboard
        if text and self.keydetector.check_event() != KeyDetector.KEYBOARD:
            mouse_x, mouse_y = self.mouse_xy()

            # reads again the configuration file so it can be changed without restarting the program!
            self.check_config()

            self.ctx = Context(text, mouse_x, mouse_y)

            # I could call the ctx.complete method and create the menu when
            # the floating windows is clicked. But to make the application
            # more responsive, i make it now.
            # This is more important when the application is inactive for a long time.
            self.ctx.complete()

            # I have to define as a object variable, or it will loose scope and the menus will close after this method returns!
            self.menu = self.actions.actions_menu(self.ctx)

            if not self.timer:
                # start the timer that will be use to show and hide the floating
                self.timer = GObject.timeout_add(self.TIMER_INTERVAL, self.timer_func)

            # There are some applications that produce several clipboard events while
            # the user is grabbing the mouse to make the selection.
            # So we wait some time before showing the floating icon.
            # The show_me method will be called from the timer...
            self.delayed_to_show = True

        else:
            if etc.DEBUG: print "Ignored"
示例#14
0
文件: main.py 项目: pombredanne/rila
def run(fname):
    with open(fname, "r") as f:
        source_code = f.read()

    # Remove shebang line if it exists.
    if source_code[0:2] == "#!":
        source_code = "\n".join(source_code.split("\n")[1:])

    ctx = Context()
    parser.parse(lexer.lex(source_code)).compile(ctx)

    bytecode = ctx.create_bytecode()
    frame = Frame(bytecode)
    interpreter = Interpreter()

    interpreter.interpret(bytecode, frame)
示例#15
0
文件: look.py 项目: megawidget/ronin
    def __init__(self, cursor):
        self.cursor=cursor
        self._backup=[None]
        ctx=Context.getContext()

        look_handler=input_handling.InputHandler()
        for method in [getattr(self,m) for m in dir(self) if callable(getattr(self,m))]:
            try:
                for key in method.keys:
                    if isinstance(key, tuple):
                        look_handler.addFunction(method, key[0], key[1])
                    else:
                        look_handler.addFunction(method, key)
                    logger.debug("Bound "+str(method)+" to "+str(key))
            except AttributeError:
                pass
        ctx.screen_manager.current.handlers.push(look_handler)

        self.message_buffer=ctx.message_buffer
        self.perception=ctx.pc.perception
        self.loc=ctx.pc.parent.loc
        self.original_loc=ctx.pc.parent.loc
        self.previous_loc=ctx.pc.parent.loc
        self.worldview=ctx.worldview
        (self.width,self.height)=(self.worldview.width-1,self.worldview.height-1)
        self.screen_manager=ctx.screen_manager
        self.ctx=ctx
        self.monster_index=-1
        self.len_monsters_keys=len(self.perception.monsters_keys)
    def __init__(self):
        self.in_robot = Context.in_robot()
        self.formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
        self.threshold_level_as_str = self.get_threshold_level_as_str()
        self.threshold_level_as_int = self.get_log_level_from_str(self.threshold_level_as_str)

        if self.in_robot:
            self.logger = robot.api.logger
        else:

            # Stream handler is attached from log() since
            # that must be decided at run-time, but here we might as well
            # do the setup to keep log() clean.
            self.stream_handler = logging.StreamHandler(sys.stdout)
            self.stream_handler.setFormatter(self.formatter)

            # We have to instantiate a logger to something and this is a global
            # logger so we name it by this class. Later in this class'
            # log method, we manipulate the msg string to include the calling
            # page class name.
            logger = logging.getLogger(self.__class__.__name__)
            logger.setLevel(self.threshold_level_as_int)
            fh = logging.FileHandler("po_log.txt", "w")
            fh.setLevel(self.threshold_level_as_int)
            fh.setFormatter(self.formatter)
            logger.addHandler(fh)
            self.logger = logger
示例#17
0
    def __init__(self, resource, name, parent_node):
        """Constructor.

        :param resource: The label resource
        :type resource: :class:`loaders.Resource`

        :param name: The player name
        :type name: :class:`str`

        :param parent_node: The parent node
        :type parent_node: :class:`renderer.SceneNode`
        """
        context = Context.get_instance()

        self.font = Font(resource['font'], 14)
        self.shader = resource['font_shader']
        self.color = Vec(0.7, 0.7, 0.7, 0)

        self.node = parent_node.add_child(TextNode(
            self.font,
            self.shader,
            name,
            self.color))

        self.ratio = context.ratio
        text_w = self.node.width
        self.translation = Vec(-text_w * context.ratio * 0.5, 3.5, 0)
        self.scale = Vec(context.ratio, context.ratio, context.ratio)

        t = self.node.transform
        t.translate(self.translation)
        t.rotate(Vec(1, 0, 0), math.pi / 2)
        t.scale(self.scale)
示例#18
0
    def wrap(*args, **kwargs):
        # Convert all positional arguments to kwargs
        argdic = dict(zip(fn.__code__.co_varnames, args))
        kw = (Context.get_skin(function=False).get(DEFAULTS_DOMAIN) or {}).copy()
        kw.update(kwargs)
        kw.update(argdic)

        return fn(**kw)
示例#19
0
 def __init__(self, manager=FileManager, context={}, config={},
              compress=False, debug=False, optimize=False):
     self.context = Context(true=True, false=False)
     self.context.update(context)
     self.config = config
     self.manager = manager() if callable(manager) else manager
     self.compress = compress
     self.builder = Builder(debug, optimize)
示例#20
0
 def __init__(self):
     self.history = FileHistory(history_file)
     self.context = Context({
         u'help': self.help,
         u'exit': self.exit,
         u'save': self.save,
         u'load': self.load_default,
     })
示例#21
0
def parse(filename):
    if filename is None:
        configdir = os.environ.get("XDG_CONFIG_HOME", os.path.expanduser("~/.config/"))
        filename = os.path.join(configdir, "shackleton", "config.json")

    if not os.path.exists(filename):
        raise IOError("File %s not found" % filename)

    result = {}

    for (context_name, context_data) in simplejson.load(open(filename)).iteritems():
        context = Context(context_name)
        result[context_name] = context

        for data in context_data["rules"]:
            rule_name = data.pop("source")
            context.addRule(Rule(rule_name, **__stringise(data)))

        for data in context_data.get("enter", []):
            action_name = data.pop("action")
            cls = getattr(actions, action_name, None)
            if cls:
                action = cls(**__stringise(data))
                context.addEnterAction(action)

        for data in context_data.get("leave", []):
            action_name = data.pop("action")
            cls = getattr(actions, action_name, None)
            if cls:
                action = cls(**__stringise(data))
                context.addLeaveAction(action)

    return result
 def _populate_opts(self):
     """
     Pulls environment from PO_ environment file
     """
     self._opts.update(self._get_opts_from_var_file())
     self._opts.update(self._get_opts_from_env_vars())
     if Context.in_robot():
         self._opts.update(self._get_opts_from_robot())
     self._update_opts_from_inherited_classes()
示例#23
0
	def runTest( self ):

		context = Context( 'context' )
		context.start()

		listener = TestListener()
		listener.context = context

		node = System( 'system0', listener )
		node.addListener( listener )

		node.process( Event( 'Start' ) )

		s = 'SUBSCRIBE sip:chloe@cave;treats SIP/2.0\r\nTo: "Matt"<sip:matthew@cave>\r\nFrom: "Josh"<sip:joshua@cave>\r\nContact: "RileyMan"<sip:riley@cave>\r\nCall-ID: 12345\r\nCSeq: 16 SUBSCRIBE\r\n\r\n'
		m = Message( s )
		e = MessageEvent( MessageEvent.EVENT_RX, message=m, transport='udp', localAddress=node.query( 'network.localAddress' ), localPort=node.query( 'network.localPort' ), remoteAddress=node.query( 'network.remoteAddress' ), remotePort=node.query( 'network.remotePort' ) )
		context.queue( e, node )
		sleep( 2 )
示例#24
0
def get_fn(name, domain=None, **kw):
    """
    Access functions in a domain.
    """

    d = Context.get_skin(function=True)[domain or name]
    try:
        return d[name]
    except TypeError:
        return d
示例#25
0
 def __init__(self, files_list, root_path = None):
     if (root_path == None):
         root_path = path.abspath(path.join(
                     path.abspath(path.dirname(
                     path.abspath(inspect.getfile(
                         inspect.currentframe())))), ".."))
     self.logger = Logger(root_path)
     self.settings = Settings(root_path)
     self.context = Context(self.settings)
     for filepath in files_list:
         self.context.load_path(filepath)
示例#26
0
    def test(self):
        d = Dispatcher()

        c = Context('Root')
        c.start()

        o = self.SampleObj()
        d.add(obj=o, parent_obj=None, context=c)

        o.Start()
        assert str(o.state.current_state) == o.STATE_STARTED
        assert str(o.last_handler) == 'inStarted_onEnter'
        o.Pause()
        assert str(o.state.current_state) == 'Paused'
        assert str(o.last_handler) == 'inPaused_onEnter'
        o.Stop()
        assert str(o.state.current_state) == 'Stopped'
        assert str(o.last_handler) == 'inStopped_onEnter'

        c.stop()
示例#27
0
    def test_run(self):
        instructions = [Mov(AX, '2'), Mov(AX, '4')]
        context = Context(instructions)
        context.run()

        self.assertEqual(context.registers.get(AX).value, 0)
        context.step()
        self.assertEqual(context.registers.get(AX).value, 2)
        context.step()
        self.assertEqual(context.registers.get(AX).value, 4)
示例#28
0
def genExtensionContexts(extensions):
    extensionContexts = []
    for extension in extensions:
        commandContexts = Context.listContext([{"identifier": functionBID(c), "name": c.name} for c in extension.reqCommands],
                                              sortKey = lambda c: c["identifier"])
        extensionContexts.append({"identifier": extensionBID(extension),
                                  "name": extension.name,
                                  "incore": extension.incore,
                                  "incoreMajor": extension.incore.major if extension.incore else None,
                                  "incoreMinor": extension.incore.minor if extension.incore else None,
                                  "reqCommands": commandContexts})
    return extensionContexts
示例#29
0
    def add_node(self, prev, gstate, do_hash=True):
        if do_hash:
            hash = gstate.compute_hash()
            if hash is not None:
                node = self.statespace.get_node_by_hash(hash)
                if node is not None:
                    return (node, False)
        else:
            hash = None
        uid = str(self.statespace.nodes_count)
        node = Node(uid, hash)
        logging.debug("New node %s", node.uid)

        if prev:
            node.prev = prev
        self.statespace.add_node(node)

        if self.debug_state == uid:
            context = Context(self, node, None)
            context.add_error_and_throw(errormsg.StateCaptured(context, uid=uid))
        return (node, True)
示例#30
0
文件: worker.py 项目: pborky/pywef
    def __call__(self, environ, start_response):

        if (self._controllers == None
                or len(self._controllers) == 0
                or self.mapper == None):
            raise NotInitializedProperly('Missing controller to execute.')
        else:

            context = Context(environ=environ, worker = self, match_callback = self.mapper.routematch,
                            generator_callback = URLGenerator(self.mapper, environ))
            try:
                context.match()
                if context.match_dict is None:
                    req = context.request.copy()
                    if req.path_info.endswith('/'):
                        req.path_info = req.path_info.rstrip('/')
                        route = context.matcher(environ=req.environ)
                    else:
                        req.path_info = req.path_info + '/'
                        route = context.matcher(environ=req.environ)
                    
                    if route is not None:
                        raise HTTPFound('Try add/remove trailing slash.', location = req.url)
                    else:
                        raise HTTPNotFound('Requested route %s cannot be matched.' % context.request.path_url)
            
            except RoutesException:
                raise HTTPNotFound('Requested route %s cannot be matched.' % context.request.path_url, exc_info = True)
            ctrl = self._controllers.get(context.match_dict.get('controller'))
            # TODO: test if callable and raise ControllerNotInitializedProperly respectively
            ctrl(context)

        return context.response(environ, start_response) # context.return_response()
    def log(self, msg, level="INFO", is_console=True):
        """
        Logs msg in Robot if possible but will also output to Console

        :param msg: The Message to output
        :type msg: str
        :param level: The level at which the message is displayed
        :type level: str
        :param is_console: If "True" then display to both console and robot
        :type is_console: bool
        """
        level_as_str, level_as_int = self.get_normalized_logging_levels(level)
        if Context.in_robot():
            self.logger.write(msg, level_as_str)
            if is_console:
                # Robot's logging only outputs to stdout if it's a warning, so allow
                # always logging to console, unless caller specifies not to.
                robot.api.logger.console("%s - %s" % (level, msg))
        else:
            if is_console:
                self.logger.addHandler(self.stream_handler)

            self.logger.log(level_as_int, msg)
    def visit(self, context: Context) -> LangType:
        var_name = self.var_name_token.value
        value = context.get(var_name)
        if not value:
            raise RTError(
                self.pos_start, self.pos_end, f'"{var_name}" is not defined', context,
            )

        if isinstance(value, LangVariantTypeDefinition):
            if len(value.args) == 0:
                return LangVariantType(
                    [], var_name, self.pos_start, self.pos_end, context
                )
            else:
                raise RTError(
                    self.pos_start,
                    self.pos_end,
                    f'"{var_name}" excepts more arguments',
                    context,
                )

        else:
            return value.copy().set_pos(self.pos_start, self.pos_end)
示例#33
0
def our_application_json(environ: Dict[str,
                                       Any], start_response: 'StartResponse',
                         ctx: context.Context, relations: areas.Relations,
                         request_uri: str) -> Iterable[bytes]:
    """Dispatches json requests based on their URIs."""
    content_type = "application/json"
    headers: List[Tuple[str, str]] = []
    prefix = ctx.get_ini().get_uri_prefix()
    if request_uri.startswith(prefix + "/streets/"):
        output = streets_update_result_json(ctx, relations, request_uri)
    elif request_uri.startswith(prefix + "/street-housenumbers/"):
        output = street_housenumbers_update_result_json(
            ctx, relations, request_uri)
    elif request_uri.startswith(prefix + "/missing-housenumbers/"):
        output = missing_housenumbers_update_result_json(
            ctx, relations, request_uri)
    else:
        # Assume that request_uri starts with prefix + "/missing-streets/".
        output = missing_streets_update_result_json(ctx, relations,
                                                    request_uri)
    output_bytes = output.encode("utf-8")
    response = webframe.Response(content_type, "200 OK", output_bytes, headers)
    return webframe.send_response(environ, start_response, response)
示例#34
0
def main():
    target = sys.argv[1]
    with open(target) as f:
        source = f.read()
    tree = ast.parse(source, target)

    ctx = Context()
    with open("libpyc.c") as f:
        ctx.body_write(f.read() + "\n")

    for builtin, fn in BUILTINS.items():
        ctx.register_global(builtin, fn)

    generate(ctx, tree)

    # Create and move to working directory
    outdir = "bin"
    shutil.rmtree(outdir, ignore_errors=True)
    os.mkdir(outdir)
    os.chdir(outdir)

    with open("main.c", "w") as f:
        f.write(ctx.body.content)

        main = ctx.namings.get("main")["name"]
        f.write(f"""int main(int argc, char *argv[]) {{
  Py_Initialize();

  // Initialize globals, if any.
{ctx.initializations.content}
  PyObject* r = {main}();
  return PyLong_AsLong(r);
}}""")

    subprocess.run(["clang-format", "-i", "main.c"])

    cflags_raw = subprocess.check_output(["python3-config", "--cflags"])
    cflags = [f.strip() for f in cflags_raw.decode().split(" ") if f.strip()]
    cmd = ["gcc", "-c", "-o", "main.o"] + cflags + ["main.c"]
    subprocess.run(cmd)

    ldflags_raw = subprocess.check_output(["python3-config", "--ldflags"])
    ldflags = [f.strip() for f in ldflags_raw.decode().split(" ") if f.strip()]
    cmd = ["gcc"] + ldflags + ["main.o"] + ["-lpython3.8"]
    subprocess.run(cmd)
示例#35
0
def handle_main_filters_refcounty(ctx: context.Context,
                                  relations: areas.Relations,
                                  refcounty_id: str,
                                  refcounty: str) -> yattag.doc.Doc:
    """Handles one refcounty in the filter part of the main wsgi page."""
    doc = yattag.doc.Doc()
    name = relations.refcounty_get_name(refcounty)
    if not name:
        return doc

    prefix = ctx.get_ini().get_uri_prefix()
    with doc.tag("a",
                 href=prefix + "/filter-for/refcounty/" + refcounty +
                 "/whole-county"):
        doc.text(name)
    if refcounty_id and refcounty == refcounty_id:
        refsettlement_ids = relations.refcounty_get_refsettlement_ids(
            refcounty_id)
        if refsettlement_ids:
            names: List[yattag.doc.Doc] = []
            for refsettlement_id in refsettlement_ids:
                name = relations.refsettlement_get_name(
                    refcounty_id, refsettlement_id)
                name_doc = yattag.doc.Doc()
                href_format = prefix + "/filter-for/refcounty/{}/refsettlement/{}"
                with name_doc.tag("a",
                                  href=href_format.format(
                                      refcounty, refsettlement_id)):
                    name_doc.text(name)
                names.append(name_doc)
            doc.text(" (")
            for index, item in enumerate(names):
                if index:
                    doc.text(", ")
                doc.asis(item.getvalue())
            doc.text(")")
    return doc
示例#36
0
def run(unknown_arguments=False):
    for file in [config.ticks_csv, config.network_csv, config.nodes_csv]:
        utils.check_for_file(file)

    parser = _create_parser()
    if unknown_arguments:
        args = parser.parse_known_args(sys.argv[2:])[0]
    else:
        args = parser.parse_args(sys.argv[2:])
    logging.info("Parsed arguments")
    utils.update_args(args)

    context = Context()

    logging.info(config.log_line_run_start + context.run_name)

    tag = context.args.tag
    if hasattr(context.args, 'tag_appendix'):
        tag += context.args.tag_appendix
    writer = Writer(tag)
    runner = Runner(context, writer)

    prepare = Prepare(context)
    runner._prepare = prepare

    postprocessing = PostProcessing(context, writer)
    runner._postprocessing = postprocessing

    event = Event(context)
    runner._event = event

    start = time.time()

    runner.run()

    logging.info("The duration of the run was {} minutes".format(
        str(time.time() - start)))
示例#37
0
def create_elf(file_name='source', ins=None):
    template = ''
    if not Context().is_arm():
        template += '.intel_syntax noprefix\n'
    template += """.global main
.global _start
.global __start

.text
_start:
__start:
main:
"""

    if ins is not None:
        template += '\t' + ins + '\n'
    else:
        template += '\t.skip 0x200, 0\n'

    assembly_file = file_name + '.as'
    object_file = file_name + '.o'
    binary_file = file_name

    assembler = 'as'
    linker = 'ld'

    with open(assembly_file, 'w') as source_file:
        source_file.write(template)

    try:
        rr("{} {} -o {}".format(assembler, assembly_file, object_file))
        rr("{} {} -o {}".format(linker, object_file, binary_file))
    except CalledProcessError as e:
        debug_print('Command failed with err: {}'.format(e))
        return None

    return file_name
def create_package_xml():
    if platform.system() == 'Windows':
        _context = Context(Windows())
    if platform.system() == 'Darwin':
        _context = Context(MacOS())
    wwa = WorkWithAutomation(_context)

    s_object_names = wwa.get_sobjects_name_from_pbs_and_workflows()

    document = etree.Element("Package")
    document.set("xmlns", "http://soap.sforce.com/2006/04/metadata")

    for s_object_name in s_object_names:
        types = etree.Element("types")
        document.append(types)

        members = etree.SubElement(types, "members")
        members.text = s_object_name

        name = etree.SubElement(types, "name")
        name.text = "CustomObject"

    version = etree.SubElement(document, "version")
    version.text = "48.0"

    etree.indent(document, space="    ")
    tree = etree.ElementTree(document)

    result = re.sub(
        r'\'',
        '\"',
        etree.tostring(tree.getroot(), encoding="UTF-8", xml_declaration=True, pretty_print=True).decode("utf-8")
    )
    if os.path.exists(_context.get_retrieve_sobjects_path()) is False:
        os.mkdir(_context.get_retrieve_sobjects_path())
    os.chdir(_context.get_retrieve_sobjects_path())

    with open("package.xml", "w") as package:
        package.write(result)
示例#39
0
def validate(ontology, case_data):
    '''
    Arguments:
        ontology   An Ontology object
        case_data  A CaseData object

    Return:
        List of ErrorMessage objects sorted by line number
    '''
    # Set the message context
    context = Context().populate(case_data.bindings)

    # Convert case_data triples to SPO dictionary {subject:{predicate:{objects}}}
    spo_dict = get_spo_dict(case_data.graph[::])

    # Call validate_case_data
    error_messages = validate_case_data(spo_dict, case_data.line_numbers,
                                        ontology.constraints,
                                        ontology.property_ranges,
                                        ontology.ancestor_classes, context)

    # Return error messages sorted by line number
    error_messages.sort(key=lambda x: x.line_number if x.line_number else 0)
    return error_messages
示例#40
0
    def fatigueMe(self):
        # First let's get the first bending frequency for the cantilever beam.
        context = Context(
            SquareBeam(self.w, self.ht, self.rho, self.E, self.wt, self.span))
        fn = context.strategy.fn

        # input PSD
        self.psdInput(fn)

        # Calculate the stress levels based on the gs and MC/I

        k = 3  # Stress concentration factor round hole

        # The sress given is max at base of beam the hole is a bit up from base see beam.pdf in ref directory.
        oneSigma = (self.spanToHole /
                    self.span) * context.strategy.maxStressCantileverPointMass(
                        self.gsRMS, k)
        print(
            "See table that will open up on your default browser.  This will show the 1,2, and 3 sigma stresses for {:.1f} hz, corresponding cycles and n/N"
            .format(fn))
        self.minersRuleApplication(oneSigma, fn)

        print("Max 1 Sigma Bending Stress at hole: ", float(round(oneSigma,
                                                                  3)))
示例#41
0
 def eval_ForLoopNode(self, node, context):
     result = EvaluateResult()
     # Evaluate initial and final values for the iterator and make
     # sure they are integers
     init_val = result.register(self.eval_node(node.init_expr,
                                               context))  # Value
     if result.error: return result
     if type(init_val.value).__name__ != "int":
         return result.failure(
             RunTimeError(init_val.start_pos, init_val.end_pos,
                          f"Exptecing int", context))
     final_val = result.register(self.eval_node(node.final_expr,
                                                context))  # Value
     if result.error: return result
     if type(final_val.value).__name__ != "int":
         return result.failure(
             RunTimeError(final_val.start_pos, final_val.end_pos,
                          f"Exptecing int", context))
     # Build new context for the loop scope and allow iterator to within bounds
     child_context = Context(context.display_name, Environment(context.env),
                             FunctionEnvironment(context.func_env), context,
                             node.start_pos)
     child_context.env.set(node.var_name.value, init_val)
     # Evaluate the expression iteratively
     loop_val = Value(None)
     while init_val.value < final_val.value:
         loop_val = result.register(self.eval(node.loop_expr,
                                              child_context))  # [Value]
         if result.error: return result
         # Makue sure to increment the iterator and update the new value
         # in the context.
         init_val, error = init_val.add_to(Value(1))
         if error: return result.failure(error)
         child_context.env.set(node.var_name.value, init_val)
     # return result.success(loop_val.set_pos(node.start_pos, node.end_pos))
     return result.success(Value(None))
示例#42
0
def main():

    numplayers = 0
    playerchars = []

    pygame.init()
    window = pygame.display.set_mode(WINDOW_SIZE)

    # DEBUG initialization context - move to seperate file later
    if DEBUG:
        numplayers = 2
        playerchars.append(('DiGiTALQU33F', 'test_guy_1'))
        playerchars.append(('iRONVAGiNA', 'test_guy_2'))

    game_context = Context(numplayers, playerchars)

    state = 'startup'

    # Main game loop
    while 1:
        for ev in pygame.event.get():
            if ev.type == pygame.QUIT:
                exit()
            if ev.type == pygame.KEYDOWN:
                if (ev.key == pygame.K_q):
                    exit()
                if (ev.key == pygame.K_DOWN):
                    pass
        if state == 'startup':
            display(window)
            state = 'generic'

        elif state == 'generic':
            pass

    raise Exception('Main loop dun goofed')  # Shouldn't reach this
示例#43
0
def genExtensionContexts(extensions):
    extensionContexts = []
    for extension in extensions:
        commandContexts = Context.listContext(
            [{
                "identifier": functionBID(c),
                "name": c.name
            } for c in extension.reqCommands],
            sortKey=lambda c: c["identifier"])
        extensionContexts.append({
            "identifier":
            extensionBID(extension),
            "name":
            extension.name,
            "incore":
            extension.incore,
            "incoreMajor":
            extension.incore.major if extension.incore else None,
            "incoreMinor":
            extension.incore.minor if extension.incore else None,
            "reqCommands":
            commandContexts
        })
    return extensionContexts
示例#44
0
    def test_processing(self):

        logging.debug('*** Processing test ***')

        mouth = Queue()
        mouth.put('hello')
        mouth.put('world')
        mouth.put(Exception('EOQ'))

        context = Context()
        context.set('spark.CISCO_SPARK_PLUMBERY_BOT', 'garbage')
        context.set('spark.room_id', 'fake')

        sender = Sender(mouth)
        #        sender.post_update = MagicMock()
        sender.work(context)

        with self.assertRaises(Exception):
            mouth.get_nowait()
示例#45
0
import datetime

from flask import Flask, redirect, request, render_template, send_from_directory, jsonify
from common.rabbit_controller import RabbitController
from api import API
from bus import Bus
from context import Context

rabbit = RabbitController('localhost', 5672, 'guest', 'guest', '/')
bus = Bus(rabbit)
api = API(bus)
context = Context(bus)

app = Flask(__name__)


@app.route('/', methods=['GET'])
def landing_page():
    ctx = context.fetch(request)

    if 'success' in request.args:
        ctx['alert_success'] = request.args['success']
    if 'error' in request.args:
        ctx['alert_error'] = request.args['error']

    return render_template('landing_page.html', **ctx)


@app.route('/static/<path:path>', methods=['GET'])
def send_static(path):
    """ Static serving for static directory """
示例#46
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "file",
        help=
        "File(s) or folder(s) you wanna run the parser on. If no file provided, runs on current folder.",
        default=[],
        action='append',
        nargs='*')
    parser.add_argument("-d",
                        "--debug",
                        action="count",
                        help="Debug output (multiple values available)",
                        default=0)
    parser.add_argument('-v',
                        '--version',
                        action='version',
                        version='norminette ' + str(__version__))
    #parser.add_argument('-s', '--sentry', action='store_true', default=False)
    parser.add_argument(
        '--cfile',
        action='store',
        help="Store C file content directly instead of filename")
    parser.add_argument(
        '--hfile',
        action='store',
        help="Store header file content directly instead of filename")
    args = parser.parse_args()
    registry = Registry()
    targets = []
    has_err = None
    content = None

    debug = args.debug
    #if args.sentry == True:
    #sentry_sdk.init("https://[email protected]/72")
    if args.cfile != None or args.hfile != None:
        targets = ['file.c'] if args.cfile else ['file.h']
        content = args.cfile if args.cfile else args.hfile
    else:
        args.file = args.file[0]
        if args.file == [[]] or args.file == []:
            targets = glob.glob("**/*.[ch]", recursive=True)
            target = targets.sort()
        else:
            for arg in args.file:
                if os.path.exists(arg) is False:
                    print(f"'{arg}' no such file or directory")
                elif os.path.isdir(arg):
                    if arg[-1] != '/':
                        arg = arg + '/'
                    targets.extend(glob.glob(arg + '**/*.[ch]',
                                             recursive=True))
                elif os.path.isfile(arg):
                    targets.append(arg)
    event = []
    for target in targets:
        if target[-2:] not in [".c", ".h"]:
            print(f"{arg} is not valid C or C header file")
        else:
            #with configure_scope() as scope:
            #    scope.set_extra("File", target)
            try:
                event.append(Event())
                #if args.sentry == True:
                #    proc = Thread(target=timeout, args=(event[-1], 5, ))
                #    proc.daemon = True
                #    proc.start()
                if content == None:
                    with open(target) as f:
                        #print ("Running on", target)
                        source = f.read()
                else:
                    source = content
                lexer = Lexer(source)
                tokens = lexer.get_tokens()
                context = Context(target, tokens, debug)
                registry.run(context, source)
                event[-1].set()
                if context.errors:
                    has_err = True
            # except (TokenError, CParsingError) as e:
            except TokenError as e:
                has_err = True
                print(target + f": KO!\n\t{colors(e.msg, 'red')}")
                event[-1].set()
            except CParsingError as e:
                has_err = True
                print(target + f": KO!\n\t{colors(e.msg, 'red')}")
                event[-1].set()
            except KeyboardInterrupt as e:
                event[-1].set()
                sys.exit(1)
    sys.exit(1 if has_err else 0)
示例#47
0
import discord
from discord.ext import commands
from discord.ext.commands import Cog
from discord.utils import get

from context import Context

context = Context()


class Administration(Cog):
    """Commands related to administration"""
    @commands.command(
        pass_context=True,
        brief="Seleccionar el prefijo para el servidor",
        description="Cambia el prefijo para el servidor permanentemente")
    async def set_prefix(self, ctx, prefix=""):
        context.new_guild_check(ctx.guild.id)

        if ctx.message.author.guild_permissions.administrator:
            context.guilds[ctx.guild.id].prefix = prefix
            context.save()
            await ctx.send("El prefix ahora es " +
                           context.guilds[ctx.guild.id].prefix)
            await ctx.message.add_reaction(context.guilds[ctx.guild.id].emoji)
        else:
            await ctx.send("Solo lo puede ocupar un administrador")
            await ctx.message.add_reaction(context.guilds[ctx.guild.id].emoji)

    @commands.command(
        pass_context=True,
示例#48
0
 def __init__(self, tags, name, steps):
     self.tags = tags
     self.name = name
     self.steps = steps
     self.background = None
     self.scc = Context()
示例#49
0
            identifier = thing_visor_ID + "/" + city + sens["id"]
            description = sens["description"]
            topic = v_thing_prefix + "/" + identifier
            v_things.append({
                "vThing": {
                    "label": label,
                    "id": identifier,
                    "description": description
                },
                "topic": v_thing_prefix + "/" + identifier,
                "type": sens["type"],
                "dataType": sens["dataType"],
                "city": city,
                "thing": thing
            })
            contexts[identifier] = Context()

    MQTT_data_broker_IP = os.environ["MQTTDataBrokerIP"]
    MQTT_data_broker_port = int(os.environ["MQTTDataBrokerPort"])
    MQTT_control_broker_IP = os.environ["MQTTControlBrokerIP"]
    MQTT_control_broker_port = int(os.environ["MQTTControlBrokerPort"])

    # Mongodb settings
    time.sleep(1.5)  # wait before query the system database
    db_name = "viriotDB"  # name of system database
    thing_visor_collection = "thingVisorC"
    db_IP = os.environ['systemDatabaseIP']  # IP address of system database
    db_port = os.environ['systemDatabasePort']  # port of system database
    db_client = MongoClient('mongodb://' + db_IP + ':' + str(db_port) + '/')
    db = db_client[db_name]
    port_mapping = db[thing_visor_collection].find_one(
示例#50
0
        trade_cal = pro.trade_cal()
        trade_cal.to_csv('trade_cal.csv')
        trade = False
    else:
        trade_cal = pd.read_csv('trade_cal.csv', index_col=0)
        # print(trade)
    return trade_cal

trade_cal = get_trade_cal()
# print(trade_cal)

'''
参照聚宽编写股票回测框架
'''

context = Context(CASH, START_DATE, END_DATE)

class G():
    pass

g = G()
 
def set_benchmark():   # 取某个指数作为基准
    context.benchmark = '000300'

# 获取历史数据
def attribute_history(security, count, fields=('open', 'close', 'high', 'vol')):
    '''
    security: 股票代码
    count: 从当日往前回测多少天
    fields: 股票行情数据列
示例#51
0
def image_builder(buildspec):
    FORMATTER = OutputFormatter(constants.PADDING)

    BUILDSPEC = Buildspec()
    BUILDSPEC.load(buildspec)
    IMAGES = []

    for image in BUILDSPEC["images"].items():
        ARTIFACTS = deepcopy(BUILDSPEC["context"])

        image_name = image[0]
        image_config = image[1]

        if image_config.get("version") is not None:
            if BUILDSPEC["version"] != image_config.get("version"):
                continue

        if image_config.get("context") is not None:
            ARTIFACTS.update(image_config["context"])

        build_context = os.getenv("BUILD_CONTEXT")
        image_tag = (tag_image_with_pr_number(image_config["tag"])
                     if build_context == "PR" else image_config["tag"])
        if not build_config.DISABLE_DATETIME_TAG or build_context != "PR":
            image_tag = tag_image_with_datetime(image_tag)
        image_repo_uri = (image_config["repository"] if build_context == "PR"
                          else modify_repository_name_for_context(
                              str(image_config["repository"]), build_context))
        base_image_uri = None
        if image_config.get("base_image_name") is not None:
            base_image_object = _find_image_object(
                IMAGES, image_config["base_image_name"])
            base_image_uri = base_image_object.ecr_url

        ARTIFACTS.update({
            "dockerfile": {
                "source": image_config["docker_file"],
                "target": "Dockerfile",
            }
        })

        context = Context(ARTIFACTS, f"build/{image_name}.tar.gz",
                          image_config["root"])
        """
        Override parameters from parent in child.
        """

        info = {
            "account_id": str(BUILDSPEC["account_id"]),
            "region": str(BUILDSPEC["region"]),
            "framework": str(BUILDSPEC["framework"]),
            "version": str(BUILDSPEC["version"]),
            "root": str(image_config["root"]),
            "name": str(image_name),
            "device_type": str(image_config["device_type"]),
            "python_version": str(image_config["python_version"]),
            "image_type": str(image_config["image_type"]),
            "image_size_baseline": int(image_config["image_size_baseline"]),
            "base_image_uri": base_image_uri
        }

        image_object = DockerImage(
            info=info,
            dockerfile=image_config["docker_file"],
            repository=image_repo_uri,
            tag=image_tag,
            to_build=image_config["build"],
            context=context,
        )

        IMAGES.append(image_object)

    FORMATTER.banner("DLC")
    FORMATTER.title("Status")

    THREADS = {}

    # In the context of the ThreadPoolExecutor each instance of image.build submitted
    # to it is executed concurrently in a separate thread.
    with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
        # Standard images must be built before example images
        # Example images will use standard images as base
        standard_images = [
            image for image in IMAGES if "example" not in image.name.lower()
        ]
        example_images = [
            image for image in IMAGES if "example" in image.name.lower()
        ]

        for image in standard_images:
            THREADS[image.name] = executor.submit(image.build)

        # the FORMATTER.progress(THREADS) function call also waits until all threads have completed
        FORMATTER.progress(THREADS)

        for image in example_images:
            THREADS[image.name] = executor.submit(image.build)

        # the FORMATTER.progress(THREADS) function call also waits until all threads have completed
        FORMATTER.progress(THREADS)

        FORMATTER.title("Build Logs")

        if not os.path.isdir("logs"):
            os.makedirs("logs")

        for image in IMAGES:
            FORMATTER.title(image.name)
            FORMATTER.table(image.info.items())
            FORMATTER.separator()
            FORMATTER.print_lines(image.log)
            with open(f"logs/{image.name}", "w") as fp:
                fp.write("/n".join(image.log))
                image.summary["log"] = f"logs/{image.name}"

        FORMATTER.title("Summary")

        for image in IMAGES:
            FORMATTER.title(image.name)
            FORMATTER.table(image.summary.items())

        FORMATTER.title("Errors")
        ANY_FAIL = False
        for image in IMAGES:
            if image.build_status == constants.FAIL:
                FORMATTER.title(image.name)
                FORMATTER.print_lines(image.log[-10:])
                ANY_FAIL = True
        if ANY_FAIL:
            raise Exception("Build failed")
        else:
            FORMATTER.print("No errors")

        FORMATTER.title("Uploading Metrics")
        metrics = Metrics(
            context=constants.BUILD_CONTEXT,
            region=BUILDSPEC["region"],
            namespace=constants.METRICS_NAMESPACE,
        )
        for image in IMAGES:
            try:
                metrics.push_image_metrics(image)
            except Exception as e:
                if ANY_FAIL:
                    raise Exception(f"Build failed.{e}")
                else:
                    raise Exception(f"Build passed. {e}")

        FORMATTER.separator()

        # Set environment variables to be consumed by test jobs
        test_trigger_job = utils.get_codebuild_project_name()
        utils.set_test_env(
            IMAGES,
            BUILD_CONTEXT=os.getenv("BUILD_CONTEXT"),
            TEST_TRIGGER=test_trigger_job,
        )
示例#52
0
    def test_do_list(self):

        context = Context()
        inbox = Queue()
        mouth = Queue()
        shell = Shell(context, inbox, mouth)

        context.set('plumbery.fittings',
                    os.path.dirname(os.path.realpath(__file__)))

        shell.do_list()
        self.assertEqual(
            mouth.get(), {
                'markdown':
                'You can list templates in following categories:\n- category1\n- category2\n- category3_is_empty'
            })
        with self.assertRaises(Exception):
            mouth.get_nowait()
        with self.assertRaises(Exception):
            inbox.get_nowait()

        shell.do_list('')
        self.assertEqual(
            mouth.get(), {
                'markdown':
                'You can list templates in following categories:\n- category1\n- category2\n- category3_is_empty'
            })
        with self.assertRaises(Exception):
            mouth.get_nowait()
        with self.assertRaises(Exception):
            inbox.get_nowait()

        shell.do_list('*unknown*')
        self.assertEqual(
            mouth.get(),
            "No category has this name. Double-check with the list command.")
        with self.assertRaises(Exception):
            mouth.get_nowait()
        with self.assertRaises(Exception):
            inbox.get_nowait()

        shell.do_list('category1')
        self.assertEqual(
            mouth.get(), {
                'markdown':
                'You can use any of following templates:\n- category1/fittings1\n- category1/fittings2'
            })
        with self.assertRaises(Exception):
            mouth.get_nowait()
        with self.assertRaises(Exception):
            inbox.get_nowait()

        shell.do_list('category2')
        self.assertEqual(
            mouth.get(), {
                'markdown':
                'You can use any of following templates:\n- category2/fittings1\n- category2/fittings2'
            })
        with self.assertRaises(Exception):
            mouth.get_nowait()
        with self.assertRaises(Exception):
            inbox.get_nowait()

        shell.do_list('category3_is_empty')
        self.assertEqual(
            mouth.get(),
            "No template has been found in category 'category3_is_empty'")
        with self.assertRaises(Exception):
            mouth.get_nowait()
        with self.assertRaises(Exception):
            inbox.get_nowait()

        context.set('plumbery.fittings', './perfectly_unknown_path')
        shell.do_list()
        self.assertEqual(mouth.get(),
                         "Invalid path for fittings. Check configuration")
        with self.assertRaises(Exception):
            mouth.get_nowait()
        with self.assertRaises(Exception):
            inbox.get_nowait()
示例#53
0
    def test_do_use(self):

        context = Context()
        inbox = Queue()
        mouth = Queue()
        shell = Shell(context, inbox, mouth)

        self.assertEqual(context.get('plumbery.fittings'), None)
        context.set('plumbery.fittings',
                    os.path.dirname(os.path.realpath(__file__)))

        self.assertEqual(context.get('worker.template'), None)

        shell.do_use()
        self.assertEqual(context.get('worker.template'), None)
        self.assertEqual(
            mouth.get(),
            "Please indicate the category and the template that you want to use."
        )
        with self.assertRaises(Exception):
            mouth.get_nowait()
        with self.assertRaises(Exception):
            inbox.get_nowait()

        shell.do_use('category1')
        self.assertEqual(context.get('worker.template'), None)
        self.assertEqual(
            mouth.get(),
            "Please indicate the category and the template that you want to use."
        )
        with self.assertRaises(Exception):
            mouth.get_nowait()
        with self.assertRaises(Exception):
            inbox.get_nowait()

        shell.do_use('hello/world')
        self.assertEqual(context.get('worker.template'), None)
        self.assertEqual(
            mouth.get(),
            "No template has this name. Double-check with the list command.")
        with self.assertRaises(Exception):
            mouth.get_nowait()
        with self.assertRaises(Exception):
            inbox.get_nowait()

        shell.do_use('category1/fittings2')
        self.assertEqual(context.get('worker.template'), 'category1/fittings2')
        self.assertEqual(mouth.get(), "This is well-noted")
        with self.assertRaises(Exception):
            mouth.get_nowait()
        with self.assertRaises(Exception):
            inbox.get_nowait()

        context.set('plumbery.fittings', './perfectly_unknown_path')
        shell.do_use('category2/fittings1')
        self.assertEqual(context.get('worker.template'), 'category1/fittings2')
        self.assertEqual(mouth.get(),
                         "Invalid path for fittings. Check configuration")
        with self.assertRaises(Exception):
            mouth.get_nowait()
        with self.assertRaises(Exception):
            inbox.get_nowait()
示例#54
0
        self.COF = Context.CoF
        self.print_info()

    def get_volume(self):
        return self.x_width * self.y_width * self.z_width

    def get_weight(self):
        return self.get_volume() * self.DENSITY

    def get_force_required(self):
        return self.get_weight() / 1000 * GRAVITY * self.COF

    def print_info(self):
        print(self.id)
        print("\t Dimensions:", self.x_width, "cm x", self.y_width, "cm x",
              self.z_width, "cm")
        print("\t Volume:", self.get_volume(), "cm³")
        print("\t Density:", self.DENSITY, "g/cm²")
        print("\t Coefficient of Friction:", self.COF)
        print("\t Weight:", self.get_weight(), "g")
        print("\t Push force required:", self.get_force_required(), "N")


if __name__ == "__main__":
    Context.load()
    small_objective = Objective(6, 6, 6)
    medium_objective = Objective(12, 12, 12)
    large2_objective = Objective(12.7, 12.7, 12.7)
    Context.DENSITY = 0.5
    large_objective = Objective(12, 12, 12)
class CobotGuiMain(QWidget):
    """! CobotGuiMain class inherit QWidget.
    This class setup all graphics components difinit on your config file:
     - Setup default rules : Language, size, account, ...
     - Setup dashboard : load widgets on dashboard registered in section <dashboard>,
     - Setup launchers : load plugins on launchers registered in section <launcher>.
    """
    APP_MODE_RELEASE = 'release'
    APP_MODE_DEBUG   = 'debug'
    
    def __init__(self, splash):
        """! The constructor.
        @param config: Config file (*.xml).
        """
        QWidget.__init__(self)
        
        loadUi(R.layouts.mainwindow, self)
        self.setAttribute(Qt.WA_AcceptTouchEvents)
        
        self._splash = splash
        self.display_mode = ''
        # Default components size
        self._launcher_width = 100
        self._dashboard_height = 80
        
        # Plugin loaded by default on app boot.
        self._default_view = None
        # Link current plugin loaded on viewer
        self._current_view = None
        # Container for plugins group instance
        self._plugins_group_list = []
        
        self._context = Context(self)
        
        self._context.addViewManagerEventListner(self.onManageView)
        self._context.addUserConnectionEventListener(self.onUserChanged)
        self._context.addControlModeEventListener(self.onControlModeChanged)
        self._context.addLanguageEventListner(self.onTranslate)
        
        self._context.addEmergencyStopEventListner(self.onEmergencyStop)
        
        self.setupMinimumTools()
        
    def setupMinimumTools(self):
        
        self.control_mode_widget = ControlModeWidget(self._context)
        self.ctrl_layout.addWidget(self.control_mode_widget)
        
        self.user_account = UserAccountsWidget(self._context)
        self.user_account.onCreate(None)
        self.user_layout.addWidget(self.user_account)
        
        self.timestamp_widget = Timestamp(self._context)
        self.timestamp_widget.onCreate(None)
        self.user_layout.addWidget(self.timestamp_widget)
        
        self.translator_widget = TranslatorUi(self._context)
        self.user_layout.addWidget(self.translator_widget)
        
        self.diagnostic_widget = DiagnosticsWidget(self._context)
        self.user_layout.addWidget(self.diagnostic_widget)

        self.emergency_stop = EmergencyStopButton(self._context)
        self.interruption_layout.addWidget(self.emergency_stop)
        
        self.alarms_manager = AlarmManagerWidget(self._context)
        self.alarm_layout.addWidget(self.alarms_manager)
        
        #Display Airbus Group logo
        self.logo_label.setPixmap(R.getPixmapById('logo_airbus_group').scaled(
                           self.logo_label.width()-2,
                           self.logo_label.height()-2,
                           Qt.KeepAspectRatio,
                           Qt.SmoothTransformation))
        
    def setupUserConfig(self, config_xml):
        """! Parser xml configuration file.
        @param config_xml: airbus_cobot_gui configuration path.
        @type config_xml: string.
        """
        
        #Check path from configuration file
        if not os.path.isfile(config_xml):
            self._context.getLogger().critical('User config file "%s" not found !'%config_xml)
        
        #Open and parse xml file
        xconfig = ElementTree.parse(config_xml).getroot()
        
        app_mode = self.APP_MODE_RELEASE
        
        try:
            app_mode = xconfig.attrib['mode'].lower()
        except:
            pass
        
        lng = Context.DEFAULT_LNG
        
        try:
            lng = xconfig.find('translate').attrib['type'].lower()
        except:
            pass
            
        xwindow = xconfig.find('window')
        
        if xwindow is None:
            self._context.getLogger().critical('Cannot found "<window>" tag into config file !')
            return
        
        try:
            self.display_mode = xwindow.attrib['display-mode'].lower()
        except:
            self.display_mode = ""
        
        #Read node window
        for node in xwindow:
            
            if node.tag == 'default-size':
                
                try:
                    width = int(node.find('width').text)
                    height = int(node.find('height').text)
                    self.resize(width, height)
                except:
                    self.resize(1920, 1080)
                    
            elif node.tag == 'header':
                self.installHeader(node)
            elif node.tag == 'launcher':
                self.installLauncher(node)
            else:
                self.getContext().getLogger().warn('Invalid tag "%s" into user configuration !'%node.tag)
        
        self.getContext().switchLanguage(lng)
        
        if app_mode == self.APP_MODE_DEBUG:
            self.getContext().switchUser(User('Airbus Group', Privilege.EXPERT))
        else:
            # Load default user none -> open login dialog
            self.getContext().switchUser(User())
            login = LoginDialog(self, False)
            QTimer.singleShot(1000, login.show)
        
    def installHeader(self, xheader):
        """! Setup all widgets on dashbord registered on config file.
        @param tree: node dashbord.
        @type tree: ElementTree.
        """
        
        for node in xheader:
            
            if node.tag == 'dashboards':
                
                register_dir = node.attrib['src']
                register_dir = get_pkg_dir_from_prefix(register_dir)
                
                if not os.path.isfile(register_dir):
                    self._context.getLogger().critical('Dashboards register file "%s" not found !'%register_dir)
                    return
                
                dashboard_provider = DashboardProvider(self, register_dir)
                
                for child in node:
                    
                    if child.tag == 'dashboard':
                        
                        dashboard_name = child.attrib['name']
                        
                        #Update splash from display the current dashboard loading
                        self._splash.update(dashboard_name)
                        
                        try:
                            dashboard = dashboard_provider.getInstance(dashboard_name, child)
                            
                            self.dashboard_layout.addWidget(dashboard)
                            
                        except Exception as ex:
                            self._context.getLogger().err('Try to provide "%s" instance failed !\n%s'
                                                          %(dashboard_name, str(ex)))
                            continue
                        
    
    def installLauncher(self, xlaunchers):
        """! Setup plugins and launcher.
        @param xlaunchers: node launcher.
        @type xlaunchers: ElementTree.
        """
        
        default_plugin_name = ""
        default_plugin = None
        control_mode = ControlMode.MANUAL
        
        try:
            default_plugin_name = xlaunchers.attrib['default-view']
        except:
            pass
        
        try:
            control_mode = ControlMode.TOLEVEL[xlaunchers.attrib['default-mode'].lower()]
        except:
            self._context.getLogger().warn("Invalid 'default-mode' attribute into config file !")
            control_mode = ControlMode.MANUAL
        
        for node in xlaunchers:
            
            if node.tag == 'plugins':
                
                plugins_register_dir = node.attrib['src']
                plugins_register_dir = get_pkg_dir_from_prefix(plugins_register_dir)
                
                if not os.path.isfile(plugins_register_dir):
                    self._context.getLogger().critical('Plugins register file "%s" not found !'%plugins_register_dir)
                    return
                
                provider = PluginProvider(self, plugins_register_dir)
                
                for xplugin in node:
                    
                    if xplugin.tag == 'plugin':
                        
                        plugin_name = xplugin.attrib['name']
                        
                        self._splash.update(plugin_name)
                        
                        try:
                            plugin = provider.getInstance(plugin_name, xplugin)
                            plugin.tryToPause()
                            
                            if plugin_name == default_plugin_name:
                                default_plugin = plugin
                            
                            self.launcher_layout.addWidget(plugin.getLauncher())
                            
                        except Exception as ex:
                            self._context.getLogger().err('Try to provide "%s" instance failed !\n%s'
                                                          %(plugin_name, str(ex)))
                            continue
                        
                    elif xplugin.tag == 'group':
                        
                        plugins_group = PluginsGroup(self, xplugin)
                        
                        for xsubplugin in xplugin:
                            
                            plugin_name = xsubplugin.attrib['name']
                            self._splash.update(plugin_name)
                             
                            try:
                                
                                plugin = provider.getInstance(plugin_name, xsubplugin)
                                plugin.tryToPause()
                                
                                plugins_group.add(plugin.getLauncher())
                                
                                if plugin_name == default_plugin_name:
                                    default_plugin = plugin
                                 
                            except Exception as ex:
                                self._context.getLogger().err('Try to provide "%s" instance failed !\n%s'
                                                              %(plugin_name, str(ex)))
                                continue
                        
                        self.launcher_layout.addWidget(plugins_group)
        
        if default_plugin is not None:
            default_plugin.onRequestDisplayView()
        
        self.control_mode_widget.setDefaultMode(control_mode)
    
    def getContext(self):
        return self._context
        
    def getDisplayMode(self):
        return self.display_mode
    
    def onManageView(self, view):
        # Sets current plugin activity to pause
        if self._current_view is not None:
            self._current_view.tryToPause()
            
        # Sets new plugin activity to resume
        view.tryToResume()
        
        if self._current_view is not None:
            # Remove current plugin view
            self.viewer.takeWidget()
            
        # Sets new plugin view on viewer
        self.viewer.setWidget(view)
        
        self._current_view = view
    
    def onUserChanged(self, user):
        
        if self._current_view is not None:
            
            if user.getUserPrivilege() == Privilege.NONE:
            #{
                self.viewer.takeWidget()
            #}
            elif self._current_view.getLauncher().getAccessRights() > user.getUserPrivilege():
            #{
                self.viewer.takeWidget()
            #}
            else:
                pass
        else:
            pass
        
    def onControlModeChanged(self, mode):
        pass
    
    def onTranslate(self, lng):
        pass
        
    def onEmergencyStop(self, state):
        """! Called when emergency stop status changed.
        @param status: emergency stop status.
        @type status: bool.
        """
        
        if state == EmergencyStopState.LOCKED:
            self.dashboard_widget.setStyleSheet(R.values.styles.background_estop_locked)
            self.logo_label.setStyleSheet(R.values.styles.background_estop_locked)
        else:
            self.dashboard_widget.setStyleSheet(R.values.styles.background_estop_unlocked)
            self.logo_label.setStyleSheet(R.values.styles.background_estop_unlocked)
    
    def resizeEvent(self, event):
        """! Resize application.
        @param event: event object.
        @type event: QEvent.
        """
        pass
    
    def shutdown(self):
        """! This methode call shutdown from all airbus_cobot_gui instances.
        """
        self._context.requestShutdown()
示例#56
0
    def test_dynamic(self):

        logging.debug('*** Dynamic test ***')

        ears = Queue()

        ears.put({
              "id" : "1_lzY29zcGFyazovL3VzL01FU1NBR0UvOTJkYjNiZTAtNDNiZC0xMWU2LThhZTktZGQ1YjNkZmM1NjVk",
              "roomId" : "Y2lzY29zcGFyazovL3VzL1JPT00vYmJjZWIxYWQtNDNmMS0zYjU4LTkxNDctZjE0YmIwYzRkMTU0",
              "roomType" : "group",
              "toPersonId" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mMDZkNzFhNS0wODMzLTRmYTUtYTcyYS1jYzg5YjI1ZWVlMmX",
              "toPersonEmail" : "*****@*****.**",
              "text" : "PROJECT UPDATE - A new project plan has been published on Box: http://box.com/s/lf5vj. The PM for this project is Mike C. and the Engineering Manager is Jane W.",
              "markdown" : "**PROJECT UPDATE** A new project plan has been published [on Box](http://box.com/s/lf5vj). The PM for this project is <@personEmail:[email protected]> and the Engineering Manager is <@personEmail:[email protected]>.",
              "files" : [ "http://www.example.com/images/media.png" ],
              "personId" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mNWIzNjE4Ny1jOGRkLTQ3MjctOGIyZi1mOWM0NDdmMjkwNDY",
              "personEmail" : "*****@*****.**",
              "created" : "2015-10-18T14:26:16+00:00",
              "mentionedPeople" : [ "Y2lzY29zcGFyazovL3VzL1BFT1BMRS8yNDlmNzRkOS1kYjhhLTQzY2EtODk2Yi04NzllZDI0MGFjNTM", "Y2lzY29zcGFyazovL3VzL1BFT1BMRS83YWYyZjcyYy0xZDk1LTQxZjAtYTcxNi00MjlmZmNmYmM0ZDg" ]
            })

        ears.put({
              "id" : "2_2lzY29zcGFyazovL3VzL01FU1NBR0UvOTJkYjNiZTAtNDNiZC0xMWU2LThhZTktZGQ1YjNkZmM1NjVk",
              "roomId" : "Y2lzY29zcGFyazovL3VzL1JPT00vYmJjZWIxYWQtNDNmMS0zYjU4LTkxNDctZjE0YmIwYzRkMTU0",
              "roomType" : "group",
              "toPersonId" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mMDZkNzFhNS0wODMzLTRmYTUtYTcyYS1jYzg5YjI1ZWVlMmX",
              "toPersonEmail" : "*****@*****.**",
              "text" : "/plumby use containers/docker",
              "personId" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mNWIzNjE4Ny1jOGRkLTQ3MjctOGIyZi1mOWM0NDdmMjkwNDY",
              "personEmail" : "*****@*****.**",
              "created" : "2015-10-18T14:26:16+00:00",
              "mentionedPeople" : [ "Y2lzY29zcGFyazovL3VzL1BFT1BMRS8yNDlmNzRkOS1kYjhhLTQzY2EtODk2Yi04NzllZDI0MGFjNTM", "Y2lzY29zcGFyazovL3VzL1BFT1BMRS83YWYyZjcyYy0xZDk1LTQxZjAtYTcxNi00MjlmZmNmYmM0ZDg" ]
            })

        ears.put({
              "id" : "3_2lzY29zcGFyazovL3VzL01FU1NBR0UvOTJkYjNiZTAtNDNiZC0xMWU2LThhZTktZGQ1YjNkZmM1NjVk",
              "roomId" : "Y2lzY29zcGFyazovL3VzL1JPT00vYmJjZWIxYWQtNDNmMS0zYjU4LTkxNDctZjE0YmIwYzRkMTU0",
              "roomType" : "group",
              "toPersonId" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mMDZkNzFhNS0wODMzLTRmYTUtYTcyYS1jYzg5YjI1ZWVlMmX",
              "toPersonEmail" : "*****@*****.**",
              "text" : "/plumby deploy",
              "personId" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mNWIzNjE4Ny1jOGRkLTQ3MjctOGIyZi1mOWM0NDdmMjkwNDY",
              "personEmail" : "*****@*****.**",
              "created" : "2015-10-18T14:26:16+00:00",
              "mentionedPeople" : [ "Y2lzY29zcGFyazovL3VzL1BFT1BMRS8yNDlmNzRkOS1kYjhhLTQzY2EtODk2Yi04NzllZDI0MGFjNTM", "Y2lzY29zcGFyazovL3VzL1BFT1BMRS83YWYyZjcyYy0xZDk1LTQxZjAtYTcxNi00MjlmZmNmYmM0ZDg" ]
            })

        ears.put({
              "id" : "4_2lzY29zcGFyazovL3VzL01FU1NBR0UvOTJkYjNiZTAtNDNiZC0xMWU2LThhZTktZGQ1YjNkZmM1NjVk",
              "roomId" : "Y2lzY29zcGFyazovL3VzL1JPT00vYmJjZWIxYWQtNDNmMS0zYjU4LTkxNDctZjE0YmIwYzRkMTU0",
              "roomType" : "group",
              "toPersonId" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mMDZkNzFhNS0wODMzLTRmYTUtYTcyYS1jYzg5YjI1ZWVlMmX",
              "toPersonEmail" : "*****@*****.**",
              "text" : "PROJECT UPDATE - A new project plan has been published on Box: http://box.com/s/lf5vj. The PM for this project is Mike C. and the Engineering Manager is Jane W.",
              "markdown" : "**PROJECT UPDATE** A new project plan has been published [on Box](http://box.com/s/lf5vj). The PM for this project is <@personEmail:[email protected]> and the Engineering Manager is <@personEmail:[email protected]>.",
              "files" : [ "http://www.example.com/images/media.png" ],
              "personId" : "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mNWIzNjE4Ny1jOGRkLTQ3MjctOGIyZi1mOWM0NDdmMjkwNDY",
              "personEmail" : "*****@*****.**",
              "created" : "2015-10-18T14:26:16+00:00",
              "mentionedPeople" : [ "Y2lzY29zcGFyazovL3VzL1BFT1BMRS8yNDlmNzRkOS1kYjhhLTQzY2EtODk2Yi04NzllZDI0MGFjNTM", "Y2lzY29zcGFyazovL3VzL1BFT1BMRS83YWYyZjcyYy0xZDk1LTQxZjAtYTcxNi00MjlmZmNmYmM0ZDg" ]
            })

        ears.put(Exception('EOQ'))

        inbox = Queue()
        mouth = Queue()

        context = Context()
        shell = Shell(context, inbox, mouth)
        listener = Listener(ears, shell)

        listener.work(context)

        self.assertEqual(context.get('listener.counter'), 4)
        with self.assertRaises(Exception):
            ears.get_nowait()
        self.assertEqual(inbox.get(), ('deploy', ''))
        with self.assertRaises(Exception):
            inbox.get_nowait()
        self.assertEqual(mouth.get(), "No template has this name. Double-check with the list command.")
        self.assertEqual(mouth.get(), "Ok, working on it")
        with self.assertRaises(Exception):
            mouth.get_nowait()
示例#57
0
# Show interpolations being made while moving the points.

# Imports
from interpolation import PolynomialInterpolation
from curves import Trajectory
from context import Context
from abstract import Point
import mycolors
import random

context = Context()
l = 10
points = [Point(2 * x, random.randint(-5, 5)) for x in range(l)]
n = 0
ncp = 200  # number construction points

while context.open:
    context.check()
    context.control()
    context.clear()
    context.show()

    n = (n + 1) % (ncp + 1)
    Point.turnPoints([1 / 1000 for i in range(l)], points)

    pi1 = PolynomialInterpolation(points)
    pi2 = PolynomialInterpolation(points)
    # pi2.createPolynomialsRespectingDistance()
    ti = Trajectory(points)
    p1 = Point(*pi1(n / ncp))
    p2 = Point(*pi2(n / ncp))
示例#58
0
    control_in_suffix = "c_in"
    control_out_suffix = "c_out"
    v_silo_prefix = "vSilo"
    v_thing_topic = v_thing_prefix + "/" + v_thing_ID

    port_mapping = db[thing_visor_collection].find_one(
        {"thingVisorID": thing_visor_ID}, {
            "port": 1,
            "_id": 0
        })
    print("port mapping: " + str(port_mapping) + "\n")

    # Instantiation of the Context object
    # Context object is a "map" of current virtual thing state, i.e. set of NGSI-LD properties
    commands = []
    LampActuatorContext = Context()

    # contexts is a map of Context, one per virtual things handled by the Thing Visor
    contexts = {v_thing_ID: LampActuatorContext}

    # JSON schemas for JSON validation TODO
    # with open('commandRequestSchema.json', 'r') as f:
    #    schema_data = f.read()
    # commandRequestSchema = json.loads(schema_data)

    # Finally run threads for control and data

    mqtt_control_client = mqtt.Client()
    mqtt_data_client = mqtt.Client()

    # threadPoolExecutor of size one to handle one command at a time in a fifo order
示例#59
0
    v_thing = {
        "label": v_thing_label,
        "id": v_thing_ID,
        "description": v_thing_description
    }

    MQTT_data_broker_IP = os.environ["MQTTDataBrokerIP"]
    MQTT_data_broker_port = int(os.environ["MQTTDataBrokerPort"])
    MQTT_control_broker_IP = os.environ["MQTTControlBrokerIP"]
    MQTT_control_broker_port = int(os.environ["MQTTControlBrokerPort"])

    sub_rn = v_thing_ID.replace("/", ":") + "_subF4I"
    vtype = ""

    # Context is a "map" of current virtual thing state
    context_vThing = Context()
    # mapping of virtual thing with its context object. Useful in case of multiple virtual things
    contexts = {v_thing_ID: context_vThing}

    # Mqtt settings
    tv_control_prefix = "TV"  # prefix name for controller communication topic
    v_thing_prefix = "vThing"  # prefix name for virtual Thing data and control topics
    v_thing_data_suffix = "data_out"
    in_control_suffix = "c_in"
    out_control_suffix = "c_out"
    v_silo_prefix = "vSilo"

    # Mongodb settings
    time.sleep(1.5)  # wait before query the system database
    db_name = "viriotDB"  # name of system database
    thing_visor_collection = "thingVisorC"
示例#60
0
from context import Context
from concrete_state_a import ConcreteStateA
from concrete_state_b import ConcreteStateB

if __name__ == "__main__":
    context = Context()
    csA = ConcreteStateA()
    csB = ConcreteStateB()
    context.request(csA)
    context.request(csB)