Parse arguments.
177366
public static String[] processOptions(String args[])
    {
        String usageError;
        goodUsage: for (int i = 0; ; ++i) {
            if (i == args.length) {
                return new String[0];
            }
            String arg = args[i];
            if (!arg.startsWith("-")) {
                processStdin = false;
                fileList.add(arg);
                mainModule = arg;
                String[] result = new String[args.length - i - 1];
                System.arraycopy(args, i+1, result, 0, args.length - i - 1);
                return result;
            }
            if (arg.equals("-version")) {
                if (++i == args.length) {
                    usageError = arg;
                    break goodUsage;
                }
                int version;
                try {
                    version = Integer.parseInt(args[i]);
                } catch (NumberFormatException ex) {
                    usageError = args[i];
                    break goodUsage;
                }
                if (!Context.isValidLanguageVersion(version)) {
                    usageError = args[i];
                    break goodUsage;
                }
                shellContextFactory.setLanguageVersion(version);
                continue;
            }
            if (arg.equals("-opt") || arg.equals("-O")) {
                if (++i == args.length) {
                    usageError = arg;
                    break goodUsage;
                }
                int opt;
                try {
                    opt = Integer.parseInt(args[i]);
                } catch (NumberFormatException ex) {
                    usageError = args[i];
                    break goodUsage;
                }
                if (opt == -2) {
                    // Compatibility with Cocoon Rhino fork
                    opt = -1;
                } else if (!Context.isValidOptimizationLevel(opt)) {
                    usageError = args[i];
                    break goodUsage;
                }
                shellContextFactory.setOptimizationLevel(opt);
                continue;
            }
            if (arg.equals("-encoding")) {
                if (++i == args.length) {
                    usageError = arg;
                    break goodUsage;
                }
                String enc = args[i];
                shellContextFactory.setCharacterEncoding(enc);
                continue;
            }
            if (arg.equals("-strict")) {
                shellContextFactory.setStrictMode(true);
                shellContextFactory.setAllowReservedKeywords(false);
                errorReporter.setIsReportingWarnings(true);
                continue;
            }
            if (arg.equals("-fatal-warnings")) {
                shellContextFactory.setWarningAsError(true);
                continue;
            }
            if (arg.equals("-e")) {
                processStdin = false;
                if (++i == args.length) {
                    usageError = arg;
                    break goodUsage;
                }
                if (!global.initialized) {
                    global.init(shellContextFactory);
                }
                IProxy iproxy = new IProxy(IProxy.EVAL_INLINE_SCRIPT);
                iproxy.scriptText = args[i];
                shellContextFactory.call(iproxy);
                continue;
            }
            if (arg.equals("-require")) {
                useRequire = true;
                continue;
            }
            if (arg.equals("-sandbox")) {
                sandboxed = true;
                useRequire = true;
                continue;
            }
            if (arg.equals("-modules")) {
                if (++i == args.length) {
                    usageError = arg;
                    break goodUsage;
                }
                if (modulePath == null) {
                    modulePath = new ArrayList<String>();
                }
                modulePath.add(args[i]);
                useRequire = true;
                continue;
            }
            if (arg.equals("-w")) {
                errorReporter.setIsReportingWarnings(true);
                continue;
            }
            if (arg.equals("-f")) {
                processStdin = false;
                if (++i == args.length) {
                    usageError = arg;
                    break goodUsage;
                }
                if (args[i].equals("-")) {
                    fileList.add(null);
                } else {
                    fileList.add(args[i]);
                    mainModule = args[i];
                }
                continue;
            }
            if (arg.equals("-sealedlib")) {
                global.setSealedStdLib(true);
                continue;
            }
            if (arg.equals("-debug")) {
                shellContextFactory.setGeneratingDebug(true);
                continue;
            }
            if (arg.equals("-?") ||
                arg.equals("-help")) {
                // print usage message
                global.getOut().println(
                    ToolErrorReporter.getMessage("msg.shell.usage", Main.class.getName()));
                exitCode = 1;
                return null;
            }
            usageError = arg;
            break goodUsage;
        }
        // print error and usage message
        global.getOut().println(
            ToolErrorReporter.getMessage("msg.shell.invalid", usageError));
        global.getOut().println(
            ToolErrorReporter.getMessage("msg.shell.usage", Main.class.getName()));
        exitCode = 1;
        return null;
    }
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()
502789
def _parse_arguments(arguments=None):
    """"""
    dir_hash = hashlib.sha1(os.getcwd().encode("utf-8")).hexdigest()

    parser = argparse.ArgumentParser(description="""Lint for Polysquare style guide""")
    parser.add_argument("--checks",
                        nargs=0,
                        action=ShowAvailableChecksAction,
                        help="""list available checks""")
    parser.add_argument("files",
                        nargs="*",
                        metavar=("FILE"),
                        help="""read FILE""",
                        type=str)
    parser.add_argument("--whitelist",
                        nargs="*",
                        help="""list of checks that should only be run""",
                        default=None)
    parser.add_argument("--blacklist",
                        nargs="*",
                        help="""list of checks that should never be run""",
                        default=None)
    parser.add_argument("--fix-what-you-can",
                        action="store_const",
                        help="""fix errors automatically""",
                        const=True)
    parser.add_argument("--spellcheck-cache",
                        help="""path to spell-checking cache file""",
                        default=None)
    parser.add_argument("--log-technical-terms-to",
                        help="""path to file to log technical terms to""",
                        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))
    parser.add_argument("--block-regexps",
                        help="""Regular expressions to exclude from all checks.""",
                        nargs="*",
                        default=None)

    return parser.parse_args(arguments)
