CLI utility methods
14518
public static SettingsCommandUser build(String[] params)
    {
        GroupedOptions options = GroupedOptions.select(params,
                new Options(new Uncertainty()),
                new Options(new Duration()),
                new Options(new Count()));
        if (options == null)
        {
            printHelp();
            System.out.println("Invalid USER options provided, see output for valid options");
            System.exit(1);
        }
        return new SettingsCommandUser((Options) options);
    }
990293
def cli(ctx, config, debug):
    """"""
    ctx.obj['config'] = config
    ctx.obj['engine'] = stex.SnakeTeX(config_file=config, debug=debug)
123003
def cli(list_files, config, ignore, path):
    
    files = MarkdownFileFinder.find_files(path)
    if list_files:
        echo_files(files)

    lint_config = get_lint_config(config)
    lint_config.apply_on_csv_string(ignore, lint_config.disable_rule)

    linter = MarkdownLinter(lint_config)
    error_count = linter.lint_files(files)
    exit(error_count)
1339143
def run_from_cli():
    

    arg_parser = argparse.ArgumentParser(
        description='Read and write properties in a wp-config.php file. '
                    'Include a --value argument to set the value, omit it to '
                    'read the value of the specified key.',
        prog='python -m wpconfigr')

    arg_parser.add_argument('--filename',
                            help='wp-config.php filename',
                            required=True)

    arg_parser.add_argument('--key',
                            help='Property key',
                            required=True)

    arg_parser.add_argument('--value',
                            help='New property value',
                            required=False)

    arg_parser.add_argument('--log-level',
                            default='CRITICAL',
                            help='Log level',
                            required=False)

    arg_parser.add_argument('--set-true',
                            action='store_true',
                            help='Set the value as boolean true')

    arg_parser.add_argument('--set-false',
                            action='store_true',
                            help='Set the value as boolean false')

    args = arg_parser.parse_args()

    if args.set_true and args.set_false:
        arg_parser.error('Cannot set --set-true and --set-false.')

    if args.value and args.set_true:
        arg_parser.error('Cannot set --value and --set-true.')

    if args.value and args.set_false:
        arg_parser.error('Cannot set --value and --set-false.')

    basicConfig(level=str(args.log_level).upper())

    updater = WpConfigFile(filename=args.filename)

    if args.set_true:
        value = True
    elif args.set_false:
        value = False
    else:
        value = args.value

    if value is not None:
        updater.set(key=args.key, value=value)
    else:
        got = updater.get(key=args.key)

        if got:
            print(got)
581752
def main(args=sys.argv):
    
    try:
        opts, args = getopt.gnu_getopt(args[1:], 'p:o:jdt', [
            'jspath=', 'output=', 'private', 'json', 'dependencies', 
            'test', 'help'])
        opts = dict(opts)
    except getopt.GetoptError:
        usage()
        sys.exit(2)

    run_and_exit_if(opts, run_doctests, '--test')
    run_and_exit_if(opts, usage, '--help')

    js_paths = get_path_list(opts)
    docs = CodeBaseDoc(js_paths, '--private' in opts)
    if args:
        selected_files = set(docs.keys()) & set(args)
    else:
        selected_files = list(docs.keys())

    def print_json():
        print(docs.to_json(selected_files))
    run_and_exit_if(opts, print_json, '--json', '-j')

    def print_dependencies():
        for dependency in find_dependencies(selected_files, docs):
            print(dependency)
    run_and_exit_if(opts, print_dependencies, '--dependencies', '-d')

    output = opts.get('--output') or opts.get('-o')
    if output is None and len(args) != 1:
        output = 'apidocs'
    docs.save_docs(selected_files, output)
608943
def cmd(args, interact=False):
    """"""
    if isinstance(args, (str, bytes)):
        args = args.split()
    return CLI.cmd(args=args, interact=interact)
