Parse and handle command line options
324535
def handle_options
      drivers = ::QUnited::Driver.constants.reject { |d| d == :Base }
      valid_drivers_string = "Valid drivers include: #{drivers.map { |d| d.to_s }.join(', ')}"

      args_empty = ARGV.empty?

      # This is a bit of a hack, but OptionParser removes the -- that separates the source
      # and test files and we need to put it back in the right place. Save the distance from
      # the end to do this later.
      double_dash_neg_index = ARGV.find_index('--') && (ARGV.find_index('--') - ARGV.size)

      optparse = OptionParser.new do |opts|
        opts.banner = <<-HELP_TEXT
Usage: qunited [OPTIONS] [JS_SOURCE_FILES...] -- [JS_TEST_FILES..]

Runs JavaScript unit tests with QUnit.

JS_SOURCE_FILES are the JavaScript files that you want to test. They will all be
loaded for running each test.

JS_TEST_FILES are files that contain the QUnit tests to run.

Options:
        HELP_TEXT

        opts.on('-d', '--driver [NAME]', 'Specify the driver to use in running the tests',
            valid_drivers_string) do |name|
          raise UsageError, 'Must specify a driver name with -d or --driver option' unless name
          names_and_drivers = Hash[drivers.map { |d| d.to_s.downcase }.zip(drivers)]
          driver = names_and_drivers[name.downcase]
          raise UsageError, "Invalid driver specified: #{name}\n#{valid_drivers_string}" unless driver
          options[:driver] = driver
        end

        opts.on('--fixtures [FILES]', 'Specify some files to include as html before running the tests') do |files|
          options[:fixture_files] = files.split(',')
        end

        opts.on_tail('-h', '--help', 'Show this message') do
          puts opts
          exit
        end
        opts.on_tail('--version', 'Print the QUnited version') do
          puts ::QUnited::VERSION
          exit
        end

        if args_empty
          puts opts
          exit 1
        end
      end.parse!

      # Put the -- back in if we had one initially and it was removed
      if double_dash_neg_index && !ARGV.include?('--')
        ARGV.insert(double_dash_neg_index, '--')
      end
    end
182360
def handle_argv(self, prog_name, argv):
        
        options, args = self.parse_options(prog_name, argv)
        return self.run(*args, **vars(options))
744526
function parseArgs(args) {
  var options = {
    arch: process.arch,
    platform: process.platform,
    force: process.env.npm_config_force === 'true',
  };

  options.args = args.filter(function(arg) {
    if (arg === '-f' || arg === '--force') {
      options.force = true;
      return false;
    } else if (arg.substring(0, 13) === '--target_arch') {
      options.arch = arg.substring(14);
    } else if (arg === '-d' || arg === '--debug') {
      options.debug = true;
    } else if (arg.substring(0, 13) === '--libsass_ext' && arg.substring(14) !== 'no') {
      options.libsassExt = true;
    }

    return true;
  });

  return options;
}
1008278
def cli():
    """"""
    parser = argparse.ArgumentParser()
    parser.add_argument('api', help="""
        API to call.
        One one of 'article', 'frontpage', 'product', 'image', 'analyze', or
        'discussion'.
    """)
    parser.add_argument('url', help="""
        URL to pass as the 'url' parameter.
    """)
    parser.add_argument('token', help="""
        API key (token).
        Get one at https://www.diffbot.com/.
    """)
    parser.add_argument('-a', '--all', help="""
        Request all fields.
    """, action='store_true')
    parser.add_argument('-f', '--file', help="""
        File to read data from.
        Use '-' to read from STDIN.
    """)
    fields = text = html = None
    _args = parser.parse_args()
    if _args.all:
        fields = '*'
    if _args.file == '-':
        text = sys.stdin.read()
    elif _args.file:
        with open(_args.file, 'rb') as src:
            if os.path.splitext(_args.file)[1] in ('.html', '.htm'):
                html = src.read().decode(ENCODING)
            else:
                text = src.read().decode(ENCODING)
    print(json.dumps((api(_args.api, _args.url, _args.token,
                          html=html or None,
                          text=text or None,
                          fields=fields)),
                     sort_keys=True,
                     indent=2))
615912
def parse_conf_args(argv):
    """"""

    args = {}
    for rarg in argv:
        if re.match("^--.*", rarg):
            arg = rarg.replace('--','', 1)

            fsplit = arg.split('=', 1)
            if len(fsplit) != 2:
                raise Exception(
                    "Command option '%s' not recognized." % rarg)

            rkey, value = fsplit
            ssplit = rkey.split('.', 1)
            if len(ssplit) != 2 or not ssplit[1]:
                raise Exception(
                    "Command option '%s' not recognized." % rarg)

            section, option = ssplit
            args[section] = (option, value)
        else:
            raise Exception(
                    "Command option '%s' not recognized." % rarg)

    return args
