Create a signaling method based on command-line arguments.
494960
def create_signaling(args):
    
    if args.signaling == 'tcp-socket':
        return TcpSocketSignaling(args.signaling_host, args.signaling_port)
    elif args.signaling == 'unix-socket':
        return UnixSocketSignaling(args.signaling_path)
    else:
        return CopyAndPasteSignaling()
198361
def cli(ctx, pattern, arguments, safe):
    """"""

    matches = utils.grep_commands(pattern)
    if matches:
        selected = utils.select_command(matches)
        if selected >= 0:
            cmd, desc = matches[selected]
            pcmd = utils.create_pcmd(cmd)
            raw_params, params, defaults = utils.get_params_in_pcmd(pcmd)

            arguments = list(arguments)
            kargs = {}
            for r, p, d in zip(raw_params, params, defaults):
                if arguments:
                    val = arguments.pop(0)
                    click.echo("{}: {}".format(p, val))
                    kargs[r] = val
                elif safe:
                    if d:
                        kargs[r] = d
                else:
                    p_default = d if d else None
                    val = click.prompt("Enter value for '{}'".format(p), default=p_default)
                    kargs[r] = val
            click.echo("\n")

            final_cmd = utils.substitute_pcmd(pcmd, kargs, safe)

            command = "$ {} :: {}".format(final_cmd, desc)
            if click.confirm("Execute\n\t{}\n\n?".format(command), default=True):
                os.system(final_cmd)
    elif matches == []:
        click.echo('No saved commands matches the pattern {}'.format(pattern))
    else:
        click.echo("No commands to run, Add one by 'keep new'. ")
242893
def prog_callback(prog, msg):
    """"""
    pipe = Popen(prog, stdin=PIPE)
    data = json.dumps(msg)
    pipe.stdin.write(data.encode('utf-8'))
    pipe.stdin.close()
508339
def communicate(args):
  """"""
  if args.local:
    raise ValueError("The communicate command can only be used without the '--local' command line option")
  jm = setup(args)
  jm.communicate(job_ids=get_ids(args.job_ids))
837151
def output_callback(self, line, kill_switch):
        """"""
        self.notifications += line + "\n"

        if "Initialization Sequence Completed" in line:
            self.started = True
        if "ERROR:" in line or "Cannot resolve host address:" in line:
            self.error = True
        if "process exiting" in line:
            self.stopped = True
1188130
def command(self, *args, **kwargs):
        """"""
        if len(args) == 1 and isinstance(args[0], collections.Callable):
            return self._generate_command(args[0])
        else:
            def _command(func):
                return self._generate_command(func, *args, **kwargs)
            return _command
860820
def build_args():
    """"""

    parser = argparse.ArgumentParser(description=u'Compile a sensor graph.')
    parser.add_argument(u'sensor_graph', type=str, help=u"the sensor graph file to load and run.")
    parser.add_argument(u'-f', u'--format', default=u"nodes", choices=[u'nodes', u'ast', u'snippet', u'ascii', u'config', u'script'], type=str, help=u"the output format for the compiled result.")
    parser.add_argument(u'-o', u'--output', type=str, help=u"the output file to save the results (defaults to stdout)")
    parser.add_argument(u'--disable-optimizer', action="store_true", help=u"disable the sensor graph optimizer completely")
    return parser
303336
function createCmdArguments(cmdArguments, opts) {
    if (toString.call(cmdArguments) !== '[object Array]') {
        cmdArguments = [];
    }
    if (toString.call(cmdArguments[0]) !== '[object Array]') {
        cmdArguments[0] = [];
    }
    cmdArguments[1] = cmdArguments[1] || {};
    cmdArguments[2] = opts;

    return cmdArguments;
}
564067
def _build_args(method, ip, comment):
    '''
    
    '''
    opt = _get_opt(method)
    args = '{0} {1}'.format(opt, ip)
    if comment:
        args += ' {0}'.format(comment)
    return args
608943
def cmd(args, interact=False):
    """"""
    if isinstance(args, (str, bytes)):
        args = args.split()
    return CLI.cmd(args=args, interact=interact)
656031
def _prepare_if_args(stmt):
    """"""
    args = stmt['args']
    if args and args[0].startswith('(') and args[-1].endswith(')'):
        args[0] = args[0][1:].lstrip()
        args[-1] = args[-1][:-1].rstrip()
        start = int(not args[0])
        end = len(args) - int(not args[-1])
        args[:] = args[start:end]
1169486
def send_notification(self, method, args, kwargs):
        """"""
        msg = dumps([1, method, args, kwargs])
        self.send(msg)