559891
function main(args, callback) {

  var opts = {};
  Object.keys(options).forEach(key => {
    var opt = options[key];
    if (opt.aliases)
      (opts.alias || (opts.alias = {}))[key] = opt.aliases;
    if (opt.default !== undefined)
      (opts.default || (opts.default = {}))[key] = opt.default;
    if (opt.type === "string")
      (opts.string || (opts.string = [])).push(key);
    else if (opt.type === "boolean")
      (opts.boolean || (opts.boolean = [])).push(key);
  });

  var argv = minimist(args, opts);

  var files = argv._;
  var configFile;

  // prefer specified config file
  if (argv.config)
    configFile = argv.config;

  // otherwise check entry file directory
  else if (files.length)
    if (!fs.existsSync(configFile = path.join(path.dirname(files[0]), "asconfig.json"))) {
      configFile = undefined;
      if (!fs.existsSync(configFile = path.join(path.dirname(files[0]), "tsconfig.json")))
        configFile = undefined;
    }

  // load config file
  if (configFile) {
    try {
      var config = JSON.parse(fs.readFileSync(configFile, "utf8"));
      if (config.assembly)
        config = config.assembly;
      if (config.entryFile) {
        if (!files.length) // prefer command line
          files = [ config.entryFile ];
        delete config.entryFile;
      }
      Object.keys(config).forEach(key => {
        if (options[key] && key !== "config") // prefer command line
          if (options[key].isPath)
            argv[key] = path.isAbsolute(config[key]) ? config[key] : path.join(path.dirname(configFile), config[key]);
          else
            argv[key] = config[key];
      });
    } catch (e) {
      if (!argv.quiet)
        process.stderr.write(chalk.red("\nFailed to load config file: " + e.message + "\n"));
      return callback(EFAILURE);
    }
  }

  // print usage information if requested or no input files have been provided
  if (argv.help || files.length !== 1) {
    (argv.help ? process.stdout : process.stderr).write([
      "Version " + pkg.version + (isDev ? "-dev" + (isOut ? " (out)" : "") : ""),
      "Syntax: "+ chalk.reset.cyan.bold("asc") + " [options] entryFile",
      "",
      chalk.reset.white.bold("Options:"),
      ""
    ].concat(Object.keys(options).map(key => {
      var opt = options[key];
      var cmd = " --" + key;
      if (opt.aliases && opt.aliases.length && opt.aliases[0].length === 1)
        cmd += ", -" + opt.aliases[0];
      while (cmd.length < 18)
        cmd += " ";
      return cmd + "  " + opt.desc.replace(/\n/g, "\n                    ") + "\n";
    })).join("\n").replace(/\[default\]/g, chalk.gray("[default]")));
    return callback(argv.help ? ESUCCESS : EUSAGE);
  }

  // compile to a Binaryen module
  var wasmModule = Compiler.compileFile(files[0], {
    silent: !!argv.quiet,
    target: argv.target,
    noTreeShaking: !!argv.noTreeShaking,
    noImplicitConversion: !!argv.noImplicitConversion,
    noRuntime: !!argv.noRuntime,
    exportRuntime: Array.isArray(argv.exportRuntime) ? argv.exportRuntime
                 : typeof argv.exportRuntime === "string" ? [ argv.exportRuntime ]
                 : undefined
  });

  // bail out if that didn't work
  if (!wasmModule)
    return callback(EFAILURE);

  // from this point on the module must be disposed (finish does this implicitly)

  // optimize the Binaryen module if requested
  if (argv.optimize)
    wasmModule.optimize();

  // validate the Binaryen module if requested
  if (argv.validate) {
    var result = wasmModule.validate(); // FIXME: this always prints to console on error
    if (!result) {
      if (!argv.quiet)
        process.stderr.write(chalk.red("\nValidation failed. See above for details.\n"));
      return finish(Error("validation failed"));
    }
  }

  // default to text format if --outFile references a .wast, .wat or .js and --textFormat isn't specified
  if (argv.outFile && !argv.textFormat) {
    if (/\.wast$/.test(argv.outFile))
      argv.textFormat = "sexpr";
    else if (/\.wat$/.test(argv.outFile))
      argv.textFormat = "linear";
    else if (/\.js$/.test(argv.outfile))
      argv.textFormat = "asmjs";
  }

  // emit to --outFile if specified, otherwise print to stdout
  var output = argv.outFile ? fs.createWriteStream(argv.outFile) : process.stdout;

  // emit text format (textFormat is requested but no textFile has been specified) + asm.js (if applicable)
  if ((argv.textFormat !== undefined || output.isTTY) && !argv.textFile) {
    if (argv.textFormat === "asmjs" || /\.js$/.test(argv.outFile))
      writeAsmjs(wasmModule, output, finish);
    else
      writeText(wasmModule, argv.textFormat, output, maybeWriteAsmjs);

  // emit a binary + text format (if specified) + asm.js (if specified)
  } else
    writeBinary(wasmModule, output, maybeWriteText);

  function maybeWriteText(err) {
    if (err || !argv.textFile)
      return finish(err);
    if (argv.textFormat === "asmjs" || (!argv.textFormat && /\.js$/.test(argv.textFile)))
      writeAsmjs(wasmModule, fs.createWriteStream(argv.textFile), finish);
    else
      writeText(wasmModule, argv.textFormat || /\.wat$/.test(argv.textFile) && "linear" || "sexpr", fs.createWriteStream(argv.textFile), maybeWriteAsmjs);
  }

  function maybeWriteAsmjs(err) {
    if (err || !argv.asmjsFile)
      return finish(err);
    writeAsmjs(wasmModule, fs.createWriteStream(argv.asmjsFile), finish);
  }

  function finish(err) {
    wasmModule.dispose();
    return callback(err ? EFAILURE : ESUCCESS);
  }
}
1051043
public static void main(String[] args) throws ParseException {
		CliFrontend cli = new CliFrontend();
		int retCode = cli.parseParameters(args);
		System.exit(retCode);
	}
