Open a ControlWebSocket to SushiBar server and listend for remote commands.
        Args:
            args (dict): chef command line arguments
            options (dict): additional compatibility mode options given on command line
505271
def daemon_mode(self, args, options):
        
        cws = ControlWebSocket(self, args, options)
        cws.start()
        if 'cmdsock' in args and args['cmdsock']:
            lcs = LocalControlSocket(self, args, options)
            lcs.start()
            lcs.join()
        cws.join()
884449
def cmd(send, msg, args):
    
    parser = arguments.ArgParser(args['config'])
    parser.add_argument('--chan', '--channel', action=arguments.ChanParser)
    try:
        cmdargs, extra = parser.parse_known_args(msg)
    except arguments.ArgumentException as e:
        send(str(e))
        return
    target = cmdargs.channels[0] if hasattr(cmdargs, 'channels') else args['target']
    mode = " ".join(extra)
    if not mode:
        send('Please specify a mode.')
    elif target == 'private':
        send("Modes don't work in a PM!")
    else:
        with args['handler'].data_lock:
            if target not in args['handler'].channels:
                send("Bot not in channel %s" % target)
            elif args['botnick'] not in args['handler'].opers[target]:
                send("Bot must be opped in channel %s" % target)
            else:
                args['handler'].connection.mode(target, mode)
                if args['target'] != args['config']['core']['ctrlchan']:
                    send("Mode \"%s\" on %s by %s" % (mode, target, args['nick']), target=args['config']['core']['ctrlchan'])
960523
def cmd(send, msg, args):
    

    parser = arguments.ArgParser(args['config'])
    parser.set_defaults(session=args['db'])
    subparser = parser.add_subparsers()
    start_parser = subparser.add_parser('start')
    start_parser.set_defaults(func=create_stopwatch)
    stop_parser = subparser.add_parser('stop')
    stop_parser.add_argument('id', type=int)
    stop_parser.set_defaults(func=stop_stopwatch)
    resume_parser = subparser.add_parser('resume')
    resume_parser.add_argument('id', type=int)
    resume_parser.set_defaults(func=resume_stopwatch)
    delete_parser = subparser.add_parser('delete')
    delete_parser.add_argument('id', type=int)
    delete_parser.set_defaults(func=delete_stopwatch, isadmin=args['is_admin'](args['nick']))
    get_parser = subparser.add_parser('get')
    get_parser.add_argument('id', type=int)
    get_parser.set_defaults(func=get_stopwatch)
    list_parser = subparser.add_parser('list')
    list_parser.set_defaults(func=list_stopwatch, nick=args['nick'], send=send)

    if not msg:
        send("Please specify a command.")
        return

    try:
        cmdargs = parser.parse_args(msg)
    except arguments.ArgumentException as e:
        send(str(e))
        return

    send(cmdargs.func(cmdargs))
570016
def webui(cmd, hostport='127.0.0.1:8800', skip_browser=False):
    
    dbpath = os.path.realpath(os.path.expanduser(config.dbserver.file))
    if os.path.isfile(dbpath) and not os.access(dbpath, os.W_OK):
        sys.exit('This command must be run by the proper user: '
                 'see the documentation for details')
    if cmd == 'start':
        dbserver.ensure_on()  # start the dbserver in a subprocess
        rundjango('runserver', hostport, skip_browser)
    elif cmd in commands:
        rundjango(cmd)
852888
def cmd_serve(self, *args):
        '''
        '''
        try:
            from http.server import SimpleHTTPRequestHandler
            from socketserver import TCPServer
        except ImportError:
            from SimpleHTTPServer import SimpleHTTPRequestHandler
            from SocketServer import TCPServer

        os.chdir(self.bin_dir)
        handler = SimpleHTTPRequestHandler
        httpd = TCPServer(("", SIMPLE_HTTP_SERVER_PORT), handler)
        print("Serving via HTTP at port {}".format(SIMPLE_HTTP_SERVER_PORT))
        print("Press Ctrl+c to quit serving.")
        httpd.serve_forever()
