Decorator that validates the kwargs of the function passed to it.
557358
def validate_input(function):
    """"""
    @wraps(function)
    def wrapper(*args, **kwargs):
        try:
            name = function.__name__ + '_validator'  # find validator name
            globals()[name](kwargs)  # call validation function
            return function(*args, **kwargs)
        except KeyError:
            raise Exception("Could not find validation schema for the"
                            " function " + function.__name__)
    return wrapper
547351
def kwargs(self, obj, kwargs):
        '''
        
        '''
        if hasattr(obj, "KWARGS"):
            for module_argument in obj.KWARGS:
                if has_key(kwargs, module_argument.name):
                    arg_value = kwargs[module_argument.name]
                else:
                    arg_value = copy(module_argument.default)

                setattr(obj, module_argument.name, arg_value)

            for (k, v) in iterator(kwargs):
                if not hasattr(obj, k):
                    setattr(obj, k, v)
        else:
            raise Exception("binwalk.core.module.Modules.process_kwargs: %s has no attribute 'KWARGS'" % str(obj))
312450
def _call_with_selection(func):
    """"""
    wrapped_kwonly_params = [
        param for param in inspect.signature(func).parameters.values()
        if param.kind == param.KEYWORD_ONLY]
    sel_sig = inspect.signature(Selection)
    default_sel_sig = sel_sig.replace(
        parameters=[param.replace(default=None) if param.default is param.empty
                    else param
                    for param in sel_sig.parameters.values()])

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        extra_kw = {param.name: kwargs.pop(param.name)
                    for param in wrapped_kwonly_params if param.name in kwargs}
        ba = default_sel_sig.bind(*args, **kwargs)
        # apply_defaults
        ba.arguments = ChainMap(
            ba.arguments,
            {name: param.default
             for name, param in default_sel_sig.parameters.items()
             if param.default is not param.empty})
        sel = Selection(*ba.args, **ba.kwargs)
        return func(sel, **extra_kw)

    wrapper.__signature__ = Signature(
        list(sel_sig.parameters.values()) + wrapped_kwonly_params)
    return wrapper
755272
def validate_class_type_arguments(operator):
    

    def inner(function):

        def wrapper(self, *args, **kwargs):
            for arg in args + tuple(kwargs.values()):
                if not isinstance(arg, self.__class__):
                    raise TypeError(
                        'unorderable types: {}() {} {}()'.format(
                            type(self).__name__, operator, type(arg).__name__
                        )
                    )

            return function(self, *args, **kwargs)

        return wrapper

    return inner
728412
def _build_callable_validator(function):
    """"""

    def callable_validator(data):
        """Validate by checking the return value of function(data)."""
        try:
            if function(data):
                return data

        except (TypeError, ValueError, NotValid) as ex:
            raise NotValid(ex.args)

        raise NotValid("%r invalidated by '%s'" % (data, _get_repr(function)))

    return callable_validator
1186358
def parse_func_kwarg_keys(func, with_vals=False):
    
    sourcecode = get_func_sourcecode(func, strip_docstr=True,
                                     strip_comments=True)
    kwkeys = parse_kwarg_keys(sourcecode, with_vals=with_vals)
    #ut.get_func_kwargs  TODO
    return kwkeys
1139263
def validate_groupby_func(name, args, kwargs, allowed=None):
    
    if allowed is None:
        allowed = []

    kwargs = set(kwargs) - set(allowed)

    if len(args) + len(kwargs) > 0:
        raise UnsupportedFunctionCall((
            "numpy operations are not valid "
            "with groupby. Use .groupby(...)."
            "{func}() instead".format(func=name)))
871637
def call(self, func, *args, **kwargs):
        
        wrapped = self.wrap(func)
        return wrapped(*args, **kwargs)
930004
def restrict_args(func, *args, **kwargs):
    '''
    
    '''
    callargs = getargspec(func)
    if not callargs.varargs:
        args = args[0:len(callargs.args)]
    return func(*args, **kwargs)