301199
def main(args=sys.argv):
    

    parser = create_optparser(args[0])
    return cli(parser.parse_args(args[1:]))
175918
def cli():
    """"""
    from flask.globals import _app_ctx_stack

    app = _app_ctx_stack.top.app
    options = {key: app.config.get(key, DEFAULTS[key]) for key in DEFAULTS.keys()}
    base_context = {"app": app}
    if options["KONCH_FLASK_IMPORTS"]:
        base_context.update(get_flask_imports())

    context = dict(base_context)

    if options["KONCH_FLASK_SHELL_CONTEXT"]:
        flask_context = app.make_shell_context()
        context.update(flask_context)

    context.update(options["KONCH_CONTEXT"])

    def context_formatter(ctx):
        formatted_base = ", ".join(sorted(base_context.keys()))
        ret = "\n{FLASK}\n{base_context}\n".format(
            FLASK=click.style("Flask:", bold=True), base_context=formatted_base
        )
        if options["KONCH_FLASK_SHELL_CONTEXT"]:
            variables = ", ".join(sorted(flask_context.keys()))
            ret += "\n{ADDITIONAL}\n{variables}\n".format(
                ADDITIONAL=click.style(
                    "Flask shell context (see shell_context_processor()):", bold=True
                ),
                variables=variables,
            )
        if options["KONCH_CONTEXT"]:
            variables = ", ".join(sorted(options["KONCH_CONTEXT"].keys()))
            ret += "\n{ADDITIONAL}\n{variables}".format(
                ADDITIONAL=click.style(
                    "Additional variables (see KONCH_CONTEXT):", bold=True
                ),
                variables=variables,
            )
        return ret

    context_format = options["KONCH_CONTEXT_FORMAT"] or context_formatter
    konch.start(
        context=context,
        shell=options["KONCH_SHELL"],
        banner=options["KONCH_BANNER"],
        prompt=options["KONCH_PROMPT"],
        output=options["KONCH_OUTPUT"],
        ptpy_vi_mode=options["KONCH_PTPY_VI_MODE"],
        context_format=context_format,
        ipy_extensions=options["KONCH_IPY_EXTENSIONS"],
        ipy_autoreload=options["KONCH_IPY_AUTORELOAD"],
        ipy_colors=options["KONCH_IPY_COLORS"],
        ipy_highlighting_style=options["KONCH_IPY_HIGHLIGHTING_STYLE"],
    )
188352
def main_as_cli(argv=None):
    ''''''
    try:
        result = main(argv)
    except Exception as e:
        result = __pretty_print_fc_exception(e)
    # FIXME: we should invert True/False return values to 0/1 here, to comply
    # with UNIX exit code semantics (and avoid problems with make, scripts, etc)
    return printToCLI(result)
