Provides additional validation of the arguments collected by argparse.
325639
def getArguments(parser):
    ""
    args = parser.parse_args()    
    # check output image exists if override not forced
    if not args.force:
        if os.path.exists(args.output + args.image[-4:]):
            raise ArgumentError('The supplied output file {} already exists. Run -f/force flag to override.'.format(args.output))

    return args
694763
def add_arguments(cls, parser, sys_arg_list=None):
        
        parser.add_argument('--tcp_check_interval',
                            dest='tcp_check_interval',
                            required=False, default=2, type=float,
                            help="TCP health-test interval in seconds, "
                                 "default 2 "
                                 "(only for 'tcp' health monitor plugin)")
        parser.add_argument('--tcp_check_port',
                            dest='tcp_check_port',
                            required=False, default=22, type=int,
                            help="Port for TCP health-test, default 22 "
                                 "(only for 'tcp' health monitor plugin)")
        return ["tcp_check_interval", "tcp_check_port"]
332924
private function validate_args( $args, $assoc_args, $extra_args ) {
		$synopsis = $this->get_synopsis();
		if ( ! $synopsis ) {
			return array( array(), $args, $assoc_args, $extra_args );
		}

		$validator = new \WP_CLI\SynopsisValidator( $synopsis );

		$cmd_path = implode( ' ', get_path( $this ) );
		foreach ( $validator->get_unknown() as $token ) {
			\WP_CLI::warning(
				sprintf(
					'The `%s` command has an invalid synopsis part: %s',
					$cmd_path,
					$token
				)
			);
		}

		if ( ! $validator->enough_positionals( $args ) ) {
			$this->show_usage();
			exit( 1 );
		}

		$unknown_positionals = $validator->unknown_positionals( $args );
		if ( ! empty( $unknown_positionals ) ) {
			\WP_CLI::error(
				'Too many positional arguments: ' .
				implode( ' ', $unknown_positionals )
			);
		}

		$synopsis_spec = \WP_CLI\SynopsisParser::parse( $synopsis );
		$i             = 0;
		$errors        = array(
			'fatal'   => array(),
			'warning' => array(),
		);
		$mock_doc      = array( $this->get_shortdesc(), '' );
		$mock_doc      = array_merge( $mock_doc, explode( "\n", $this->get_longdesc() ) );
		$mock_doc      = '/**' . PHP_EOL . '* ' . implode( PHP_EOL . '* ', $mock_doc ) . PHP_EOL . '*/';
		$docparser     = new \WP_CLI\DocParser( $mock_doc );
		foreach ( $synopsis_spec as $spec ) {
			if ( 'positional' === $spec['type'] ) {
				$spec_args = $docparser->get_arg_args( $spec['name'] );
				if ( ! isset( $args[ $i ] ) ) {
					if ( isset( $spec_args['default'] ) ) {
						$args[ $i ] = $spec_args['default'];
					}
				}
				if ( isset( $spec_args['options'] ) ) {
					if ( ! empty( $spec['repeating'] ) ) {
						do {
							// phpcs:ignore WordPress.PHP.StrictInArray.MissingTrueStrict -- This is a loose comparison by design.
							if ( isset( $args[ $i ] ) && ! in_array( $args[ $i ], $spec_args['options'] ) ) {
								\WP_CLI::error( 'Invalid value specified for positional arg.' );
							}
							$i++;
						} while ( isset( $args[ $i ] ) );
					} else {
						// phpcs:ignore WordPress.PHP.StrictInArray.MissingTrueStrict -- This is a loose comparison by design.
						if ( isset( $args[ $i ] ) && ! in_array( $args[ $i ], $spec_args['options'] ) ) {
							\WP_CLI::error( 'Invalid value specified for positional arg.' );
						}
					}
				}
				$i++;
			} elseif ( 'assoc' === $spec['type'] ) {
				$spec_args = $docparser->get_param_args( $spec['name'] );
				if ( ! isset( $assoc_args[ $spec['name'] ] ) && ! isset( $extra_args[ $spec['name'] ] ) ) {
					if ( isset( $spec_args['default'] ) ) {
						$assoc_args[ $spec['name'] ] = $spec_args['default'];
					}
				}
				if ( isset( $assoc_args[ $spec['name'] ] ) && isset( $spec_args['options'] ) ) {
					// phpcs:ignore WordPress.PHP.StrictInArray.MissingTrueStrict -- This is a loose comparison by design.
					if ( ! in_array( $assoc_args[ $spec['name'] ], $spec_args['options'] ) ) {
						$errors['fatal'][ $spec['name'] ] = "Invalid value specified for '{$spec['name']}'";
					}
				}
			}
		}

		list( $returned_errors, $to_unset ) = $validator->validate_assoc(
			array_merge( \WP_CLI::get_config(), $extra_args, $assoc_args )
		);
		foreach ( array( 'fatal', 'warning' ) as $error_type ) {
			$errors[ $error_type ] = array_merge( $errors[ $error_type ], $returned_errors[ $error_type ] );
		}

		if ( 'help' !== $this->name ) {
			foreach ( $validator->unknown_assoc( $assoc_args ) as $key ) {
				$suggestion    = Utils\get_suggestion(
					$key,
					$this->get_parameters( $synopsis_spec ),
					$threshold = 2
				);

				$errors['fatal'][] = sprintf(
					'unknown --%s parameter%s',
					$key,
					! empty( $suggestion ) ? PHP_EOL . "Did you mean '--{$suggestion}'?" : ''
				);
			}
		}

		if ( ! empty( $errors['fatal'] ) ) {
			$out = 'Parameter errors:';
			foreach ( $errors['fatal'] as $key => $error ) {
				$out .= "\n {$error}";
				$desc = $docparser->get_param_desc( $key );
				if ( '' !== $desc ) {
					$out .= " ({$desc})";
				}
			}

			\WP_CLI::error( $out );
		}

		array_map( '\\WP_CLI::warning', $errors['warning'] );

		return array( $to_unset, $args, $assoc_args, $extra_args );
	}