610195
def cmd(send, msg, args):
    
    parser = arguments.ArgParser(args['config'])
    parser.add_argument('speaker', nargs='?', default=args['config']['core']['channel'])
    parser.add_argument('--length', type=int, choices=[1, 2], default=2)
    parser.add_argument('--start', nargs='*')
    try:
        cmdargs = parser.parse_args(msg)
    except arguments.ArgumentException as e:
        send(str(e))
        return
    if args['db'].query(Babble).count():
        send(build_msg(args['db'], cmdargs.speaker, cmdargs.length, cmdargs.start))
    else:
        send("Please run ./scripts/gen_babble.py to initialize the babble cache")
13312
def _use_ssh_config(self, dict_arg):
        
        connect_dict = dict_arg.copy()

        # Use SSHConfig to generate source content.
        full_path = path.abspath(path.expanduser(self.ssh_config_file))
        if path.exists(full_path):
            ssh_config_instance = paramiko.SSHConfig()
            with io.open(full_path, "rt", encoding="utf-8") as f:
                ssh_config_instance.parse(f)
                source = ssh_config_instance.lookup(self.host)
        else:
            source = {}

        if "proxycommand" in source:
            proxy = paramiko.ProxyCommand(source["proxycommand"])
        elif "ProxyCommand" in source:
            proxy = paramiko.ProxyCommand(source["ProxyCommand"])
        else:
            proxy = None

        # Only update 'hostname', 'sock', 'port', and 'username'
        # For 'port' and 'username' only update if using object defaults
        if connect_dict["port"] == 22:
            connect_dict["port"] = int(source.get("port", self.port))
        if connect_dict["username"] == "":
            connect_dict["username"] = source.get("user", self.username)
        if proxy:
            connect_dict["sock"] = proxy
        connect_dict["hostname"] = source.get("hostname", self.host)

        return connect_dict
558040
def run(argv = ARGV)
      # => Parse CLI Configuration
      cli = Options.new
      cli.parse_options(argv)

      # => Grab the Default Values
      default = Config.options

      # => Parse JSON Config File (If Specified and Exists)
      json_config = Util.parse_json_config(cli.config[:config_file] || Config.config_file)

      # => Merge Configuration (CLI Wins)
      config = [default, json_config, cli.config].compact.reduce(:merge)

      # => Apply Configuration
      Config.setup do |cfg|
        cfg.config_file         = config[:config_file]
        cfg.cache_timeout       = config[:cache_timeout].to_i
        cfg.bind                = config[:bind]
        cfg.port                = config[:port]
        cfg.auth_file           = config[:auth_file]
        cfg.state_file          = config[:state_file]
        cfg.environment         = config[:environment].to_sym.downcase
        cfg.chef_api_endpoint   = config[:chef_api_endpoint]
        cfg.chef_api_client     = config[:chef_api_client]
        cfg.chef_api_client_key = config[:chef_api_client_key]
        cfg.chef_api_admin      = config[:chef_api_admin]
        cfg.chef_api_admin_key  = config[:chef_api_admin_key]
        cfg.rd_node_username    = config[:rd_node_username]
      end

      # => Launch the API
      API.run!
    end
461047
def serve(ip, port, application, ssl=None, processes=1, **kwargs):
    

    try:
        # use werkzeug if its there
        from werkzeug.serving import run_simple
        print("Using Werkzeug run_simple")
        run_simple(ip, port, application, ssl_context=ssl, processes=processes, **kwargs)
        return
    except ImportError:
        pass

    # otherwise just use python's built in wsgi webserver
    from wsgiref.simple_server import make_server
    server = make_server(ip, port, application)
    print("Serving on %s:%s, using built in Python server" % (ip, port))
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        pass
384554
def _args_for_remote(self):
        
        conf = self.config.get('terraform_remote_state')
        if conf is None:
            return None
        args = ['-backend=%s' % conf['backend']]
        for k, v in sorted(conf['config'].items()):
            args.append('-backend-config="%s=%s"' % (k, v))
        return args