263115
def main(arguments=None):
    
    # setup the command-line util settings
    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="DEBUG",
        options_first=False,
        projectName="tastic"
    )
    arguments, settings, log, dbConn = su.setup()

    # unpack remaining cl arguments using `exec` to setup the variable names
    # automatically
    for arg, val in arguments.iteritems():
        if arg[0] == "-":
            varname = arg.replace("-", "") + "Flag"
        else:
            varname = arg.replace("<", "").replace(">", "")
        if varname == "import":
            varname = "iimport"
        if isinstance(val, str) or isinstance(val, unicode):
            exec(varname + " = '%s'" % (val,))
        else:
            exec(varname + " = %s" % (val,))
        if arg == "--dbConn":
            dbConn = val
        log.debug('%s = %s' % (varname, val,))

    ## START LOGGING ##
    startTime = times.get_now_sql_datetime()
    log.info(
        '--- STARTING TO RUN THE cl_utils.py AT %s' %
        (startTime,))

    if init:
        from os.path import expanduser
        home = expanduser("~")
        filepath = home + "/.config/tastic/tastic.yaml"
        try:
            cmd = """open %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass
        try:
            cmd = """start %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass

    # CALL FUNCTIONS/OBJECTS
    if sort or archive:

        ws = workspace(
            log=log,
            settings=settings,
            fileOrWorkspacePath=pathToFileOrWorkspace
        )
    if sort:
        ws.sort()
    if archive:
        ws.archive_done()

    if sync:
        tp = syncc(
            log=log,
            settings=settings,
            workspaceRoot=pathToWorkspace,
            workspaceName=workspaceName,
            syncFolder=pathToSyncFolder,
            editorialRootPath=editorialRootPath,
            includeFileTags=fileTagsFlag
        )
        tp.sync()

    if reminders:
        r = reminderss(
            log=log,
            settings=settings
        )
        r.import_list(
            listName=listName,
            pathToTaskpaperDoc=pathToTaskpaperDoc
        )

    if "dbConn" in locals() and dbConn:
        dbConn.commit()
        dbConn.close()
    ## FINISH LOGGING ##
    endTime = times.get_now_sql_datetime()
    runningTime = times.calculate_time_difference(startTime, endTime)
    log.info('-- FINISHED ATTEMPT TO RUN THE cl_utils.py AT %s (RUNTIME: %s) --' %
             (endTime, runningTime, ))

    return
1013194
def cli(parser):
    '''
    
    '''
    parser.add_argument('-n', '--dry-run', action='store_true', help='Print cleanup actions without running')
    opts = parser.parse_args()

    for sitedir in site.getsitepackages():
        cleanup(sitedir, execute=not opts.dry_run, verbose=opts.verbose or opts.dry_run)
771727
def cli(ctx, project_dir):
    """"""
    exit_code = SCons(project_dir).clean()
    ctx.exit(exit_code)
42770
def do_cli(ctx, host, port, template, env_vars, debug_port, debug_args,  # pylint: disable=R0914
           debugger_path, docker_volume_basedir, docker_network, log_file, layer_cache_basedir, skip_pull_image,
           force_image_build, parameter_overrides):
    

    LOG.debug("local start_lambda command is called")

    # Pass all inputs to setup necessary context to invoke function locally.
    # Handler exception raised by the processor for invalid args and print errors

    try:
        with InvokeContext(template_file=template,
                           function_identifier=None,  # Don't scope to one particular function
                           env_vars_file=env_vars,
                           docker_volume_basedir=docker_volume_basedir,
                           docker_network=docker_network,
                           log_file=log_file,
                           skip_pull_image=skip_pull_image,
                           debug_port=debug_port,
                           debug_args=debug_args,
                           debugger_path=debugger_path,
                           parameter_overrides=parameter_overrides,
                           layer_cache_basedir=layer_cache_basedir,
                           force_image_build=force_image_build,
                           aws_region=ctx.region) as invoke_context:

            service = LocalLambdaService(lambda_invoke_context=invoke_context,
                                         port=port,
                                         host=host)
            service.start()

    except (InvalidSamDocumentException,
            OverridesNotWellDefinedError,
            InvalidLayerReference,
            DebuggingNotSupported) as ex:
        raise UserException(str(ex))