606044
def _eval_kwargs(self):
        """"""
        evaled_kwargs = {}
        for k, v in self.p.kwargs.items():
            if util.is_param_method(v):
                v = v()
            evaled_kwargs[k] = v
        return evaled_kwargs
1212195
def call_decorator(cls, func):
        

        @wraps(func)
        def _wrap(self, *args, **kwargs):
            try:
                return func(self, *args, **kwargs)
            except Exception:
                self.logger.exception('While executing benchmark')
                if not (self.catch_child_exception or False):
                    raise

        return _wrap
36318
def validate(**vkargs):
    
    depr('Use route wildcard filters instead.')
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kargs):
            for key, value in vkargs.items():
                if key not in kargs:
                    abort(403, 'Missing parameter: %s' % key)
                try:
                    kargs[key] = value(kargs[key])
                except ValueError:
                    abort(403, 'Wrong parameter format for: %s' % key)
            return func(*args, **kargs)
        return wrapper
    return decorator
75709
def argument(*args, **kwargs):
    
    def decorator(f):
        if not hasattr(f, '_arguments'):
            f._arguments = []
        if not hasattr(f, '_argnames'):
            f._argnames = []
        f._arguments.append((args, kwargs))
        f._argnames.append(_get_dest(*args, **kwargs))
        return f
    return decorator
589906
def type_check(arg_name, pos, reqd_type):
    

    def decorator(fn):

        # brevity compromised in favour of readability
        def logic(*args, **kwargs):
            arg_count = len(args)
            if arg_count:
                if pos < arg_count:
                    if isinstance(args[pos], reqd_type):
                        return fn(*args, **kwargs)
                    else:
                        raise TypeError("'{0}' at position {1} not of type {2}".format(args[pos], pos, reqd_type))
                else:
                    if arg_name in kwargs:
                        value = kwargs[arg_name]
                        if isinstance(value, reqd_type):
                            return fn(*args, **kwargs)
                        else:
                            raise TypeError("'{0}' is not of type {1}".format(arg_name, reqd_type))
                    else:
                        # partially applied functions because of incomplete args, let python handle this
                        return fn(*args, **kwargs)
            else:
                if arg_name in kwargs:
                    value = kwargs[arg_name]
                    if isinstance(value, reqd_type):
                        return fn(*args, **kwargs)
                else:
                    raise TypeError("'{0}' is not of type {1}".format(arg_name, reqd_type))

        return logic

    return decorator
267900
def interface_required(interface):
        
        def _interface_required(func):
            """Internal decorator that wraps around the decorated function.

            Args:
              func (function): function being decorated

            Returns:
              The wrapper function.
            """
            @functools.wraps(func)
            def wrapper(self, *args, **kwargs):
                """Wrapper function to check that the given ``JLink`` has the
                same interface as the one specified by the decorator.

                Args:
                  self (JLink): the ``JLink`` instance
                  args: list of arguments to pass to ``func``
                  kwargs: key-word arguments dict to pass to ``func``

                Returns:
                  The return value of the wrapped function.

                Raises:
                  JLinkException: if the current interface is not supported by
                      the wrapped method.
                """
                if self.tif != interface:
                    raise errors.JLinkException('Unsupported for current interface.')
                return func(self, *args, **kwargs)
            return wrapper
        return _interface_required
299889
def validate(func):
    
    call = PythonCall(func)

    @wraps(func)
    def decorator(*args, **kwargs):
        parameters = call.bind(args, kwargs)
        for arg_name, validator in func.__annotations__.items():
            if not validator(parameters[arg_name]):
                raise TypeError(
                    "Argument {!r} failed to validate".format(arg_name))
        return call.apply(args, kwargs)
    return decorator
1210353
def safe_wraps(wrapper, *args, **kwargs):
    """"""
    while isinstance(wrapper, functools.partial):
        wrapper = wrapper.func
    return functools.wraps(wrapper, *args, **kwargs)