Custom type for argparse to enforce value limits
432150
def _argparse_minmax_type(self, string):
        """"""
        value = float(string)
        if value < 0 or value > 8:
            raise argparse.ArgumentTypeError(
                '%s must be between 0.0 and 8.0' % string,
            )

        return value
152851
def truncate_args(f):
    

    def wrapper(self, args):
        if len(args) > 100:
            if self.truncate_addresses:
                args = args[:100]
            else:
                raise ValueError(
                    "This exceeds 100 address at a time SmartyStreets limit"
                )

        return f(self, args)

    return wrapper
668003
def limit=(limit)

      if !limit.nil? && limit > 200
        fail ArgumentError, "invalid value for 'limit', must be smaller than or equal to 200."
      end

      if !limit.nil? && limit < 1
        fail ArgumentError, "invalid value for 'limit', must be greater than or equal to 1."
      end

      @limit = limit
    end
242933
def _make_parser(**kwargs):
    
    # Optional arguements for configparser.SafeConfigParser{,readfp}
    kwargs_0 = filter_options(("defaults", "dict_type", "allow_no_value"),
                              kwargs)
    kwargs_1 = filter_options(("filename", ), kwargs)

    try:
        parser = configparser.SafeConfigParser(**kwargs_0)
    except TypeError:
        # .. note::
        #    It seems ConfigParser.*ConfigParser in python 2.6 does not support
        #    'allow_no_value' option parameter, and TypeError will be thrown.
        kwargs_0 = filter_options(("defaults", "dict_type"), kwargs)
        parser = configparser.SafeConfigParser(**kwargs_0)

    return (kwargs_1, parser)
854776
def process_arg_val(arg, val, hsh, is_default = false)
            if is_default && arg.required? && (val.nil? || val.empty?)
                self.errors << "No value was specified for required argument '#{arg}'"
                return
            end
            if !is_default && val.nil? && KeywordArgument === arg
                if arg.value_optional?
                    val = arg.value_optional
                else
                    self.errors << "No value was specified for keyword argument '#{arg}'"
                    return
                end
            end

            # Argument value validation
            if ValueArgument === arg && arg.validation && val
                case arg.validation
                when Regexp
                    [val].flatten.each do |v|
                        add_value_error(arg, val) unless v =~ arg.validation
                    end
                when Array
                    [val].flatten.each do |v|
                        add_value_error(arg, val) unless arg.validation.include?(v)
                    end
                when Proc
                    begin
                        arg.validation.call(val, arg, hsh)
                    rescue StandardError => ex
                        self.errors << "An error occurred in the validation handler for argument '#{arg}': #{ex}"
                        return
                    end
                else
                    raise "Unknown validation type: #{arg.validation.class.name}"
                end
            end

            # TODO: Argument value coercion

            # Call any registered on_parse handler
            begin
                val = arg.on_parse.call(val, arg, hsh) if val && arg.on_parse
            rescue StandardError => ex
                self.errors << "An error occurred in the on_parse handler for argument '#{arg}': #{ex}"
                return
            end

            # Return result
            val
        end
971412
def setup_argparse(self, argument_parser):
    """"""
    import glob
    import logging
    import argparse

    def get_fonts(pattern):

      fonts_to_check = []
      # use glob.glob to accept *.ufo

      for fullpath in glob.glob(pattern):
        fullpath_absolute = os.path.abspath(fullpath)
        if fullpath_absolute.lower().endswith(".ufo") and os.path.isdir(
            fullpath_absolute):
          fonts_to_check.append(fullpath)
        else:
          logging.warning(
              ("Skipping '{}' as it does not seem "
               "to be valid UFO source directory.").format(fullpath))
      return fonts_to_check

    class MergeAction(argparse.Action):

      def __call__(self, parser, namespace, values, option_string=None):
        target = [item for l in values for item in l]
        setattr(namespace, self.dest, target)

    argument_parser.add_argument(
        'fonts',
        # To allow optional commands like "-L" to work without other input
        # files:
        nargs='*',
        type=get_fonts,
        action=MergeAction,
        help='font file path(s) to check.'
        ' Wildcards like *.ufo are allowed.')

    return ('fonts',)
