Posts command event to main window

    Command events propagate.

    Parameters
    ----------
     * msg_cls: class
    \tMessage class from new_command_event()
     * kwargs: dict
    \tMessage arguments
436211
def post_command_event(target, msg_cls, **kwargs):
    

    msg = msg_cls(id=-1, **kwargs)
    wx.PostEvent(target, msg)
632032
def show(cls, msg=None):
        
        if msg:
            cls.add(msg)

        cls.overlay.show()
        cls.overlay.el.bind("click", lambda x: cls.hide())

        cls.el.style.display = "block"
        cls.bind()
651529
def _command(self, msg):
        """"""
        logger.debug('send command to %s', "ws://{}:{}".format(self.ip, self.port));
        try:
            websocket = yield from websockets.connect(
                "ws://{}:{}".format(self.ip, self.port), timeout=self.timeout_connect)
        except:
            logger.debug('command failed to connect to %s', "ws://{}:{}".format(self.ip, self.port));
            return False

        logger.debug('command websocket connected to %s', "ws://{}:{}".format(self.ip, self.port));

        try:
            yield from self._send_register_payload(websocket)

            if not self.client_key:
                raise PyLGTVPairException("Unable to pair")

            yield from websocket.send(json.dumps(msg))

            if msg['type'] == 'request':
                raw_response = yield from websocket.recv()
                self.last_response = json.loads(raw_response)

        finally:
            logger.debug('close command connection to %s', "ws://{}:{}".format(self.ip, self.port));
            yield from websocket.close()
1266989
def publish_event(self, channel, event, message):
        '''
        '''
        assert self.protocol is not None, "Protocol required"
        msg = {'event': event, 'channel': channel}
        if message:
            msg['data'] = message
        return self.publish(channel, msg)
501165
private void onMessageSent(MessageSentEvent event) {
        handler.post(() -> listener.onMessageSent(event));
        log("Event published " + event.toString());
    }
1215731
def log_event(event, logger=root_logger, **log_dict):
    
    msg = "event={}".format(event)
    msg = add_items_to_message(msg, log_dict)
    log_dict.update({'event': event})
    logger.info(msg, extra=log_dict)
75414
def process_message(message):
    
    message["type"] = message.pop("MsgType").lower()
    if message["type"] == 'event':
        message["type"] = str(message.pop("Event")).lower() + '_event'
        message_type = EventMetaClass.TYPES.get(message["type"], UnknownEvent)
    else:
        message_type = MessageMetaClass.TYPES.get(
            message["type"], UnknownMessage
        )
    return message_type(message)
919947
def announce(self, msg):
        
        self.print_if_verbose("{} -> {}".format(self.network_uid, msg.__class__.__name__))
        self.__trigger_event__(
            event_class=self.MessageAnnounced,
            msg=msg,
        )
47816
public static void postAction (
        Component source, String command, Object argument)
    {
        // slip things onto the event queue for later
        CommandEvent event = new CommandEvent(source, command, argument);
        EventQueue.invokeLater(new ActionInvoker(event));
    }
813572
def do(self, arg):
    ""
    print "This is an example command."
    print "%s.do(%r, %r):" % (__name__, self, arg)
    print "  last event", self.lastEvent
    print "  prefix", self.cmdprefix
    print "  arguments", self.split_tokens(arg)
