Parse command line arguments
519291
function parseCommandLine() {
	var commands = process.argv.slice(2);
	var args = {};

	for (var i = 0; i < commands.length; i++) {
		var match = commands[i].match(/^--(.+)=(.+)$/);
		if (match)
			args[match[1]] = match[2];
		else if (i < commands.length - 1 && commands[i].substr(0, 1) === "-") {
			args[commands[i].substr(1)] = commands[i + 1];
			i++;
		}
		else if (i === 0) args[commandKey] = commands[i];
		else if (i === 1) args[commandHost] = commands[i];
	}

	return args;
}
1261735
def parse_args( self, args = None, values = None ):
        '''
        
        '''
        q = multiproc.Queue()
        p = multiproc.Process(target=self._parse_args, args=(q, args, values))
        p.start()
        ret = q.get()
        p.join()
        return ret
335599
function parseCommandLine(args) {

    var parsed_cmds = [];

    if (args.length <= 2) {
        parsed_cmds.push(defaultCommand());
    } else {

        var cli = args.slice(2);

        var pos = 0;
        var cmd;

        cli.forEach(function(element, index, array) {

            //replace alias name with real name.
            if (element.indexOf('--') === -1 && element.indexOf('-') === 0) {
                cli[index] = alias_map[element];
            }

            //parse command and args
            if (cli[index].indexOf('--') === -1) {
                cmd.args.push(cli[index]);
            } else {

                if (keys[cli[index]] == "undefined") {
                    throw new Error("not support command:" + cli[index]);
                };

                pos = index;
                cmd = commands[cli[index]];
                if (typeof cmd.args == 'undefined') {
                    cmd.args = [];
                };
                parsed_cmds.push(cmd);
            }
        });
    };

    return parsed_cmds;
}
830393
def parse_command_line_arguments(argparse_parser, init_indent=5, subs_indent=5,
                                 line_width=76):
    """"""
    # Redirect stdout and stderr to prettify help or usage output from argparse.
    old_stdout = sys.stdout # save stdout
    old_stderr = sys.stderr # save stderr
    sys.stdout = RedirectHelp(sys.stdout, help_string_replacement_pairs,
            init_indent, subs_indent, line_width) # redirect stdout to add postprocessor
    sys.stderr = RedirectHelp(sys.stderr, help_string_replacement_pairs,
            init_indent, subs_indent, line_width) # redirect stderr to add postprocessor

    # Run the actual argument-parsing operation via argparse.
    args = argparse_parser.parse_args()

    # The argparse class has finished its argument-processing, so now no more
    # usage or help messages will be printed.  So restore stdout and stderr
    # to their usual settings, except with self-flushing added.
    sys.stdout = SelfFlushingOutstream(old_stdout)
    sys.stderr = SelfFlushingOutstream(old_stderr)

    return args
1360850
def _parse_arguments(arguments=None):
    """"""
    dir_hash = hashlib.sha1(os.getcwd().encode("utf-8")).hexdigest()

    parser = argparse.ArgumentParser(description="""Find spelling errors""")
    parser.add_argument("files",
                        nargs="*",
                        metavar=("FILE"),
                        help="""read FILE""",
                        type=str)
    parser.add_argument("--spellcheck-cache",
                        help="""path to spell-checking cache file""",
                        default=None)
    parser.add_argument("--technical-terms",
                        help="""path to file to source technical terms from""",
                        default=None)
    parser.add_argument("--stamp-file-path",
                        help="""path to directory to store cached results""",
                        default=os.path.join(tempfile.gettempdir(),
                                             "jobstamps",
                                             "spellcheck_linter",
                                             dir_hash))

    return parser.parse_args(arguments)