750763
def _format_arg(arg):
    """"""
    # Check that the argument conforms to one of the acceptable types, a string
    # (when the default exception type is used), an exception type (when the
    # default exception message is used) or a list/tuple to specify both
    # exception type and exception message
    if not (_isexception(arg) or isinstance(arg, (str, tuple, list))):
        raise TypeError("Illegal custom contract exception definition")
    # Check that when the argument is a list or tuple, they only have at most
    # 2 items, the exception type and the exception message
    if isinstance(arg, (tuple, list)) and ((not arg) or (len(arg) > 2)):
        raise TypeError("Illegal custom contract exception definition")
    # When only an exception message is given (and the default RuntimeError
    # exception type is used), check that the message is not empty
    if isinstance(arg, str) and (not arg):
        raise ValueError("Empty custom contract exception message")
    # When only an exception message is defined,
    # use the default exception type
    if isinstance(arg, str):
        return {"msg": arg, "type": RuntimeError}
    # When only an exception type is defined,
    # use the default exception message
    if _isexception(arg):
        return {"msg": "Argument `*[argument_name]*` is not valid", "type": arg}
    # If a list/tuple definition is used, check that if is not a string, it is
    # a valid exception type (i.e. that it actually raises an exception)
    if (len(arg) == 1) and (not isinstance(arg[0], str)) and (not _isexception(arg[0])):
        raise TypeError("Illegal custom contract exception definition")
    if (len(arg) == 2) and (
        not (
            (isinstance(arg[0], str) and _isexception(arg[1]))
            or (isinstance(arg[1], str) and _isexception(arg[0]))
        )
    ):
        raise TypeError("Illegal custom contract exception definition")
    # Check that the exception definition has a non-empty exception message
    # when a list/tuple definition is used
    if (len(arg) == 1) and isinstance(arg[0], str) and (not arg[0]):
        raise ValueError("Empty custom contract exception message")
    if (len(arg) == 2) and (
        (isinstance(arg[0], str) and (not arg[0]))
        or (isinstance(arg[1], str) and (not arg[1]))
    ):
        raise ValueError("Empty custom contract exception message")
    # Return conforming dictionary with default exception type and exception
    # message applied (if necessary)
    if len(arg) == 1:
        return {
            "msg": (
                arg[0]
                if isinstance(arg[0], str)
                else "Argument `*[argument_name]*` is not valid"
            ),
            "type": arg[0] if _isexception(arg[0]) else RuntimeError,
        }
    # len(arg) == 2
    return {
        "msg": arg[0] if isinstance(arg[0], str) else arg[1],
        "type": arg[0] if _isexception(arg[0]) else arg[1],
    }
855502
def compilearg(self):
        """"""
        if isinstance(self.value,list):
            value = self.delimiter.join(self.value)
        else:
            value = self.value
        if value.find(" ") >= 0:
            value = '"' + value + '"' #wrap all in quotes

        #for some odd, reason this produced an error, as if we're not an instance of choiceparameter
        #return super(ChoiceParameter,self).compilearg(value)

        #workaround:
        if self.paramflag and self.paramflag[-1] == '=' or self.nospace:
            sep = ''
        elif self.paramflag:
            sep = ' '
        else:
            return str(value)
        return self.paramflag + sep + str(value)
1056140
def parse_arg(arg):
    
    # handle string input
    if type(arg) == str:
        arg = arg.strip()
        # parse csv as tickers and create children
        if ',' in arg:
            arg = arg.split(',')
            arg = [x.strip() for x in arg]
        # assume single string - create single item list
        else:
            arg = [arg]

    return arg