586310
def parse_args(args, kwargs):
    """"""
    if 'style' in kwargs:
        args += (kwargs['style'],)
        del kwargs['style']
    for arg in args:
        if not isinstance(arg, (bytes, unicode)):
            raise ValueError("args must be strings:" + repr(args))
        if arg.lower() in FG_COLORS:
            if 'fg' in kwargs: raise ValueError("fg specified twice")
            kwargs['fg'] = FG_COLORS[arg]
        elif arg.lower().startswith('on_') and arg[3:].lower() in BG_COLORS:
            if 'bg' in kwargs: raise ValueError("fg specified twice")
            kwargs['bg'] = BG_COLORS[arg[3:]]
        elif arg.lower() in STYLES:
            kwargs[arg] = True
        else:
            raise ValueError("couldn't process arg: "+repr(arg))
    for k in kwargs:
        if k not in ['fg', 'bg'] + list(STYLES.keys()):
            raise ValueError("Can't apply that transformation")
    if 'fg' in kwargs:
        if kwargs['fg'] in FG_COLORS:
            kwargs['fg'] = FG_COLORS[kwargs['fg']]
        if kwargs['fg'] not in list(FG_COLORS.values()):
            raise ValueError("Bad fg value: %r" % kwargs['fg'])
    if 'bg' in kwargs:
        if kwargs['bg'] in BG_COLORS:
            kwargs['bg'] = BG_COLORS[kwargs['bg']]
        if kwargs['bg'] not in list(BG_COLORS.values()):
            raise ValueError("Bad bg value: %r" % kwargs['bg'])
    return kwargs
935383
def parse_parameters(self, parameters):
        """"""

        self.parameters = []
        for param_name, param_value in parameters.items():
            p = Parameter(param_name, param_value)
            if p:
                self.parameters.append(p)
617983
def parse_args(self, arguments=None):
        
        self._args = self.parser.parse_args(arguments)
        return self.args
749212
def __parseParameters(self):
        """"""
        self.__parameters = []
        for parameter in self.__data['parameters']:
            self.__parameters.append(Parameter(parameter))
815964
def p_arguments(p):
    """'"""
    p[0] = { 'args' : p[1], }
    if len(p) > 2:
        if p[2] == '(':
            p[0]['tests'] = p[3]
        else:
            p[0]['tests'] = [ p[2] ]
1255202
def _parse_args():
    """"""
    import argparse
    parser = argparse.ArgumentParser(description='Keylogger for Linux + X11')
    arg = parser.add_argument
    arg('-s', '--sleep-time', type=float, help='seconds between iterations')
    arg('-t', '--transform', choices=['spanish', 'english_usa', 'pt_br'])
    arg('-f', '--file')
    arg('-l', '--line-buffering', action='store_true')
    args = parser.parse_args()
    return args