103746
protected function parseArguments()
	{
		// Get the list of argument values from the environment.
		$args = $_SERVER['argv'];

		// Set the path used for program execution and remove it form the program arguments.
		$this->executable = array_shift($args);

		// We use a for loop because in some cases we need to look ahead.
		for ($i = 0; $i < count($args); $i++)
		{
			// Get the current argument to analyze.
			$arg = $args[$i];

			// First let's tackle the long argument case.  eg. --foo
			if (strlen($arg) > 2 && substr($arg, 0, 2) == '--')
			{
				// Attempt to split the thing over equals so we can get the key/value pair if an = was used.
				$arg = substr($arg, 2);
				$parts = explode('=', $arg);
				$this->data[$parts[0]] = true;

				// Does not have an =, so let's look ahead to the next argument for the value.
				if (count($parts) == 1 && isset($args[$i + 1]) && preg_match('/^--?.+/', $args[$i + 1]) == 0)
				{
					$this->data[$parts[0]] = $args[$i + 1];

					// Since we used the next argument, increment the counter so we don't use it again.
					$i++;
				}
				elseif (count($parts) == 2)
				// We have an equals sign so take the second "part" of the argument as the value.
				{
					$this->data[$parts[0]] = $parts[1];
				}
			}

			// Next let's see if we are dealing with a "bunch" of short arguments.  eg. -abc
			elseif (strlen($arg) > 2 && $arg[0] == '-')
			{
				// For each of these arguments set the value to TRUE since the flag has been set.
				for ($j = 1; $j < strlen($arg); $j++)
				{
					$this->data[$arg[$j]] = true;
				}
			}

			// OK, so it isn't a long argument or bunch of short ones, so let's look and see if it is a single
			// short argument.  eg. -h
			elseif (strlen($arg) == 2 && $arg[0] == '-')
			{
				// Go ahead and set the value to TRUE and if we find a value later we'll overwrite it.
				$this->data[$arg[1]] = true;

				// Let's look ahead to see if the next argument is a "value".  If it is, use it for this value.
				if (isset($args[$i + 1]) && preg_match('/^--?.+/', $args[$i + 1]) == 0)
				{
					$this->data[$arg[1]] = $args[$i + 1];

					// Since we used the next argument, increment the counter so we don't use it again.
					$i++;
				}
			}

			// Last but not least, we don't have a key/value based argument so just add it to the arguments list.
			else
			{
				$this->args[] = $arg;
			}
		}
	}
203543
def parse_args():
    """"""
    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        description='Diagnose script for checking the current system.')
    choices = ['python', 'pip', 'mxnet', 'os', 'hardware', 'network']
    for choice in choices:
        parser.add_argument('--' + choice, default=1, type=int,
                            help='Diagnose {}.'.format(choice))
    parser.add_argument('--region', default='', type=str,
                        help="Additional sites in which region(s) to test. \
                        Specify 'cn' for example to test mirror sites in China.")
    parser.add_argument('--timeout', default=10, type=int,
                        help="Connection test timeout threshold, 0 to disable.")
    args = parser.parse_args()
    return args
598412
def parse_args():
    
    parser = argparse.ArgumentParser(description="Decrypt YubiKey OTPs using YubiHSM",
                                     add_help=True,
                                     formatter_class=argparse.ArgumentDefaultsHelpFormatter
                                     )
    parser.add_argument('-D', '--device',
                        dest='device',
                        default=default_device,
                        required=False,
                        help='YubiHSM device'
                        )
    parser.add_argument('-B', '--aead-dir',
                        dest='aead_dir',
                        default=default_dir,
                        required=False,
                        help='AEAD directory - base directory of your AEADs',
                        metavar='DIR',
                        )
    parser.add_argument('-U', '--serve-url',
                        dest='serve_url',
                        default=default_serve_url,
                        required=False,
                        help='Base URL for decrypt web service',
                        metavar='URL',
                        )
    parser.add_argument('-S', '--stats-url',
                        dest='stats_url',
                        required=False,
                        help='URL where statistics can be retrieved',
                        metavar='URL',
                        )
    parser.add_argument('-v', '--verbose',
                        dest='verbose',
                        action='store_true', default=False,
                        help='Enable verbose operation'
                        )
    parser.add_argument('-d', '--daemon',
                        dest='daemon',
                        action='store_true', default=False,
                        help='Run as daemon'
                        )
    parser.add_argument('--debug',
                        dest='debug',
                        action='store_true', default=False,
                        help='Enable debug operation'
                        )
    parser.add_argument('--port',
                        dest='listen_port',
                        type=int, default=default_port,
                        required=False,
                        help='Port to listen on',
                        metavar='PORT',
                        )
    parser.add_argument('--addr',
                        dest='listen_addr',
                        default=default_listen_addr,
                        required=False,
                        help='Address to bind to',
                        metavar='ADDR',
                        )
    parser.add_argument('--reqtimeout',
                        dest='reqtimeout',
                        type=int, default=default_reqtimeout,
                        required=False,
                        help='Request timeout in seconds',
                        metavar='SECONDS',
                        )
    parser.add_argument('--key-handle', '--key-handles',
                        dest='key_handles',
                        nargs='+',
                        required=True,
                        help='Key handle(s) to use to decrypt AEADs on the YHSM.',
                        metavar='HANDLE',
                        )
    parser.add_argument('--pid-file',
                        dest='pid_file',
                        default=default_pid_file,
                        required=False,
                        help='PID file',
                        metavar='FILENAME',
                        )
    parser.add_argument('--db-url',
                        dest='db_url',
                        default=default_db_url,
                        required=False,
                        help='The database url to read the AEADs from, you can '
                        'also use env:YOURENVVAR to instead read the URL from '
                        'the YOURENVVAR environment variable.',
                        metavar='DBURL',
                        )
    parser.add_argument('--proxy', '--proxies',
                        dest='proxies',
                        nargs='+',
                        required=False,
                        default=[],
                        help='IP addresses of proxies where the IP in '
                        'X-Forwarded-For should be used for logging purposes.',
                        metavar='IP',
                        )

    return parser.parse_args()
