Parse the command line arguments
5505
def parse_args():
    
    parser = argparse.ArgumentParser(description = "Generate secrets for YubiKeys 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('-O', '--output-dir', '--aead-dir',
                        dest='output_dir',
                        default=default_dir,
                        required=False,
                        help='Output directory (AEAD base dir)',
                        )
    parser.add_argument('-c', '--count',
                        dest='count',
                        type=int, default=1,
                        required=False,
                        help='Number of secrets to generate',
                        )
    parser.add_argument('-v', '--verbose',
                        dest='verbose',
                        action='store_true', default=False,
                        help='Enable verbose operation',
                        )
    parser.add_argument('--public-id-chars',
                        dest='public_id_chars',
                        type=int, default=12,
                        required=False,
                        help='Number of chars in generated public ids',
                        )
    parser.add_argument('--key-handles',
                        dest='key_handles',
                        nargs='+',
                        required=True,
                        help='Key handles to encrypt the generated secrets with',
                        )
    parser.add_argument('--start-public-id',
                        dest='start_id',
                        required=True,
                        help='The first public id to generate AEAD for',
                        )

    parser.add_argument('--random-nonce',
                        dest='random_nonce',
                        required=False,
                        action='store_true', default=False,
                        help='Let the HSM generate nonce',
                        )

    return parser.parse_args()
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
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
159567
def parse_command_line():
    """"""
    parser = argparse.ArgumentParser(
        prog='csp_pulsar_sender',
        description='Send fake pulsar data using ftp protocol.')
    parser.add_argument('config_file', type=argparse.FileType('r'),
                        help='JSON configuration file.')
    parser.add_argument('-v', '--verbose', help='Enable verbose messages.',
                        action='store_true')
    parser.add_argument('-p', '--print_settings', help='Print settings file.',
                        action='store_true')
    return parser.parse_args()
634053
def parse_options(arguments=None):
    
    if arguments is None:
        arguments = sys.argv[1:]
    if isinstance(arguments, str):
        arguments = arguments.split()
    if isinstance(arguments, argparse.Namespace):
        return arguments
    parser = create_args_parser()
    args = parser.parse_args(arguments)
    # pprint(args.__dict__)

    args.dialect = args.dialect.lower()
    if args.dialect not in ['lisp', 'newlisp', 'clojure', 'scheme', 'all', '']:
        parser.error("`{0}' is not a recognized dialect".format(args.dialect))

    args.backup_dir = os.path.expanduser(args.backup_dir)
    if not os.path.exists(args.backup_dir):
        parser.error("Directory `{0}' does not exist".format(args.backup_dir))

    if len(args.files) > 1 and args.output_file:
        parser.error('Cannot use the -o flag when more than one file is specified')

    if not args.files:
        # Indentation from standard input
        if args.modify and not args.output_file:
            args.modify = False
        args.backup = False
        args.warning = False

    if args.output_diff:
        # If someone requests a diff we assume he/she doesn't want the file to be
        # modified
        args.modify = False

    return args
1024014
def parse_args():
  """"""
  parser = argparse.ArgumentParser(
      description='Tool to run attacks and defenses.')
  parser.add_argument('--attacks_dir', required=True,
                      help='Location of all attacks.')
  parser.add_argument('--targeted_attacks_dir', required=True,
                      help='Location of all targeted attacks.')
  parser.add_argument('--defenses_dir', required=True,
                      help='Location of all defenses.')
  parser.add_argument('--dataset_dir', required=True,
                      help='Location of the dataset.')
  parser.add_argument('--dataset_metadata', required=True,
                      help='Location of the dataset metadata.')
  parser.add_argument('--intermediate_results_dir', required=True,
                      help='Directory to store intermediate results.')
  parser.add_argument('--output_dir', required=True,
                      help=('Output directory.'))
  parser.add_argument('--epsilon', required=False, type=int, default=16,
                      help='Maximum allowed size of adversarial perturbation')
  parser.add_argument('--gpu', dest='use_gpu', action='store_true')
  parser.add_argument('--nogpu', dest='use_gpu', action='store_false')
  parser.set_defaults(use_gpu=False)
  parser.add_argument('--save_all_classification',
                      dest='save_all_classification', action='store_true')
  parser.add_argument('--nosave_all_classification',
                      dest='save_all_classification', action='store_false')
  parser.set_defaults(save_all_classification=False)
  return parser.parse_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
509811
def _parse_args():
    """"""
    parser = argparse.ArgumentParser(description='{} service.'.
                                     format(__service_id__))
    parser.add_argument('--random_errors', action='store_true',
                        help='Enable random errors')
    parser.add_argument('-v', action='store_true',
                        help='Verbose mode (enable debug printing)')
    parser.add_argument('-vv', action='store_true', help='Extra verbose mode')
    args = parser.parse_args()

    if args.vv:
        init_logger(log_level='DEBUG', show_log_origin=True)
    elif args.v:
        init_logger(logger_name='sip.ec.master_controller', log_level='DEBUG')
    else:
        init_logger(log_level='INFO')

    return args
1275980
def _parse_command_line():
    """"""
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--portserver_static_pool',
        type=str,
        default='15000-24999',
        help='Comma separated N-P Range(s) of ports to manage (inclusive).')
    parser.add_argument(
        '--portserver_unix_socket_address',
        type=str,
        default='@unittest-portserver',
        help='Address of AF_UNIX socket on which to listen (first @ is a NUL).')
    parser.add_argument('--verbose',
                        action='store_true',
                        default=False,
                        help='Enable verbose messages.')
    parser.add_argument('--debug',
                        action='store_true',
                        default=False,
                        help='Enable full debug messages.')
    return parser.parse_args(sys.argv[1:])