344286
def parse_args(add_args, docstring):
    """"""

    def run_args():
        """Run any global methods eponymous with args"""
        valuable_args = {k for k, v in args.__dict__.items() if v}
        arg_methods = {globals()[a] for a in valuable_args if a in globals()}
        if not arg_methods:
            return
        for method in arg_methods:
            method()
        raise SystemExit(_exit_ok)

    parser = argparse.ArgumentParser(
        description=docstring and docstring.splitlines()[0] or "No docstring")
    result = add_args(parser)
    parser = result if result else parser
    parser.add_argument('-v', '--version', action='store_true',
                        help='Show version [default: %s]' % __version__)
    # parser.add_argument('-q', '--quiet', action='store_true',
    # help='Do not show stdout')
    # parser.add_argument('-Q', '--quiet_errors', action='store_true',
    # help='Do not show stderr')
    global args  # pylint: disable=global-statement
    args = parser.parse_args()
    run_args()
    return args
1102283
def parse_view_args(self, req, name, field):
        """"""
        return core.get_value(req.view_args, name, field)
84063
def _parse_arguments():
    """"""
    parser = argparse.ArgumentParser(description="CMake AST Dumper")
    parser.add_argument("filename", nargs=1, metavar=("FILE"),
                        help="read FILE")
    return parser.parse_args()
1262177
def _parse(args):
    """"""

    ordered = []
    opt_full = dict()
    opt_abbrev = dict()

    args = args + ['']  # Avoid out of range
    i = 0

    while i < len(args) - 1:
        arg = args[i]
        arg_next = args[i+1]
        if arg.startswith('--'):
            if arg_next.startswith('-'):
                raise ValueError('{} lacks value'.format(arg))
            else:
                opt_full[arg[2:]] = arg_next
                i += 2
        elif arg.startswith('-'):
            if arg_next.startswith('-'):
                raise ValueError('{} lacks value'.format(arg))
            else:
                opt_abbrev[arg[1:]] = arg_next
                i += 2
        else:
            ordered.append(arg)
            i += 1
    
    return ordered, opt_full, opt_abbrev
396637
def parse_cmd_arguments():
    """"""
    parser = argparse.ArgumentParser()
    parser.add_argument('file', type=str,
                        help='Filename to be staticfied')
    parser.add_argument('--static-endpoint',
                        help='Static endpoint which is "static" by default')
    parser.add_argument('--add-tags', type=str,
                        help='Additional tags to staticfy')
    parser.add_argument('--exc-tags', type=str, help='tags to exclude')
    parser.add_argument('--framework', type=str,
                        help='Web Framework: Defaults to Flask')
    parser.add_argument('--namespace', type=str,
                        help='String to prefix url with')
    parser.add_argument('-o', type=str, help='Specify output file')
    parser.add_argument('--output', type=str, help='Specify output file')
    args = parser.parse_args()

    return args
1016343
def parse(self, line=None):
        """"""
        args = self.parser.parse_args(args=line)
        return args.func(args)