1276997
def max_values(args):
    
    return Interval(max(x.low for x in args), max(x.high for x in 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
1130891
def slicing_singlevalue(arg, length):
    """"""
    if isinstance(arg, slice):
        start, stop, step = arg.indices(length)
        i = start
        if step > 0:
            while i < stop:
                yield i
                i += step
        else:
            while i > stop:
                yield i
                i += step
    else:
        try:
            i = arg.__index__()
        except AttributeError:
            raise TypeError("indices must be integers or slices, not " + arg.__class__.__name__)
        if i < 0:
            i += length
        yield i
885479
function(parser, argv, strict) {

  // Validate.
  if (!_.isObject(parser)) {
    throw new TypeError('Invalid parser objct: ' + pp(parser));
  }
  if (!isArgv(argv)) {
    throw new TypeError('Invalid argv object: ' + pp(argv));
  }
  if (!_.isBoolean(strict)) {
    throw new TypeError('Invalid strict boolean: ' + pp(strict));
  }

  if (strict) {
    // Don't allow any rogue options.
    parser.strict();
  }

  var retVal = {
    payload: argv.payload,
    options: parser.parse(argv.rawOptions),
    rawOptions: argv.rawOptions
  };

  // Guard against non-options right of the splitter.
  if (strict && retVal.options._.length !== 0) {
    throw new Error('Non-options are NOT allowed to the right of "' +
      splitter + '" : ' + retVal.options._);
  }

  // Return.
  return retVal;

}
1198863
def enforce_types(key, val):
    '''
    
    '''
    non_string_params = {
        'ssl_verify': bool,
        'insecure_auth': bool,
        'disable_saltenv_mapping': bool,
        'env_whitelist': 'stringlist',
        'env_blacklist': 'stringlist',
        'saltenv_whitelist': 'stringlist',
        'saltenv_blacklist': 'stringlist',
        'refspecs': 'stringlist',
        'ref_types': 'stringlist',
        'update_interval': int,
    }

    def _find_global(key):
        for item in non_string_params:
            try:
                if key.endswith('_' + item):
                    ret = item
                    break
            except TypeError:
                if key.endswith('_' + six.text_type(item)):
                    ret = item
                    break
        else:
            ret = None
        return ret

    if key not in non_string_params:
        key = _find_global(key)
        if key is None:
            return six.text_type(val)

    expected = non_string_params[key]
    if expected == 'stringlist':
        if not isinstance(val, (six.string_types, list)):
            val = six.text_type(val)
        if isinstance(val, six.string_types):
            return [x.strip() for x in val.split(',')]
        return [six.text_type(x) for x in val]
    else:
        try:
            return expected(val)
        except Exception as exc:
            log.error(
                'Failed to enforce type for key=%s with val=%s, falling back '
                'to a string', key, val
            )
            return six.text_type(val)
335393
def argv(self, module, argv=sys.argv[1:]):
        '''
        
        '''
        kwargs = {'enabled': False}
        last_priority = {}
        parser = argparse.ArgumentParser(add_help=False)
        # Hack: This allows the ListActionParser class to correllate short options to long options.
        # There is probably a built-in way to do this in the
        # argparse.ArgumentParser class?
        parser.short_to_long = {}

        # Must build arguments from all modules so that:
        #
        #    1) Any conflicting arguments will raise an exception
        #    2) The only unknown arguments will be the target files, making them
        #       easy to identify
        for m in self.list(attribute="CLI"):

            for module_option in m.CLI:

                parser_args = []
                parser_kwargs = {}

                if not module_option.long:
                    continue

                if module_option.short:
                    parser_args.append('-' + module_option.short)
                parser_args.append('--' + module_option.long)
                parser_kwargs['dest'] = module_option.long

                if module_option.type is None:
                    parser_kwargs['action'] = 'store_true'
                elif module_option.type is list:
                    parser_kwargs['action'] = 'append'
                    parser.short_to_long[
                        module_option.short] = module_option.long

                parser.add_argument(*parser_args, **parser_kwargs)

        args, unknown = parser.parse_known_args(argv)
        args = args.__dict__

        # Only add parsed options pertinent to the requested module
        for module_option in module.CLI:

            if module_option.type == binwalk.core.common.BlockFile:

                for k in get_keys(module_option.kwargs):
                    kwargs[k] = []
                    for unk in unknown:
                        kwargs[k].append(unk)

            elif has_key(args, module_option.long) and args[module_option.long] not in [None, False]:

                # Loop through all the kwargs for this command line option
                for (name, default_value) in iterator(module_option.kwargs):

                    # If this kwarg has not been previously processed, or if its priority is equal to or
                    # greater than the previously processed kwarg's priority,
                    # then let's process it.
                    if not has_key(last_priority, name) or last_priority[name] <= module_option.priority:

                        # Track the priority for future iterations that may
                        # process the same kwarg name
                        last_priority[name] = module_option.priority

                        try:
                            kwargs[name] = module_option.convert(args[module_option.long], default_value)
                        except KeyboardInterrupt as e:
                            raise e
                        except Exception as e:
                            raise ModuleException("Invalid usage: %s" % str(e))

        binwalk.core.common.debug("%s :: %s => %s" % (module.TITLE, str(argv), str(kwargs)))
        return kwargs
1174070
def _set_arg(self, a, s="main", c=False):
        
        # if action of an argument that suppresses any other, just return
        if a.dest is SUPPRESS or a.default is SUPPRESS:
            return
        # check if an option string is used for this action in sys.argv ;
        #  if so, simply return as it will be parsed normally
        if any(o in sys.argv[1:] for o in a.option_strings):
            return
        # in case of non-null config, get the value from the config object
        default = a.default if a.default is None else str(a.default)
        if c:
            try:
                value = ArgumentParser._config.get(s, a.dest)
            except (NoOptionError, NoSectionError) as e:
                item = "setting" if isinstance(e, NoOptionError) else "section"
                # if the argument is required, just ask for the value
                value = self._input_arg(a) if a.required else default
                logger.debug("{} {} not present in config (set to {})"
                             .format(a.dest, item, value))
        # in case of null config, just ask for the value
        else:
            value = self._input_arg(a)
        # collect the option string before continuing
        try:
            ostr = a.option_strings[0]
        except IndexError:  # occurs when positional argument
            ostr = None
        # now handle arguments regarding the action
        if self.is_action(a, 'store', 'append'):
            if value:
                if ostr:
                    self._reparse_args['opt'].extend([ostr, value])
                else:
                    self._reparse_args['pos'].extend([value])
        elif self.is_action(a, 'store_const', 'append_const'):
            if value.lower() == "add" or value != default:
                self._reparse_args['opt'].append(ostr)
        elif self.is_action(a, 'store_true'):
            if value.lower() in ["y", "true"]:
                self._reparse_args['opt'].append(ostr)
        elif self.is_action(a, 'store_false'):
            if value.lower() in ["n", "false"]:
                self._reparse_args['opt'].append(ostr)
        elif self.is_action(a, 'count'):
            v = int(value or 0)
            if v > 0:
                if ostr.startswith("--"):
                    new_arg = [ostr for i in range(v)]
                else:
                    new_arg = ["-{}".format(v * ostr.strip('-'))]
                self._reparse_args['opt'].extend(new_arg)
        elif self.is_action(a, 'parsers'):
            if not value:
                value = self._input_arg(a)
            pmap = a._name_parser_map
            if c:
                pmap[value].config_args(a.dest)
                pmap[value]._reparse_args['pos'].insert(0, value)
            else:
                pmap[value].input_args()
            self._reparse_args['sub'].append(pmap[value])
        else:
            raise NotImplementedError("Unknown argparse action")
975613
private void checkArgumentRange(final Object argumentValue) {
        // Only validate numeric types because we have already ensured at constructor time that only numeric types have bounds
        if (!Number.class.isAssignableFrom(getUnderlyingFieldClass())) {
            return;
        }

        final Double argumentDoubleValue = (argumentValue == null) ? null : ((Number)argumentValue).doubleValue();

        // Check hard limits first, if specified
        if (hasBoundedRange() && isValueOutOfRange(argumentDoubleValue)) {
            throw new CommandLineException.OutOfRangeArgumentValue(getLongName(), getMinValue(), getMaxValue(), argumentValue);
        }

        // Check recommended values
        if (hasRecommendedRange() && isValueOutOfRange(argumentDoubleValue)) {
            final boolean outMinValue = getMinRecommendedValue() != Double.NEGATIVE_INFINITY;
            final boolean outMaxValue = getMaxRecommendedValue() != Double.POSITIVE_INFINITY;
            if (outMinValue && outMaxValue) {
                logger.warn("Argument --{} has value {}, but recommended within range ({},{})",
                        getLongName(), argumentDoubleValue, getMinRecommendedValue(), getMaxRecommendedValue());
            } else if (outMinValue) {
                logger.warn("Argument --{} has value {}, but minimum recommended is {}",
                        getLongName(), argumentDoubleValue, getMinRecommendedValue());
            } else if (outMaxValue) {
                logger.warn("Argument --{} has value {}, but maximum recommended is {}",
                        getLongName(), argumentDoubleValue, getMaxRecommendedValue());
            }
            // if there is no recommended value, do not log anything
        }
    }