1128537
def parse_options!(args)
			@options = {}
			opts = ::OptionParser.new do |opts|
				opts.banner = "Usage: syswatch [options]\n\n  Options:"

				opts.on("-f", "--foreground", "Do not daemonize, just run in foreground.") do |f|
					@options[:foreground] = f
				end

				opts.on("-v", "--verbose", "Be verbose, print out some messages.") do |v|
					@options[:verbose] = v
				end

				opts.on("-t", "--test", "Test notifications.") do |t|
					@options[:test] = t
				end

				opts.on("-c", "--config [FILE]", "Use a specific config file, instead of `#{SysWatch::DEFAULTS[:config]}`") do |config|
					@options[:config] = config
				end
			end
			opts.parse! args
		end
1186396
function parseOptions(options) {
    return {
        boolean: "boolean" in options ? options.boolean : true,
        number: "number" in options ? options.number : true,
        string: "string" in options ? options.string : true,
        allow: options.allow || []
    };
}
1304158
public static CommandLine parse(Options options, String... args) throws Exception {
        return CommandLineParser.parse(options, args);
    }
1353729
def _parse_command_line_arguments():
    
    global config
    # Get command line args for vispy
    argnames = ['vispy-backend=', 'vispy-gl-debug', 'vispy-glir-file=',
                'vispy-log=', 'vispy-help', 'vispy-profile=', 'vispy-cprofile',
                'vispy-dpi=', 'vispy-audit-tests']
    try:
        opts, args = getopt.getopt(sys.argv[1:], '', argnames)
    except getopt.GetoptError:
        opts = []
    # Use them to set the config values
    for o, a in opts:
        if o.startswith('--vispy'):
            if o == '--vispy-backend':
                config['default_backend'] = a
                logger.info('vispy backend: %s', a)
            elif o == '--vispy-gl-debug':
                config['gl_debug'] = True
            elif o == '--vispy-glir-file':
                config['glir_file'] = a
            elif o == '--vispy-log':
                if ',' in a:
                    verbose, match = a.split(',')
                else:
                    verbose = a
                    match = None
                config['logging_level'] = a
                set_log_level(verbose, match)
            elif o == '--vispy-profile':
                config['profile'] = a
            elif o == '--vispy-cprofile':
                _enable_profiling()
            elif o == '--vispy-help':
                print(VISPY_HELP)
            elif o == '--vispy-dpi':
                config['dpi'] = int(a)
            elif o == '--vispy-audit-tests':
                config['audit_tests'] = True
            else:
                logger.warning("Unsupported vispy flag: %s" % o)
1304239
def handle_command_line(options):
    
    options = merge(options, constants.DEFAULT_OPTIONS)
    engine = plugins.ENGINES.get_engine(
        options[constants.LABEL_TEMPLATE_TYPE],
        options[constants.LABEL_TMPL_DIRS],
        options[constants.LABEL_CONFIG_DIR],
    )
    if options[constants.LABEL_TEMPLATE] is None:
        if options[constants.POSITIONAL_LABEL_TEMPLATE] is None:
            raise exceptions.NoTemplate(constants.ERROR_NO_TEMPLATE)
        else:
            engine.render_string_to_file(
                options[constants.POSITIONAL_LABEL_TEMPLATE],
                options[constants.LABEL_CONFIG],
                options[constants.LABEL_OUTPUT],
            )
    else:
        engine.render_to_file(
            options[constants.LABEL_TEMPLATE],
            options[constants.LABEL_CONFIG],
            options[constants.LABEL_OUTPUT],
        )
    engine.report()
    HASH_STORE.save_hashes()
    exit_code = reporter.convert_to_shell_exit_code(
        engine.number_of_templated_files()
    )
    return exit_code