36213
def parse_arguments(argv):
    
    parser = argparse.ArgumentParser(description=DESCRIPTION)
    base_parser = argparse.ArgumentParser(add_help=False)

    parser.add_argument('-V', '--version', action='version',
                        version='taxit v' + version,
                        help='Print the version number and exit')

    parser.add_argument('-v', '--verbose',
                        action='count', dest='verbosity', default=1,
                        help='Increase verbosity of screen output (eg, -v is verbose, '
                        '-vv more so)')
    parser.add_argument('-q', '--quiet',
                        action='store_const', dest='verbosity', const=0,
                        help='Suppress output')

    ##########################
    # Setup all sub-commands #
    ##########################

    subparsers = parser.add_subparsers(dest='subparser_name')

    # Begin help sub-command
    parser_help = subparsers.add_parser(
        'help', help='Detailed help for actions using `help <action>`')
    parser_help.add_argument('action', nargs=1)
    # End help sub-command

    actions = {}

    for name, mod in subcommands.itermodules(
            os.path.split(subcommands.__file__)[0]):
        # set up subcommand help text. The first line of the dosctring
        # in the module is displayed as the help text in the
        # script-level help message (`script -h`). The entire
        # docstring is displayed in the help message for the
        # individual subcommand ((`script action -h`)).
        subparser = subparsers.add_parser(
            name,
            prog='taxit {}'.format(name),
            help=mod.__doc__.lstrip().split('\n', 1)[0],
            description=mod.__doc__,
            formatter_class=RawDescriptionHelpFormatter,
            parents=[base_parser])

        mod.build_parser(subparser)
        actions[name] = mod.action

    # Determine we have called ourself (e.g. "help <action>")
    # Set arguments to display help if parameter is set
    #           *or*
    # Set arguments to perform an action with any specified options.
    arguments = parser.parse_args(argv)
    # Determine which action is in play.
    action = arguments.subparser_name

    # Support help <action> by simply having this function call itself and
    # translate the arguments into something that argparse can work with.
    if action == 'help':
        return parse_arguments([str(arguments.action[0]), '-h'])

    return actions[action], arguments
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))
1309159
private function parseArgs() {
        // Use the global $argv variable to retrieve command-line arguments
        global $argv;

        // Reset values
        $this->_flags       = [];
        $this->_options     = [];
        $this->_parameters  = [];

        // index[0] is the script name and index[1] is the command name
        // so count starts from 2 from now on
        for ($i = 2; $i < count($argv); $i++) {
            if (strpos($argv[$i], '-') === 0) {
                // In gnuopt flags are determined by parameters that starts with `-`
                $flag = ltrim($argv[$i], '-');
                // Make sure that every things splittable
                $flag = strlen($flag) > 1 ? str_split($flag) : [$flag];
                // Then register flags
                $this->_flags = array_merge($this->_flags, $flag);
            } else if (strpos($argv[$i], $this->_delimeter) > 0) {
                // In our history options are the parameters that lets the user
                // to set the value of a key 
                $tokens = explode($this->_delimeter, $argv[$i]);
                // Make sure to remove the option key
                $param_name = strtolower($tokens[0]);
                array_shift($tokens);
                // Then let the others to be the value
                $param_value = implode($this->_delimeter, $tokens);
                // Register options
                // NOTE: Options are allowed to be overwritten
                $this->_options[$param_name] = $param_value;
            } else {
                // Else, it a parameter
                $this->_parameters[] = $argv[$i];
            }
        }
    }
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
945141
def _get_args_to_parse(args, sys_argv):
    
    arguments = args if args is not None else sys_argv[1:]
    _LOG.debug("Parsing arguments: %s", arguments)
    return arguments
50667
private void parseCommandLineArgs(String[] args) throws ConfigurationException {
        if (args == null || args.length == 0) {
            return;
        }
        logger.info("Parsing command line arguments");
        m_commandLineArgs = args;
        
        try {
            for (int inx = 0; inx < args.length; inx++) {
                String arg = args[inx];
                if (arg.equals("-?") || arg.equalsIgnoreCase("-h") || arg.equalsIgnoreCase("-help")) {
                    System.out.println("See documentation and doradus.yaml for help.");
                    System.exit(0);
                }
                Utils.require(arg.charAt(0) == '-', "Unrecognized argument: %s", arg);
                Utils.require(inx + 1 < args.length, "A value is expected after: %s", arg);
                String name = arg.substring(1);
                String value = args[++inx];
                setCommandLineParam(name, value);
            }
        } catch (Exception e) {
            logger.error("Failed to parse command line arguments", e);
            throw new ConfigurationException("Failed to parse command line arguments", e);
        }
    }
410879
def parse(args: list = None) -> dict:
    

    parser = ArgumentParser(description='Cauldron command')
    parser.add_argument(
        'command',
        nargs='?',
        default='shell',
        help='The Cauldron command action to execute'
    )

    parser.add_argument(
        '-v', '--version',
        dest='show_version_info',
        default=False,
        action='store_true',
        help='show Cauldron version and exit'
    )

    sub_parsers = parser.add_subparsers(
        dest='command',
        title='Sub-Command Actions',
        description='The actions you can execute with the cauldron command',
    )

    sub_parsers.add_parser('shell', aliases=['version'])
    add_shell_action(sub_parsers.add_parser('shell'))
    add_kernel_action(sub_parsers.add_parser('kernel', aliases=['serve']))

    arguments = vars(parser.parse_args(args=args))
    arguments['parser'] = parser
    return arguments
897287
def parse_args(argv=None):
    """"""
    parser = ArgumentParser()
    parser.add_argument('--password', dest="password", type=str)
    parser.add_argument('--user', dest="user", type=str)
    parser.add_argument('--config-file', dest="config_file", type=str)

    options = parser.parse_args(argv)
    return options