Creates a proper decorator.

    If the default for the first (function) argument is None, creates a
    version which be invoked as either @decorator or @decorator(kwargs...).

    See examples below.
549951
def decorator(d):
    
    defaults = d.__defaults__
    if defaults and defaults[0] is None:
        # Can be applied as @decorator or @decorator(kwargs) because
        # first argument is None
        def decorate(fn=None, **kwargs):
            if fn is None:
                return _functools.partial(decorate, **kwargs)
            else:
                decorated = d(fn, **kwargs)
                _functools.update_wrapper(decorated, fn)
                return decorated
    else:
        # Can only be applied as @decorator
        def decorate(fn):
            decorated = d(fn)
            _functools.update_wrapper(decorated, fn)
            return decorated
    _functools.update_wrapper(decorate, d)
    return decorate
18188
def decorate_init(init_decorator):
    

    def class_decorator(cls):
        cls.__init__ = init_decorator(cls.__init__)
        return cls

    return class_decorator
1161290
def allow_bare_decorator(cls):
    

    @wraps(cls)
    def wrapper(*args, **kwargs):
        """"Wrapper for real decorator"""

        # If we weren't only passed a bare class, return class instance
        if kwargs or len(args) != 1 or not isclass(args[0]):  # pylint: disable=no-else-return
            return cls(*args, **kwargs)
        # Otherwise, pass call to instance with default values
        else:
            return cls()(args[0])

    return wrapper
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
18997
def arg_default(*args, **kwargs):
    
    parser = argparse.ArgumentParser()
    parser.add_argument(*args, **kwargs)
    args = vars(parser.parse_args([]))
    _, default = args.popitem()
    return default
1182721
def _generate_custom_annotation_instance(self, ns, annotation):
        
        annotation_class = class_name_for_annotation_type(annotation.annotation_type, ns)
        return generate_func_call(
            annotation_class,
            kwargs=((fmt_var(k, True), self._generate_python_value(ns, v))
                    for k, v in annotation.kwargs.items())
        )
919202
def decorator(caller, func=None):
    
    if func is None: # returns a decorator
        fun = FunctionMaker(caller)
        first_arg = inspect.getargspec(caller)[0][0]
        src = 'def %s(%s): return _call_(caller, %s)' % (
            caller.__name__, first_arg, first_arg)
        return fun.make(src, dict(caller=caller, _call_=decorator),
                        undecorated=caller)
    else: # returns a decorated function
        fun = FunctionMaker(func)
        src = """def %(name)s(%(signature)s):
    return _call_(_func_, %(signature)s)"""
        return fun.make(src, dict(_func_=func, _call_=caller), undecorated=func)
31522
def wrap(self, function):
        
        func = inspect.getfullargspec(function)
        needed_arguments = func.args + func.kwonlyargs

        @wraps(function)
        def wrapper(*args, **kwargs):
            arguments = kwargs.copy()
            missing_arguments = needed_arguments - arguments.keys()
            for arg in missing_arguments:
                try:
                    arguments[arg] = self._get_argument(arg)
                except KeyError:
                    pass
            return function(*args, **arguments)

        return wrapper
1355340
def hook(name=None, *args, **kwargs):
    
    def decorator(f):
        if not hasattr(f, "hooks"):
            f.hooks = []
        f.hooks.append((name or f.__name__, args, kwargs))
        return f
    return decorator
1014391
def build_function(name, args=None, defaults=None, doc=None):
    """"""
    args, defaults = args or [], defaults or []
    # first argument is now a list of decorators
    func = nodes.FunctionDef(name, doc)
    func.args = argsnode = nodes.Arguments()
    argsnode.args = []
    for arg in args:
        argsnode.args.append(nodes.Name())
        argsnode.args[-1].name = arg
        argsnode.args[-1].parent = argsnode
    argsnode.defaults = []
    for default in defaults:
        argsnode.defaults.append(nodes.const_factory(default))
        argsnode.defaults[-1].parent = argsnode
    argsnode.kwarg = None
    argsnode.vararg = None
    argsnode.parent = func
    if args:
        register_arguments(func)
    return func
1117181
def init_argument_parser(name=None, **kwargs):
    

    if name is None:
        name = "default"

    if name in _parsers:
        raise ValueError(("kwargs besides 'name' can only be passed in the"
            " first time. '%s' ArgumentParser already exists: %s") % (
            name, _parsers[name]))

    kwargs.setdefault('formatter_class', argparse.ArgumentDefaultsHelpFormatter)
    kwargs.setdefault('conflict_handler', 'resolve')
    _parsers[name] = ArgumentParser(**kwargs)