805473
def _parser_options():
    """"""
    import argparse
    parser = argparse.ArgumentParser(description="UNCLE Cron Server")
    parser.add_argument("-examples", action="store_true",
                        help="Display examples of how to use this script.")
    parser.add_argument("-setup", action="store_true",
                        help=("Setup the cron tab and script database for this server so "
                              "that it is ready to have repositories installed."))
    parser.add_argument("-rollback", action="store_true",
                        help=("Remove this script's cron tab and reverse other things done "
                              "by this script. This does not delete this script."))
    parser.add_argument("-enable", action="store_true",
                        help="Re-enable the continuous integration server.")
    parser.add_argument("-disable", action="store_true",
                        help=("Disable the continuous integration server so that it no longer "
                              "monitors the installed repositories."))
    parser.add_argument("-cron", action="store_true",
                        help=("Run the continuous integration routines for all the repos installed "
                              "in this script's database."))
    parser.add_argument("-list", action="store_true",
                        help="List all the repositories in the CI server's database.")
    parser.add_argument("-install", nargs="+",
                        help=("Install the specified XML file(s) as repositories to be monitored "
                              "by the CI server."))
    parser.add_argument("-uninstall", nargs="+",
                        help=("Uninstall the specified XML file(s) as repositories from "
                              "the CI server."))
    parser.add_argument("--verbose", nargs="?", type=int, const=1,
                        help="Runs the CI server in verbose mode.")
    parser.add_argument("-cronfreq", type=int, default=1,
                        help="Specify the frequency at which the cron runs.")
    parser.add_argument("-nolive", action="store_true",
                        help=("For unit testing, when specified no live requests are made to "
                              "servers and all the class actions are performed in test mode. "
                              "This also prevents the cron tab from being installed."))

    global args
    args = vars(parser.parse_known_args()[0])

    if args["examples"]:
        examples()
        exit(0)

    return args
1181062
def _parser_options():
    """"""
    #We have two options: get some of the details from the config file,
    import argparse
    from acorn import base
    pdescr = "ACORN setup and custom configuration"
    parser = argparse.ArgumentParser(parents=[base.bparser], description=pdescr)
    for arg, options in script_options.items():
        parser.add_argument(arg, **options)
        
    args = base.exhandler(examples, parser)
    if args is None:
        return

    return args
1282808
def parse_args
      options = {:thin_command_client => false}

      opts = OptionParser.new do |opts|
        parse_common(opts, options)
        parse_other_args(opts, options)

        opts.on("-s", "--start AGENT") do |a|
          options[:action] = 'start'
          options[:agent_name] = a
        end

        opts.on("-p", "--stop AGENT") do |a|
          options[:action] = 'stop'
          options[:agent_name] = a
        end

        opts.on("--stop-agent ID") do |id|
          options[:action] = 'stop'
          options[:identity] = id
        end

        opts.on("-k", "--kill PIDFILE") do |file|
          options[:pid_file] = file
          options[:action] = 'kill'
        end

        opts.on("-K", "--killall") do
          options[:action] = 'killall'
        end

        opts.on("-U", "--status") do
          options[:action] = 'show'
        end

        opts.on("-l", "--list") do
          options[:list] = true
        end

        opts.on("--log-level LVL") do |lvl|
          options[:log_level] = lvl
        end

        opts.on("-c", "--cfg-dir DIR") do |d|
          options[:cfg_dir] = d
        end

        opts.on("-z", "--pid-dir DIR") do |dir|
          options[:pid_dir] = dir
        end

        opts.on("--log-dir DIR") do |dir|
          options[:log_dir] = dir

          # Ensure log directory exists (for windows, etc.)
          FileUtils.mkdir_p(dir) unless File.directory?(dir)
        end

        opts.on("-f", "--foreground") do
          options[:daemonize] = false
          #Squelch Ruby VM warnings about various things
          $VERBOSE = nil
        end

        opts.on("-I", "--interactive") do
          options[:console] = true
        end

        opts.on_tail("--help") do
          puts Usage.scan(__FILE__)
          exit
        end

      end

      begin
        opts.parse(ARGV)
      rescue Exception => e
        exit 0 if e.is_a?(SystemExit)
        fail(e.message, print_usage = true)
      end

      # allow specific arguments to use a thin command client for faster
      # execution (on Windows, etc.)
      unless options[:thin_command_client]
        # require full right_agent for any commands which do not specify thin
        # command client.
        require File.normalize_path(File.join(File.dirname(__FILE__), '..', '..', 'right_agent'))
      end
      resolve_identity(options)
      options
    end
626361
def parse_command_line(self, argv=None):
        
        if self.config:
            parser = argparse.ArgumentParser(add_help=False)
            self.settings['config'].add_argument(parser)
            opts, _ = parser.parse_known_args(argv)
            if opts.config is not None:
                self.set('config', opts.config)

            self.params.update(self.import_from_module())

        parser = self.parser()
        opts = parser.parse_args(argv)
        for k, v in opts.__dict__.items():
            if v is None:
                continue
            self.set(k.lower(), v)