1076400
def parse_args(arguments, apply_config=False):
    """"""
    parser = create_parser()
    args = parser.parse_args(arguments)

    if not args.files and not args.list_fixes:
        parser.error('incorrect number of arguments')

    args.files = [decode_filename(name) for name in args.files]

    if apply_config:
        parser = read_config(args, parser)
        args = parser.parse_args(arguments)
        args.files = [decode_filename(name) for name in args.files]

    if '-' in args.files:
        if len(args.files) > 1:
            parser.error('cannot mix stdin and regular files')

        if args.diff:
            parser.error('--diff cannot be used with standard input')

        if args.in_place:
            parser.error('--in-place cannot be used with standard input')

        if args.recursive:
            parser.error('--recursive cannot be used with standard input')

    if len(args.files) > 1 and not (args.in_place or args.diff):
        parser.error('autopep8 only takes one filename as argument '
                     'unless the "--in-place" or "--diff" args are '
                     'used')

    if args.recursive and not (args.in_place or args.diff):
        parser.error('--recursive must be used with --in-place or --diff')

    if args.in_place and args.diff:
        parser.error('--in-place and --diff are mutually exclusive')

    if args.max_line_length <= 0:
        parser.error('--max-line-length must be greater than 0')

    if args.select:
        args.select = _split_comma_separated(args.select)

    if args.ignore:
        args.ignore = _split_comma_separated(args.ignore)
        if not all(
                any(
                    conflicting_code.startswith(ignore_code)
                    for ignore_code in args.ignore
                )
                for conflicting_code in CONFLICTING_CODES
        ):
            args.ignore.update(CONFLICTING_CODES)
    elif not args.select:
        if args.aggressive:
            # Enable everything by default if aggressive.
            args.select = {'E', 'W1', 'W2', 'W3', 'W6'}
        else:
            args.ignore = _split_comma_separated(DEFAULT_IGNORE)

    if args.exclude:
        args.exclude = _split_comma_separated(args.exclude)
    else:
        args.exclude = {}

    if args.jobs < 1:
        # Do not import multiprocessing globally in case it is not supported
        # on the platform.
        import multiprocessing
        args.jobs = multiprocessing.cpu_count()

    if args.jobs > 1 and not args.in_place:
        parser.error('parallel jobs requires --in-place')

    if args.line_range:
        if args.line_range[0] <= 0:
            parser.error('--range must be positive numbers')
        if args.line_range[0] > args.line_range[1]:
            parser.error('First value of --range should be less than or equal '
                         'to the second')

    return args
1153502
def _parse_args():
    """"""
    class HelpOnErrorArgParser(argparse.ArgumentParser):
        """Print help message as well when an error is raised."""
        def error(self, message):
            sys.stderr.write("Error: %s\n" % message)
            self.print_help()
            sys.exit(2)

    def validate(_file):
        """Validate if the given target argument is a valid file or a valid directory"""
        _file = abspath(_file)
        if not exists(_file):
            if not exists(dirname(_file)):
                # Argparse uses the ArgumentTypeError to give a rejection message like:
                # error: argument input: x does not exist
                raise argparse.ArgumentTypeError("{0} does not exist".format(_file))
        return _file

    def expand_cg_args(cg_args):
        """Separate clubbed flags in command line args for the generator.py

        Allows flags to be clubbed like, -ilt example.txt.
        """
        expanded = list()
        for item in cg_args:
            if len(item) < 3:
                # If at all a flag, must be single flag
                expanded.append(item)
                continue
            if item.startswith("-"):
                if not item.startswith("--"):
                    for flag in item[1:]:
                        expanded.append('-' + flag)
                    continue
            expanded.append(item)
        return expanded

    class AssignDefaultIgnore(argparse.Action):
        """If argument is specified but nothing provided, use pre-defined.

        nargs="*" doesn't allow const and default kwarg can't be used as we might not want to
        ignore as well.
        """
        def __call__(self, parser, args, values, option_string=None):
            if values is not None and not len(values):
                values = IGNORE_METHODS
            setattr(args, self.dest, values)

    try:
        indx = sys.argv.index('--')
        cg_args, sys.argv = sys.argv[1:indx], sys.argv[:1] + sys.argv[indx + 1:]
    except ValueError:
        cg_args = []

    cg_args = expand_cg_args(cg_args)  # allow -il type of usage
    parser = HelpOnErrorArgParser(description=DESCRIPTION)
    parser.add_argument(
        "-l", "--long", action='store_true', default=False,
        help="File reference of method in call graph is absolute, i.e. starts with ansible, "
             "otherwise just the basename if not __init__.py")
    parser.add_argument(
        "-t", "--target", nargs="?", type=validate, const=TARGET_FILE, default=TARGET_FILE,
        help="Filepath to write call graph, defaults to %(default)s")
    parser.add_argument(
        "-i", "--ignore", nargs='*', action=AssignDefaultIgnore,
        help="Methods to ignore while generating call graph")
    # TODO: Aloow classes that can be intercepted
    parser.usage = \
        parser.format_usage()[len("usage: "):].rstrip() + " -- <ansible-playbook options>\n"
    cg_args = parser.parse_args(cg_args)

    if not len(sys.argv[1:]):
        parser.print_help()
        sys.exit(2)

    return cg_args