337014
def command(self, init=False):
        """"""

        def wrapper(func):
            header = '\n'.join([s for s in (func.__doc__ or '').split('\n')
                                if not s.strip().startswith(':')])
            parser = self.parsers.add_parser(func.__name__, description=header)
            args, vargs, kw, defs, kwargs, kwdefs, anns = inspect.getfullargspec(func)
            defs = defs or []
            kwargs_ = dict(zip(args[-len(defs):], defs))
            docs = dict(PARAM_RE.findall(func.__doc__ or ""))

            def process_arg(name, *, value=..., **opts):
                argname = name.replace('_', '-').lower()
                arghelp = docs.get(vargs, '')
                if value is ...:
                    return parser.add_argument(argname, help=arghelp, **opts)

                if isinstance(value, bool):
                    if value:
                        return parser.add_argument(
                            "--no-" + argname, dest=name, action="store_false",
                            help="Disable %s" % (arghelp or name).lower())

                    return parser.add_argument(
                        "--" + argname, dest=name, action="store_true",
                        help="Enable %s" % (arghelp or name).lower())

                if isinstance(value, list):
                    return parser.add_argument(
                        "--" + argname, action="append", default=value, help=arghelp)

                return parser.add_argument(
                    "--" + argname, type=anns.get(name, type(value)),
                    default=value, help=arghelp + ' [%s]' % repr(value))

            if vargs:
                process_arg('*', nargs="*", metavar=vargs)

            for name, value in (kwdefs or {}).items():
                process_arg(name, value=value)

            for name in args:
                process_arg(name, value=kwargs_.get(name, ...))

            self.handlers[func.__name__] = func
            func.parser = parser
            return func

        if callable(init):
            init.__init__ = True
            return wrapper(init)

        def decorator(func):
            func.__init__ = bool(init)
            return wrapper(func)

        return decorator
59222
def _run():
    """"""
    args = parse_args()

    # register signal handler
    signal.signal(signal.SIGTERM, signal_handler)
    signal.signal(signal.SIGINT, signal_handler)

    # set up logging
    log_formatter = logging.Formatter("%(asctime)s %(filename)s(line %(lineno)d) "
                                      "%(levelname)s: %(message)s")
    root_logger = logging.getLogger()
    root_logger.setLevel(logging.INFO)
    console_handler = logging.StreamHandler()
    console_handler.setFormatter(log_formatter)
    root_logger.addHandler(console_handler)

    # add file handler if specified
    if args.log_file:
        file_handler = logging.FileHandler(args.log_file)
        file_handler.setFormatter(log_formatter)
        root_logger.addHandler(file_handler)

    # check vm_num and vm_index value
    if args.vm_num < 1:
        print "vm_num value cannot be negative!"
        return
    if args.vm_index < 1 or args.vm_index > args.vm_num:
        print "vm_index value cannot be negative or greater than vm_num!"
        return

    if args.create_conf_dir:
        if args.create_HMA:
            hma_dir = return_abs_path(args.create_conf_dir, 'vpns')
            hma.create_config_files(hma_dir)
        elif args.create_IPVANISH:
            ipvanish_dir = return_abs_path(args.create_conf_dir, 'vpns')
            ipvanish.create_config_files(ipvanish_dir)
        elif args.create_PUREVPN:
            purevpn_dir = return_abs_path(args.create_conf_dir, 'vpns')
            purevpn.create_config_files(purevpn_dir)
        elif args.create_VPNGATE:
            vpngate_dir = return_abs_path(args.create_conf_dir, 'vpns')
            vpngate.create_config_files(vpngate_dir)
        # create the config files for the openvpn config files
        create_config_files(args.create_conf_dir)
    else:
        # sanity check tls_auth and key_direction
        if (args.tls_auth is not None and args.key_direction is None) or \
                (args.tls_auth is None and args.key_direction is not None):
            logging.error("tls_auth and key_direction must be specified "
                          "together!")
            return

        scan_vpns(directory=args.directory, auth_file=args.auth_file,
                  crt_file=args.crt_file, tls_auth=args.tls_auth,
                  key_direction=args.key_direction, exclude_list=args.exclude_list,
                  shuffle_lists=args.shuffle_lists, vm_num=args.vm_num,
                  vm_index=args.vm_index, reduce_vp=args.reduce_vp)
852963
def cmdline(argv, rules=None, config=None, **kwargs):
    """"""
    parser = Parser(rules, **kwargs)
    if config is not None: parser.loadrc(config)
    return parser.parse(argv).result
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")
1289657
def _verbose_message(message, *args, **kwargs):
    """"""
    verbosity = kwargs.pop('verbosity', 1)
    if sys.flags.verbose >= verbosity:
        if not message.startswith(('#', 'import ')):
            message = '# ' + message
        print(message.format(*args), file=sys.stderr)