555399
def validate_args(self):
        """"""
        base.BaseTarget.validate_args(self)
        params = self.params
        if params['extra_control_fields'] is not None:
            assert isinstance(params['extra_control_fields'], list), (
                'extra_control_fields must be a list of tuples, not %s' % type(
                    params['extra_control_fields']))
            for elem in params['extra_control_fields']:
                assert (isinstance(elem, tuple) and len(elem) == 1), (
                    'extra_control_fields must be a list of 2-element tuples. '
                    'Invalid contents: %s' % elem)
        pkgname_re = '^[a-z][a-z0-9+-.]+'
        assert re.match(pkgname_re, params['package_name']), (
            'Invalid package name: %s. Must match %s' % (
                params['package_name'], pkgname_re))
1110889
def check_args(arguments, data_frame):
    
    stripped_args = [a[0] for a in arguments]
    df = data_frame.df
    # first make sure all args are valid
    for a in arguments:
        if a[0] not in df.index:
            print("-I- ignoring invalid argument: {}".format(a[0]))
            print("-")
    # next make sure required arguments are present
    condition = df['reqd']
    reqd_args = df[condition]
    for arg in reqd_args['arg_name']:
        if arg not in stripped_args:
            raise pmag.MissingCommandLineArgException("-"+arg)
    #next, assign any default values as needed

    #condition = df['default'] != '' # don't need this, and sometimes the correct default argument IS ''
    default_args = df #[condition]
    using_defaults = []
    for arg_name, row in default_args.iterrows():
        default = row['default']
        if arg_name not in stripped_args:
            using_defaults.append(arg_name)
            arguments.append([arg_name, default])
    using_defaults = ["-" + arg for arg in using_defaults]
    print('Using default arguments for: {}'.format(', '.join(using_defaults)))
    return arguments