197205
def parse_config_args(args)
      result = {}
      args.scan(/--?([a-z\-\_]+)\s([\d]+)\s?/).each do |arg|
        result[arg.first] = arg.last
      end
      {'raw' => args, 'parsed' => result}
    end
1363817
def parse_args(args):
    
    parser = argparse.ArgumentParser(
        description="Just a Hello World demonstration")
    parser.add_argument(
        '-v',
        '--version',
        action='version',
        version='twip {ver}'.format(ver=__version__))
    return parser.parse_args(args)
235282
def _parse_arguments():
        
        parser = get_base_arguments(get_parser())
        parser = get_tc_arguments(parser)
        args, unknown = parser.parse_known_args()
        return args, unknown
1325741
def parse_command_line(args: List[str] = None, final: bool = True) -> List[str]:
    
    return options.parse_command_line(args, final=final)
365145
def parse_arguments(argv):
    """"""
    parser = argparse.ArgumentParser(description=__doc__.format(__version__))
    parser.add_argument('--application', '-a',
                        dest='application',
                        choices=scraper.APPLICATIONS,
                        default='firefox',
                        metavar='APPLICATION',
                        help='The name of the application to download, default: "%(default)s"')
    parser.add_argument('--base_url',
                        dest='base_url',
                        default=scraper.BASE_URL,
                        metavar='BASE_URL',
                        help='The base url to be used, default: "%(default)s"')
    parser.add_argument('--build-number',
                        dest='build_number',
                        type=int,
                        metavar='BUILD_NUMBER',
                        help='Number of the build (for candidate, daily, and tinderbox builds)')
    parser.add_argument('--debug-build',
                        dest='debug_build',
                        action='store_true',
                        help='Download a debug build (for tinderbox, and try builds)')
    parser.add_argument('--destination', '-d',
                        dest='destination',
                        default=os.getcwd(),
                        metavar='DESTINATION',
                        help='Directory or file name to download the '
                             'file to, default: current working directory')
    parser.add_argument('--extension',
                        dest='extension',
                        metavar='EXTENSION',
                        help='File extension of the build (e.g. "zip"), default: '
                             'the standard build extension on the platform.')
    parser.add_argument('--locale', '-l',
                        dest='locale',
                        metavar='LOCALE',
                        help='Locale of the application, default: "en-US" or "multi"')
    parser.add_argument('--log-level',
                        action='store',
                        dest='log_level',
                        default=logging.INFO,
                        metavar='LOG_LEVEL',
                        help='Threshold for log output (default: INFO')
    parser.add_argument('--password',
                        dest='password',
                        metavar='PASSWORD',
                        help='Password for basic HTTP authentication.')
    parser.add_argument('--platform', '-p',
                        dest='platform',
                        choices=scraper.PLATFORM_FRAGMENTS.keys(),
                        metavar='PLATFORM',
                        help='Platform of the application')
    parser.add_argument('--print-url',
                        dest='print_url',
                        action='store_true',
                        help='Print final URL instead of downloading the file.')
    parser.add_argument('--retry-attempts',
                        dest='retry_attempts',
                        default=0,
                        type=int,
                        metavar='RETRY_ATTEMPTS',
                        help='Number of times the download will be attempted in '
                             'the event of a failure, default: %(default)s')
    parser.add_argument('--retry-delay',
                        dest='retry_delay',
                        default=10.,
                        type=float,
                        metavar='RETRY_DELAY',
                        help='Amount of time (in seconds) to wait between retry '
                             'attempts, default: %(default)s')
    parser.add_argument('--revision',
                        dest='revision',
                        help='Revision of the build (for daily, tinderbox, and try builds)')
    parser.add_argument('--stub',
                        dest='is_stub_installer',
                        action='store_true',
                        help='Stub installer (Only applicable to Windows builds).')
    parser.add_argument('--timeout',
                        dest='timeout',
                        type=float,
                        metavar='TIMEOUT',
                        help='Amount of time (in seconds) until a download times out.')
    parser.add_argument('--type', '-t',
                        dest='scraper_type',
                        choices=factory.scraper_types.keys(),
                        default='release',
                        metavar='SCRAPER_TYPE',
                        help='Type of build to download, default: "%(default)s"')
    parser.add_argument('--url',
                        dest='url',
                        metavar='URL',
                        help='URL to download. Note: Reserved characters (such '
                             'as &) must be escaped or put in quotes otherwise '
                             'CLI output may be abnormal.')
    parser.add_argument('--username',
                        dest='username',
                        metavar='USERNAME',
                        help='Username for basic HTTP authentication.')
    parser.add_argument('--version', '-v',
                        dest='version',
                        metavar='VERSION',
                        help='Version of the application to be downloaded for release '
                             'and candidate builds (special values: %s)' % ', '.join(
                                scraper.RELEASE_AND_CANDIDATE_LATEST_VERSIONS.keys()))

    # Group for daily builds
    group = parser.add_argument_group('Daily builds', 'Extra options for daily builds.')
    group.add_argument('--branch',
                       dest='branch',
                       default='mozilla-central',
                       metavar='BRANCH',
                       help='Name of the branch, default: "%(default)s"')
    group.add_argument('--build-id',
                       dest='build_id',
                       metavar='BUILD_ID',
                       help='ID of the build to download.')
    group.add_argument('--date',
                       dest='date',
                       metavar='DATE',
                       help='Date of the build, default: latest build')

    return vars(parser.parse_args(argv))