1075462
function handler(current, argv) {
        var cmds = pargv._commands;
        var completions = [];
        if (pargv._env.EXEC === argv[0])
            argv.shift(); // remove first arg which is app/exec name.
        var tmpCmd = pargv.getCommand(utils.first(argv)); // is first is known command.
        if (tmpCmd) { // limit to single command if known.
            cmds = {}; // set the commands to just the one known command.
            cmds[tmpCmd._name] = tmpCmd;
            var sliced_1 = argv.slice(1); // remove command name.
            var curCmdIdx_1 = 0;
            var lastCmdIdx_1 = tmpCmd._arguments.length - 1; // last index for commands.
            sliced_1.forEach(function (el, i) {
                if (!constants_1.FLAG_EXP.test(el) && i <= lastCmdIdx_1) {
                    var prev_1 = sliced_1[i - 1] || null;
                    var prevKey = tmpCmd.isOption(prev_1);
                    if (!prevKey && !constants_1.FLAG_EXP.test(prev_1)) // could be val for option.
                        curCmdIdx_1 = i;
                }
            });
            var curIdx = sliced_1.length - 1;
            var prevIdx = sliced_1.length - 2;
            var prev = sliced_1[prevIdx] || null;
            var isFlagPrev = prev && constants_1.FLAG_EXP.test(prev);
            var isBool = tmpCmd.isBool(prev);
            var isOption = isFlagPrev && !isBool;
            var isCommand = (curCmdIdx_1 >= 0) &&
                (curCmdIdx_1 <= lastCmdIdx_1);
            //  !FLAG_EXP.test(sliced[curIdx])
            if (isCommand || isOption) {
                var key = isOption ? tmpCmd.aliasToKey(prev) : tmpCmd.aliasToKey(curCmdIdx_1);
                if (tmpCmd._completions[key])
                    completions = completions.concat(tmpCmd._completions[key]);
            }
            if (tmpCmd._completions['*']) // anon custom completions.
                completions = completions.concat(tmpCmd._completions['*']);
        }
        else {
            var _loop_1 = function (k) {
                var cmd = cmds[k];
                [cmd._name].concat(cmd.aliases(cmd._name) || []) // iterate commands.
                    .forEach(function (el, i) {
                    if (!~completions.indexOf(el))
                        completions.push(el);
                });
                cmd._options.forEach(function (o) {
                    if (!~completions.indexOf(o))
                        completions.push(o);
                    (cmd.aliases(o) || []).forEach(function (el) {
                        if (!~completions.indexOf(el))
                            completions.push(el);
                    });
                });
            };
            for (var k in cmds) {
                _loop_1(k);
            }
        }
        // TODO: clunky redundant need to refactor this.
        var _options = completions.filter(function (c) { return constants_1.FLAG_EXP.test(c); });
        var _cmds = completions.filter(function (c) { return !constants_1.FLAG_EXP.test(c); });
        return _cmds.sort().concat(_options.sort());
    }
862872
function parse (argv, opts, target) {
  if ('string' === typeof argv) argv = argv.split(rSplit).filter(ignore);
  if (!opts) opts = {};
  opts[don] = true;
  var parsed = parseArray(argv, opts);
  opts[don] = false;
  var through = parsed[don].length ? parseArray(parsed[don], opts) : null;
  if (!target) target = {};
  target.options = parsed;
  target.commands = parsed[din];
  target.input = argv;
  if (through) {
    target.through = {
      options: through,
      commands: through[din]
    };
    delete through[din];
  }
  delete parsed[din];
  delete parsed[don];
  return target;
  function ignore (s) {
    return s && '' !== s;
  }
}
391960
def parse_args
      options = {:reset => false}
      options[:agent_name] = ARGV[0] unless ARGV[0] =~ /^-/

      opts = OptionParser.new do |opts|
        parse_other_args(opts, options)

        opts.on('-r', '--reset') do
          options[:reset] = true
        end

        opts.on('-T', '--timeout SEC') do |sec|
          options[:timeout] = sec
        end

        opts.on('-j', '--json') do
          options[:json] = true
        end

        opts.on('-v', '--verbose') do
          options[:verbose] = true
        end

        opts.on("-c", "--cfg-dir DIR") do |d|
          options[:cfg_dir] = d
        end

        opts.on_tail('--help') do
          puts Usage.scan(__FILE__)
          exit
        end

      end

      begin
        opts.parse(ARGV)
      rescue Exception => e
        exit 0 if e.is_a?(SystemExit)
        fail(e.message + "\nUse 'rstat --help' for additional information")
      end

      options
    end