202950
def self_if_parameters(func):
    
    @wraps(func)
    def wrapper(self, *args, **kwargs):
        result = func(self, *args, **kwargs)
        if args or kwargs:
            return self
        else:
            return result
    return wrapper
1108404
public static function create()
	{
		switch (func_num_args()) {
			case 0:
				return new MethodOptions();
			case 1:
				return new MethodOptions(func_get_arg(0));
			case 2:
				return new MethodOptions(func_get_arg(0), func_get_arg(1));
			case 3:
				return new MethodOptions(func_get_arg(0), func_get_arg(1), func_get_arg(2));
			case 4:
				return new MethodOptions(func_get_arg(0), func_get_arg(1), func_get_arg(2), func_get_arg(3));
			case 5:
				return new MethodOptions(func_get_arg(0), func_get_arg(1), func_get_arg(2), func_get_arg(3), func_get_arg(4));
			case 6:
				return new MethodOptions(func_get_arg(0), func_get_arg(1), func_get_arg(2), func_get_arg(3), func_get_arg(4), func_get_arg(5));
			case 7:
				return new MethodOptions(func_get_arg(0), func_get_arg(1), func_get_arg(2), func_get_arg(3), func_get_arg(4), func_get_arg(5), func_get_arg(6));
			case 8:
				return new MethodOptions(func_get_arg(0), func_get_arg(1), func_get_arg(2), func_get_arg(3), func_get_arg(4), func_get_arg(5), func_get_arg(6), func_get_arg(7));
			default:
				throw new \InvalidArgumentException('More than 8 arguments supplied, please be reasonable.');
		}
	}
1191712
def arg(*args, **kwargs):
    
    def decorate(func):
        """
        Decorate
        """
        # we'll set the command name with the passed cmd_name argument, if
        # exist, else the command name will be the function name
        func.__cmd_name__ = kwargs.pop(
            'cmd_name', getattr(func, '__cmd_name__', func.__name__))
        # retrieve the class (SillyClass)
        func.__cls__ = utils.check_class()
        if not hasattr(func, '__arguments__'):
            # if the funcion hasn't the __arguments__ yet, we'll setup them
            # using get_functarguments.
            func.__arguments__ = utils.get_functarguments(func)
        if len(args) or len(kwargs):
            # if we have some argument or keyword argument
            # we'll try to get the destination name from the kwargs ('dest')
            # else we'll use the last arg name as destination
            arg_name = kwargs.get(
                'dest', args[-1].lstrip('-').replace('-', '_'))
            try:
                # we try to get the command index.
                idx = func.__named__.index(arg_name)
                # and delete it from the named list
                del func.__named__[idx]
                # and delete it from the arguments list
                del func.__arguments__[idx]
            except ValueError:
                pass
            # append the args and kwargs to the function arguments list
            func.__arguments__.append((args, kwargs,))
        if func.__cls__ is None and isinstance(func, types.FunctionType):
            # if the function don't have a class and is a FunctionType
            # we'll add it directly to he commands list.
            ap_ = ArgParseInator(skip_init=True)
            if func.__cmd_name__ not in ap_.commands:
                # we'll add it if not exists
                ap_.commands[func.__cmd_name__] = func
        return func
    return decorate
1046784
@SuppressWarnings("unchecked")
    private static Function<Service<HttpRequest, HttpResponse>,
            ? extends Service<HttpRequest, HttpResponse>> newDecorator(Decorator decorator) {
        return service -> service.decorate(getInstance(decorator, DecoratingServiceFunction.class));
    }
829820
def mock_decorator(*a, **k):
    
    # This is a decorator without parameters, e.g.
    #
    # @login_required
    # def some_view(request):
    #     ...
    #
    if a:
        # This could fail in the instance where a callable argument is passed
        # as a parameter to the decorator!
        if callable(a[0]):
            def wrapper(*args, **kwargs):
                return a[0](*args, **kwargs)
            return wrapper

    # This is a decorator with parameters, e.g.
    #
    # @render_template("index.html")
    # def some_view(request):
    #     ...
    #
    def real_decorator(function):
        def wrapper(*args, **kwargs):
            return function(*args, **kwargs)
        return wrapper
    return real_decorator
948639
def default(*args, **kwargs):
    
    default = kwargs.get('default', None)
    for arg in args:
        if arg:
            return arg
    return default