197957
function Args() {
    if (argv._.length >= 1) {
        try {
            // Attempt to parse 1st argument as JSON string
            _.extend(this, JSON.parse(argv._[0]));
        } catch (err) {
            // Pass, we must be in the console so don't worry about it
        }
    }
}
710033
def build_argparser():
    """"""
    parser = ArgumentParser('Utility for managing MAR files')
    create_group = parser.add_argument_group("Create a MAR file")
    create_group.add_argument("-c", "--create", metavar="MARFILE", help="create MAR")
    create_group.add_argument("-V", "--productversion", dest="productversion",
                              help="product/version string")
    create_group.add_argument("-H", "--channel", dest="channel",
                              help="channel this MAR file is applicable to")
    create_group.add_argument("files", nargs=REMAINDER,
                              help="files to add to the MAR file")

    extract_group = parser.add_argument_group("Extract a MAR file")
    extract_group.add_argument("-x", "--extract", help="extract MAR", metavar="MARFILE")

    list_group = parser.add_argument_group("Print information on a MAR file")
    list_group.add_argument("-t", "--list", help="print out MAR contents",
                            metavar="MARFILE")
    list_group.add_argument("-T", "--list-detailed", metavar="MARFILE",
                            help="print out MAR contents including signatures")

    verify_group = parser.add_argument_group("Verify a MAR file")
    verify_group.add_argument("-v", "--verify", metavar="MARFILE",
                              help="verify the marfile")

    parser.add_argument("-j", "--bzip2", action="store_const", dest="compression",
                        const="bz2", help="compress/decompress members with BZ2")
    parser.add_argument("-J", "--xz", action="store_const", dest="compression",
                        const="xz", help="compress/decompress archive with XZ")
    parser.add_argument("--auto", action="store_const", dest="compression",
                        const="auto", help="automatically decompress contents")

    parser.add_argument("-k", "--keyfiles", dest="keyfiles", action='append',
                        help="sign/verify with given key(s)")
    parser.add_argument("-C", "--chdir", dest="chdir",
                        help="chdir to this directory before creating or "
                        "extracing; location of marfile isn't affected by "
                        "this option.")
    parser.add_argument("--verbose", dest="loglevel", action="store_const",
                        const=logging.DEBUG, default=logging.WARN,
                        help="increase logging verbosity")
    parser.add_argument('--version', action='version', version='mar version {}'.format(mardor.version_str))

    signing_group = parser.add_argument_group('Sign a MAR file')
    signing_group.add_argument('--hash', help='output hash for signing', choices=('sha1', 'sha384'))
    signing_group.add_argument('--asn1', help='format hash as an ASN1 DigestInfo block',
                               default=False, action='store_true')
    signing_group.add_argument('--add-signature', help='inject signature', nargs=3,
                               metavar=('input', 'output', 'signature'))

    return parser
343383
private static void validateArguments(String[] args) {
    if (ArrayUtils.isEmpty(args)) {
      System.err.printf("$ java -server ... %s <port>%n", EchoServer.class.getName());
      System.exit(1);
    }
  }
321861
def validate_args(self):
        
        from ..mixins import ModelMixin

        for arg in ("instance", "decider", "identifier", "fields", "default_language"):
            if getattr(self, arg) is None:
                raise AttributeError("%s must not be None" % arg)

        if not isinstance(self.instance, (ModelMixin,)):
            raise ImproperlyConfigured('"instance" argument must be a Linguist model')

        if not issubclass(self.decider, (models.Model,)):
            raise ImproperlyConfigured(
                '"decider" argument must be a valid Django model'
            )
845585
def check_args(parser, args):
    """"""
    # Make sure only one action has been specified
    if len([a for a in [args.create, args.extract, args.verify, args.list,
                        args.list_detailed, args.hash, args.add_signature] if a
            is not None]) != 1:
        parser.error("Must specify something to do (one of -c, -x, -t, -T, -v, --hash, --add-signature)")

    if args.create and not args.files:
        parser.error("Must specify at least one file to add to marfile")

    if args.extract and args.compression not in (None, 'bz2', 'xz', 'auto'):  # pragma: nocover
        parser.error('Unsupported compression type')

    if args.create and args.compression not in (None, 'bz2', 'xz'):  # pragma: nocover
        parser.error('Unsupported compression type')

    if args.hash and len(args.files) != 1:
        parser.error("Must specify a file to output the hash for")
468807
def parse_args(argv=None):
    """"""
    parser = ArgumentParser()
    parser.add_argument('--replay-file', dest="replay_file", type=str, required=True)

    options = parser.parse_args(argv)
    return options