682750
def parse(cmdline = ARGV)
    vals = {}
    required = {}

    opt :version, "Print version and exit" if @version && ! (@specs[:version] || @long["version"])
    opt :help, "Show this message" unless @specs[:help] || @long["help"]

    @specs.each do |sym, opts|
      required[sym] = true if opts[:required]
      vals[sym] = opts[:default]
      vals[sym] = [] if opts[:multi] && !opts[:default] # multi arguments default to [], not nil
    end

    resolve_default_short_options!

    ## resolve symbols
    given_args = {}
    @leftovers = each_arg cmdline do |arg, params|
      ## handle --no- forms
      arg, negative_given = if arg =~ /^--no-([^-]\S*)$/
        ["--#{$1}", true]
      else
        [arg, false]
      end

      sym = case arg
        when /^-([^-])$/      then @short[$1]
        when /^--([^-]\S*)$/  then @long[$1] || @long["no-#{$1}"]
        else                       raise CommandlineError, "invalid argument syntax: '#{arg}'"
      end

      sym = nil if arg =~ /--no-/ # explicitly invalidate --no-no- arguments

      next 0 if ignore_invalid_options && !sym
      raise CommandlineError, "unknown argument '#{arg}'" unless sym

      if given_args.include?(sym) && !@specs[sym][:multi]
        raise CommandlineError, "option '#{arg}' specified multiple times"
      end

      given_args[sym] ||= {}
      given_args[sym][:arg] = arg
      given_args[sym][:negative_given] = negative_given
      given_args[sym][:params] ||= []

      # The block returns the number of parameters taken.
      num_params_taken = 0

      unless params.nil?
        if SINGLE_ARG_TYPES.include?(@specs[sym][:type])
          given_args[sym][:params] << params[0, 1]  # take the first parameter
          num_params_taken = 1
        elsif MULTI_ARG_TYPES.include?(@specs[sym][:type])
          given_args[sym][:params] << params        # take all the parameters
          num_params_taken = params.size
        end
      end

      num_params_taken
    end

    ## check for version and help args
    raise VersionNeeded if given_args.include? :version
    raise HelpNeeded if given_args.include? :help

    ## check constraint satisfaction
    @constraints.each do |type, syms|
      constraint_sym = syms.find { |sym| given_args[sym] }
      next unless constraint_sym

      case type
      when :depends
        syms.each { |sym| raise CommandlineError, "--#{@specs[constraint_sym][:long]} requires --#{@specs[sym][:long]}" unless given_args.include? sym }
      when :conflicts
        syms.each { |sym| raise CommandlineError, "--#{@specs[constraint_sym][:long]} conflicts with --#{@specs[sym][:long]}" if given_args.include?(sym) && (sym != constraint_sym) }
      end
    end

    required.each do |sym, val|
      raise CommandlineError, "option --#{@specs[sym][:long]} must be specified" unless given_args.include? sym
    end

    ## parse parameters
    given_args.each do |sym, given_data|
      arg, params, negative_given = given_data.values_at :arg, :params, :negative_given

      opts = @specs[sym]
      if params.empty? && opts[:type] != :flag
        raise CommandlineError, "option '#{arg}' needs a parameter" unless opts[:default]
        params << (opts[:default].kind_of?(Array) ? opts[:default].clone : [opts[:default]])
      end

      vals["#{sym}_given".intern] = true # mark argument as specified on the commandline

      case opts[:type]
      when :flag
        vals[sym] = (sym.to_s =~ /^no_/ ? negative_given : !negative_given)
      when :int, :ints
        vals[sym] = params.map { |pg| pg.map { |p| parse_integer_parameter p, arg } }
      when :float, :floats
        vals[sym] = params.map { |pg| pg.map { |p| parse_float_parameter p, arg } }
      when :string, :strings
        vals[sym] = params.map { |pg| pg.map(&:to_s) }
      when :io, :ios
        vals[sym] = params.map { |pg| pg.map { |p| parse_io_parameter p, arg } }
      when :date, :dates
        vals[sym] = params.map { |pg| pg.map { |p| parse_date_parameter p, arg } }
      end

      if SINGLE_ARG_TYPES.include?(opts[:type])
        if opts[:multi]       # multiple options, each with a single parameter
          vals[sym] = vals[sym].map { |p| p[0] }
        else                  # single parameter
          vals[sym] = vals[sym][0][0]
        end
      elsif MULTI_ARG_TYPES.include?(opts[:type]) && !opts[:multi]
        vals[sym] = vals[sym][0]  # single option, with multiple parameters
      end
      # else: multiple options, with multiple parameters

      opts[:callback].call(vals[sym]) if opts.key?(:callback)
    end

    ## modify input in place with only those
    ## arguments we didn't process
    cmdline.clear
    @leftovers.each { |l| cmdline << l }

    ## allow openstruct-style accessors
    class << vals
      def method_missing(m, *_args)
        self[m] || self[m.to_s]
      end
    end
    vals
  end