120353
function SocketClient (socket) {
    var that = this;

    this.socket = socket;
    this.socket_closing = false;

    this.remoteAddress = this.socket.remoteAddress;
    winston.info('Control connection from %s opened', this.socket.remoteAddress);

    this.bindEvents();

    socket.write("\nHello, you are connected to the Kiwi server :)\n\n");

    this.control_interface = new ControlInterface(socket);
    _.each(socket_commands, function(fn, command_name) {
        that.control_interface.addCommand(command_name, fn.bind(that));
    });
}
179314
def cmd(send, msg, args):
    
    nick = args['nick']
    channel = args['target'] if args['target'] != 'private' else args['config']['core']['channel']
    levels = {
        1: 'Whirr...',
        2: 'Vrrm...',
        3: 'Zzzzhhhh...',
        4: 'SHFRRRRM...',
        5: 'GEEEEZZSH...',
        6: 'PLAAAAIIID...',
        7: 'KKKRRRAAKKKAAKRAKKGGARGHGIZZZZ...',
        8: 'Nuke',
        9: 'nneeeaaaooowwwwww..... BOOOOOSH BLAM KABOOM',
        10: 'ssh root@remote.tjhsst.edu rm -rf ~%s'
    }
    if not msg:
        send('What to microwave?')
        return
    match = re.match('(-?[0-9]*) (.*)', msg)
    if not match:
        send('Power level?')
    else:
        level = int(match.group(1))
        target = match.group(2)
        if level > 10:
            send('Aborting to prevent extinction of human race.')
            return
        if level < 1:
            send('Anti-matter not yet implemented.')
            return
        if level > 7:
            if not args['is_admin'](nick):
                send("I'm sorry. Nukes are a admin-only feature")
                return
            elif msg == args['botnick']:
                send("Sorry, Self-Nuking is disabled pending aquisition of a Lead-Lined Fridge.")
            else:
                with args['handler'].data_lock:
                    if target not in args['handler'].channels[channel].users():
                        send("I'm sorry. Anonymous Nuking is not allowed")
                        return

        msg = levels[1]
        for i in range(2, level + 1):
            if i < 8:
                msg += ' ' + levels[i]
        send(msg)
        if level >= 8:
            do_nuke(args['handler'].connection, nick, target, channel)
        if level >= 9:
            send(levels[9])
        if level == 10:
            send(levels[10] % target)
        send('Ding, your %s is ready.' % target)
1184505
async def open_websocket(url: str,
                         headers: Optional[list] = None,
                         subprotocols: Optional[list] = None):
    
    ws = await create_websocket(
        url, headers=headers, subprotocols=subprotocols)
    try:
        yield ws
    finally:
        await ws.close()
1320282
def __send_command(self, command, args=[]):
        ''''''
        self.ws.send(json.dumps({"op": command, "args": args}))
844857
function WebsocketRouter(options) {
  options = options || {};
  this.clientsPath = [];
  this.host = options.host ? options.host : 'localhost';
  this.port = options.port ? options.port : 8000;
}
806959
def run(options, http_req_handler = HttpReqHandler):
    
    # pylint: disable-msg=W0613
    global _HTTP_SERVER

    for x in ('server_version', 'sys_version'):
        if _OPTIONS.get(x) is not None:
            setattr(http_req_handler, x, _OPTIONS[x])

    _HTTP_SERVER = threading_tcp_server.KillableThreadingHTTPServer(
                       _OPTIONS,
                       (_OPTIONS['listen_addr'], _OPTIONS['listen_port']),
                       http_req_handler,
                       name = "httpdis")

    for name, cmd in _COMMANDS.iteritems():
        if cmd.at_start:
            LOG.info("at_start: %r", name)
            cmd.at_start(options)

    LOG.info("will now serve")
    while not _KILLED:
        try:
            _HTTP_SERVER.serve_until_killed()
        except (socket.error, select.error), why:
            if errno.EINTR == why[0]:
                LOG.debug("interrupted system call")
            elif errno.EBADF == why[0] and _KILLED:
                LOG.debug("server close")
            else:
                raise

    LOG.info("exiting")
592508
private Map<String, String> launchArgs(int port, String remoteVMOptions) {
        Map<String, String> argumentName2Value = new HashMap<>();
        argumentName2Value.put("main", remoteAgent + " " + port);
        argumentName2Value.put("options", remoteVMOptions);
        return argumentName2Value;
    }