1249406
def _make_args_checker(self):
        
        def _checker(*args, **kws):
            # Check if too many arguments are provided
            nargs = len(args)
            nnonvaargs = min(nargs, self._max_positional_args)
            if nargs > self._max_positional_args and self._ivararg is None:
                raise self._too_many_args_error(nargs)

            # Check if there are too few positional arguments (without defaults)
            if nargs < self._min_positional_args:
                missing = [p.name
                           for p in self.params[nargs:self._min_positional_args]
                           if p.name not in kws]
                # The "missing" arguments may still be provided as keywords, in
                # which case it's not an error at all.
                if missing:
                    raise self._too_few_args_error(missing, "positional")

            # Check if there are too few required keyword arguments
            if self._required_kwonly_args:
                missing = [kw
                           for kw in self._required_kwonly_args
                           if kw not in kws]
                if missing:
                    raise self._too_few_args_error(missing, "keyword")

            # Check types of positional arguments
            for i, argvalue in enumerate(args):
                param = self.params[i if i < self._max_positional_args else
                                    self._ivararg]
                if param.checker and not (
                    param.checker.check(argvalue) or
                    param.has_default and
                        (argvalue is param.default or argvalue == param.default)
                ):
                    raise self._param_type_error(param, param.name, argvalue)

            # Check types of keyword arguments
            for argname, argvalue in kws.items():
                argindex = self._iargs.get(argname)
                if argindex is not None and argindex < nnonvaargs:
                    raise self._repeating_arg_error(argname)
                index = self._iargs.get(argname)
                if index is None:
                    index = self._ivarkws
                if index is None:
                    s = "%s got an unexpected keyword argument `%s`" % \
                        (self.name_bt, argname)
                    raise self._type_error(s)
                param = self.params[index]
                if param.checker and not (
                    param.checker.check(argvalue) or
                    param.has_default and
                        (argvalue is param.default or argvalue == param.default)
                ):
                    raise self._param_type_error(param, argname, argvalue)

        return _checker
1281691
def AddArg(self, arg):
    
    self.args.append(arg)
    if len(self.args) > self.number_of_args:
      raise ParseError("Too many args for this expression.")

    elif len(self.args) == self.number_of_args:
      return True

    return False
886005
def _parse_arguments(self, method, parameters):
    """"""

    # TODO: Consider raising an exception if there are extra arguments.

    arguments = _fetch_arguments(self, method)

    arg_dict = {}
    errors = []
    for key, properties in parameters:
        if key in arguments:
            value = arguments[key]
            try:
                arg_dict[key] = _apply_validator_chain(
                    properties.get('validators', []), value, self)
            except validators.ValidationError as err:
                errors.append(err)
        else:
            if properties.get('required', False):
                raise web.HTTPError(
                    400,
                    ('Missing required parameter: %s'
                     % (key, ))
                    )
            else:
                if properties.get('default', None) is not None:
                    arg_dict[key] = properties['default']
                else:
                    arg_dict[key] = None
    if errors:
        raise web.HTTPError(400, 'There were %s errors' % len(errors))

    return arg_dict
769336
def _process_arguments(self, arguments):
        
        if not arguments:
            return None
        a = arguments.split(" :", 1)
        arglist = a[0].split()
        if len(a) == 2:
            arglist.append(a[1])
        return arglist
545945
def parse_known_args():
    
    parser = ArgumentParser()
    parser.add_argument("-l", "--loop", type=int, help="Loop every X seconds")
    parser.add_argument('-V', '--version',
                        action='store_true',
                        dest='version',
                        help='Print the version number and exit')
    parser.add_argument("-u", "--update",
                        action='store_true',
                        dest="update",
                        help="Update the software from online repo")
    parser.add_argument("-p", "--problem",
                        action='store_true',
                        dest="problem",
                        help="Report a problem")
    parser.add_argument("-m", "--memory",
                        action='store_true',
                        dest="memory",
                        help="Run memory tests")
    args, otherthings = parser.parse_known_args()
    return args, otherthings, parser
281643
protected void validateArgumentList(String[] args) {
        checkRequiredArguments(args);

        // Skip the first argument as it is the task name
        // Arguments and values come in pairs (expect -password).
        // Anything outside of that pattern is invalid.
        // Loop through, jumping in pairs except when we encounter
        // -password -- that may be an interactive prompt which won't
        // define a value.
        for (int i = 1; i < args.length; i++) {
            String argPair = args[i];
            String arg = null;
            String value = null;
            if (argPair.contains("=")) {
                arg = argPair.split("=")[0];
                value = getValue(argPair);
            } else {
                arg = argPair;
            }

            if (!isKnownArgument(arg)) {
                throw new IllegalArgumentException(getMessage("invalidArg", arg));
            } else {
                if (value == null) {
                    throw new IllegalArgumentException(getMessage("missingValue", arg));
                }
            }
        }
    }