120706
def main(arguments=None):
    
    # setup the command-line util settings
    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="WARNING",
        options_first=False,
        projectName="polyglot"
    )
    arguments, settings, log, dbConn = su.setup()

    # unpack remaining cl arguments using `exec` to setup the variable names
    # automatically
    for arg, val in arguments.iteritems():
        if arg[0] == "-":
            varname = arg.replace("-", "") + "Flag"
        else:
            varname = arg.replace("<", "").replace(">", "")
        if isinstance(val, str) or isinstance(val, unicode):
            exec(varname + " = '%s'" % (val,))
        else:
            exec(varname + " = %s" % (val,))
        if arg == "--dbConn":
            dbConn = val
        log.debug('%s = %s' % (varname, val,))

    ## START LOGGING ##
    startTime = times.get_now_sql_datetime()
    log.info(
        '--- STARTING TO RUN THE cl_utils.py AT %s' %
        (startTime,))

    # for k, v in locals().iteritems():
    #     print k, v

    if not destinationFolder:
        destinationFolder = os.getcwd()
    if not filenameFlag:
        filenameFlag = False
    if not cleanFlag:
        readability = False
    else:
        readability = True

    if init:
        from os.path import expanduser
        home = expanduser("~")
        filepath = home + "/.config/polyglot/polyglot.yaml"
        try:
            cmd = """open %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass
        try:
            cmd = """start %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass

    if pdf and url:
        filepath = printpdf.printpdf(
            log=log,
            settings=settings,
            url=url,
            folderpath=destinationFolder,
            title=filenameFlag,
            append=False,
            readability=readability
        ).get()

    if html and url:

        cleaner = htmlCleaner.htmlCleaner(
            log=log,
            settings=settings,
            url=url,
            outputDirectory=destinationFolder,
            title=filenameFlag,  # SET TO FALSE TO USE WEBPAGE TITLE,
            style=cleanFlag,  # add polyglot's styling to the HTML document
            metadata=True,  # include metadata in generated HTML (e.g. title),
            h1=True  # include title as H1 at the top of the doc
        )
        filepath = cleaner.clean()

    if epub:
        if url:
            iinput = url
        else:
            iinput = docx
        from polyglot import ebook
        epub = ebook(
            log=log,
            settings=settings,
            urlOrPath=iinput,
            title=filenameFlag,
            bookFormat="epub",
            outputDirectory=destinationFolder
        )
        filepath = epub.get()

    if mobi:
        if url:
            iinput = url
        else:
            iinput = docx
        from polyglot import ebook
        mobi = ebook(
            log=log,
            settings=settings,
            urlOrPath=iinput,
            title=filenameFlag,
            bookFormat="mobi",
            outputDirectory=destinationFolder,
        )
        filepath = mobi.get()

    if kindle:
        if url:
            iinput = url
        else:
            iinput = docx
        from polyglot import kindle
        sender = kindle(
            log=log,
            settings=settings,
            urlOrPath=iinput,
            title=filenameFlag
        )
        success = sender.send()

    if kindleNB2MD:
        basename = os.path.basename(notebook)
        extension = os.path.splitext(basename)[1]
        filenameNoExtension = os.path.splitext(basename)[0]
        if destinationFolder:
            filepath = destinationFolder + "/" + filenameNoExtension + ".md"
        else:
            filepath = notebook.replace("." + extension, ".md")
        from polyglot.markdown import kindle_notebook
        nb = kindle_notebook(
            log=log,
            kindleExportPath=notebook,
            outputPath=filepath
        )
        nb.convert()

    if openFlag:
        try:
            cmd = """open %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass
        try:
            cmd = """start %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass

    if "dbConn" in locals() and dbConn:
        dbConn.commit()
        dbConn.close()
    ## FINISH LOGGING ##
    endTime = times.get_now_sql_datetime()
    runningTime = times.calculate_time_difference(startTime, endTime)
    log.info('-- FINISHED ATTEMPT TO RUN THE cl_utils.py AT %s (RUNTIME: %s) --' %
             (endTime, runningTime, ))

    return
786933
def do_cli(function_name, stack_name, filter_pattern, tailing, start_time, end_time):
    

    LOG.debug("'logs' command is called")

    with LogsCommandContext(function_name,
                            stack_name=stack_name,
                            filter_pattern=filter_pattern,
                            start_time=start_time,
                            end_time=end_time,
                            # output_file is not yet supported by CLI
                            output_file=None) as context:

        if tailing:
            events_iterable = context.fetcher.tail(context.log_group_name,
                                                   filter_pattern=context.filter_pattern,
                                                   start=context.start_time)
        else:
            events_iterable = context.fetcher.fetch(context.log_group_name,
                                                    filter_pattern=context.filter_pattern,
                                                    start=context.start_time,
                                                    end=context.end_time)

        formatted_events = context.formatter.do_format(events_iterable)

        for event in formatted_events:
            # New line is not necessary. It is already in the log events sent by CloudWatch
            click.echo(event, nl=False)