75273
def execute(self, args):
        
        import colorama

        self.cli_ctx.raise_event(EVENT_INVOKER_PRE_CMD_TBL_CREATE, args=args)
        cmd_tbl = self.commands_loader.load_command_table(args)
        command = self._rudimentary_get_command(args)
        self.cli_ctx.invocation.data['command_string'] = command
        self.commands_loader.load_arguments(command)

        self.cli_ctx.raise_event(EVENT_INVOKER_POST_CMD_TBL_CREATE, cmd_tbl=cmd_tbl)
        self.parser.load_command_table(self.commands_loader)
        self.cli_ctx.raise_event(EVENT_INVOKER_CMD_TBL_LOADED, parser=self.parser)

        arg_check = [a for a in args if a not in ['--verbose', '--debug']]
        if not arg_check:
            self.cli_ctx.completion.enable_autocomplete(self.parser)
            subparser = self.parser.subparsers[tuple()]
            self.help.show_welcome(subparser)
            return CommandResultItem(None, exit_code=0)

        if args[0].lower() == 'help':
            args[0] = '--help'

        self.cli_ctx.completion.enable_autocomplete(self.parser)

        self.cli_ctx.raise_event(EVENT_INVOKER_PRE_PARSE_ARGS, args=args)
        parsed_args = self.parser.parse_args(args)
        self.cli_ctx.raise_event(EVENT_INVOKER_POST_PARSE_ARGS, command=parsed_args.command, args=parsed_args)

        self._validation(parsed_args)

        # save the command name (leaf in the tree)
        self.data['command'] = parsed_args.command
        cmd = parsed_args.func
        if hasattr(parsed_args, 'cmd'):
            parsed_args.cmd = cmd
        deprecations = getattr(parsed_args, '_argument_deprecations', [])
        if cmd.deprecate_info:
            deprecations.append(cmd.deprecate_info)

        params = self._filter_params(parsed_args)

        # search for implicit deprecation
        path_comps = cmd.name.split()[:-1]
        implicit_deprecate_info = None
        while path_comps and not implicit_deprecate_info:
            implicit_deprecate_info = resolve_deprecate_info(self.cli_ctx, ' '.join(path_comps))
            del path_comps[-1]

        if implicit_deprecate_info:
            deprecate_kwargs = implicit_deprecate_info.__dict__.copy()
            deprecate_kwargs['object_type'] = 'command'
            del deprecate_kwargs['_get_tag']
            del deprecate_kwargs['_get_message']
            deprecations.append(ImplicitDeprecated(**deprecate_kwargs))

        colorama.init()
        for d in deprecations:
            print(d.message, file=sys.stderr)
        colorama.deinit()

        cmd_result = parsed_args.func(params)
        cmd_result = todict(cmd_result)

        event_data = {'result': cmd_result}
        self.cli_ctx.raise_event(EVENT_INVOKER_TRANSFORM_RESULT, event_data=event_data)
        self.cli_ctx.raise_event(EVENT_INVOKER_FILTER_RESULT, event_data=event_data)

        return CommandResultItem(event_data['result'],
                                 exit_code=0,
                                 table_transformer=cmd_tbl[parsed_args.command].table_transformer,
                                 is_query_active=self.data['query_active'])
156421
def add_message_event(proto_message, span, message_event_type, message_id=1):
    
    span.add_time_event(
        time_event=time_event.TimeEvent(
            datetime.utcnow(),
            message_event=time_event.MessageEvent(
                message_id,
                type=message_event_type,
                uncompressed_size_bytes=proto_message.ByteSize()
            )
        )
    )
34875
def publish(self, subject, msg, reply=None):
        
        if msg is None:
            msg = ''

        if reply is None:
            command = 'PUB %s %d' % (subject, len(msg))
        else:
            command = 'PUB %s %s %d' % (subject, reply, len(msg))

        self._send(command)
        self._send(msg)
314641
def run(self):
        '''
        
        '''

        # Parse the stdin into a global event object
        stdin = self.read_stdin()
        self.event = self.read_event(stdin)

        # Prepare global settings
        self.settings = get_settings()
        self.api_settings = self.get_api_settings()

        # Prepare command line arguments and
        self.parser = argparse.ArgumentParser()

        # set up the 2.x to 1.x event mapping argument
        self.parser.add_argument("--map-v2-event-into-v1",
                                 action="store_true",
                                 default=False,
                                 dest="v2event")

        if hasattr(self, 'setup'):
            self.setup()
        (self.options, self.remain) = self.parser.parse_known_args()

        # map the event if required
        if (self.options.v2event or
                os.environ.get("SENSU_MAP_V2_EVENT_INTO_V1")):
            self.event = map_v2_event_into_v1(self.event)

        # Filter (deprecated) and handle
        self.filter()
        self.handle()