227626
def parse_args(args):
    
    index = None
    for arg_i, arg in enumerate(args):
        if not arg.startswith('-'):
            index = arg_i
            break

    # Unable to parse any arguments
    if index is None:
        return (args, None, [])

    return (args[:index], args[index], args[(index + 1):])
1327387
def parse_arguments():
    """"""

    parser = argparse.ArgumentParser(prog=sys.argv[0],
                                     description='Send Webhooks Channel events to IFTTT',
                                     epilog='Visit https://ifttt.com/channels/maker_webhooks for more information')
    parser.add_argument('--version', action='version', version=pyfttt.__version__)

    sgroup = parser.add_argument_group(title='sending events')
    sgroup.add_argument('-k', '--key', metavar='K',
                        default=os.environ.get('IFTTT_API_KEY'),
                        help='IFTTT secret key')
    sgroup.add_argument('-e', '--event', metavar='E', required=True,
                        help='The name of the event to trigger')
    sgroup.add_argument('value1', nargs='?',
                        help='Extra data sent with the event (optional)')
    sgroup.add_argument('value2', nargs='?',
                        help='Extra data sent with the event (optional)')
    sgroup.add_argument('value3', nargs='?',
                        help='Extra data sent with the event (optional)')

    return parser.parse_args()
442312
function parse(args) {
  const cliArgs = [];
  const nodeArgs = [];

  for (const arg of args) {
    if (NODE_FLAGS.test(arg)) {
      nodeArgs.push(arg);
    } else {
      cliArgs.push(arg);
    }
  }

  return {
    cliArgs,
    nodeArgs
  };
}