10542
def send_command():
    

    def verbose(msg):
        """
        print output if verbose is set.
        """
        if options.verbose:
            print(msg)

    options = command_parser()
    msg = json.dumps(vars(options)).encode("utf-8")
    if len(msg) > MAX_SIZE:
        verbose("Message length too long, max length (%s)" % MAX_SIZE)

    # find all likely socket addresses
    uds_list = glob.glob("{}.[0-9]*".format(SERVER_ADDRESS))

    verbose('message "%s"' % msg)
    for uds in uds_list:
        # Create a UDS socket
        sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)

        # Connect the socket to the port where the server is listening
        verbose("connecting to %s" % uds)
        try:
            sock.connect(uds)
        except socket.error:
            # this is a stale socket so delete it
            verbose("stale socket deleting")
            try:
                os.unlink(uds)
            except OSError:
                pass
            continue
        try:
            # Send data
            verbose("sending")
            sock.sendall(msg)
        finally:
            verbose("closing socket")
            sock.close()
1361896
def create_event(msg: EventMsgDict) -> Event:
    
    proto = msg.get('proto', '')
    cls = proto_dict.get(proto, Event)
    e = cls(msg['type'], msg)
    return e
997927
def func(command, description, link, params_string, returns="On success, the sent Message is returned.", return_type="Message"):
    
    description_with_tabs = "\t\t" + description.strip().replace("\n", "\n\t\t")
    param_list_args = []
    param_list_kwargs = []
    args = []
    args2 = []
    kwargs = []
    kwargs2 = []
    asserts = []
    str_args = ""
    str_kwargs = ""
    param_strings = params_string.split("\n")
    for param in param_strings:
        assert_commands, assert_comments, param_name, param_type, table, non_buildin_type, param_name_input = parse_param_types(param)
        param_required = table[2].strip()
        param_needed = None
        if param_required == "Yes":
            param_needed = True
        elif param_required == "Optional":
            param_needed = False
        param_description = table[3].strip()
        if param_needed:
            param_list_args.append(Param(param_name, param_type,param_needed, param_description))
            args.append(param_name)
            args2.append("{param_name}={param_name}".format(param_name=param_name))
            str_args += '\t\t:param {key}: {descr}\n\t\t:type  {key}: {type}\n\n'.format(key=param_name, descr=param_description, type=param_type)
            if assert_commands:
                asserts.append("assert({var} is not None)".format(var=param_name))
                asserts.append("assert({ass})".format(ass=" or ".join(assert_commands)) + (("  # {comment}".format(comment=", ".join(assert_comments))) if assert_comments else ""))
        else:
            param_list_kwargs.append(Param(param_name, param_type,param_needed, param_description))
            kwargs.append("{param_name}=None".format(param_name=param_name))
            kwargs2.append("{param_name}={param_name}".format(param_name=param_name))
            str_kwargs += '\t\t:keyword {key}: {descr}\n\t\t:type    {key}: {type}\n\n'.format(key=param_name, descr=param_description, type=param_type)
            if assert_commands:
                asserts.append("assert({var} is None or {ass})".format(var=param_name, ass=" or ".join(assert_commands)) + (("  # {comment}".format(comment=", ".join(assert_comments))) if assert_comments else ""))
    args.extend(kwargs)
    args2.extend(kwargs2)
    asserts_string = "\n\t\t" + "\n\t\t".join(asserts)
    text = ""
    if len(str_args)>0:
        text += '\n\t\tParameters:\n\n'
        text += str_args
    if len(str_kwargs)>0:
        text += '\n\t\tOptional keyword parameters:\n\n'
        text += str_kwargs
    do_args = ['"%s"' % command]
    do_args.extend(args2)
    result = '\tdef {funcname}(self, {params}):\n\t\t"""\n{description_with_tabs}\n\n\t\t{link}\n\n' \
           '{paramshit}\n' \
           '\t\tReturns:\n\n\t\t:return: {returns}\n\t\t:rtype:  {return_type}\n\t\t"""{asserts_with_tabs}\n\t\treturn self.do({do_args})\n\t# end def {funcname}'.format(
        funcname=convert_to_underscore(command),
        params=", ".join(args), description_with_tabs=description_with_tabs, link=link,
        returns=returns, return_type=return_type, command=command, do_args=", ".join(do_args),
        asserts_with_tabs=asserts_string,
        paramshit = text
    )
    result = result.replace("\t", "    ")
    return result