Given a class definition and a decorator that acts on methods,
    applies that decorator to the class' __init__ method.
    Useful for decorating __init__ while still allowing __init__ to be
    inherited.
18188
def decorate_init(init_decorator):
    

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

    return class_decorator
31387
def handle
      return unless engine?
      return if decorators.empty?

      validate_decorators!
      validate_pattern_matching!

      engine.add_method_decorator(method_type, method_name, decorator)
      mark_pattern_matching_decorators
      method_reference.make_alias(target)
      redefine_method
    end
815303
def method_cache(by='value',method='run'):
    """"""

    def decorate_(func):
        def decorate(*args, **kwargs):
            model = args[0] # Assumed to be self.
            assert hasattr(model,method), "Model must have a '%s' method."%method
            if func.__name__ == method: # Run itself.
                method_args = kwargs
            else: # Any other method.
                method_args = kwargs[method] if method in kwargs else {}
            if not hasattr(model.__class__,'cached_runs'): # If there is no run cache.
                model.__class__.cached_runs = {} # Create the method cache.
            cache = model.__class__.cached_runs
            if by == 'value':
                model_dict = {key:value for key,value in list(model.__dict__.items()) \
                              if key[0]!='_'}
                method_signature = SciUnit.dict_hash({'attrs':model_dict,'args':method_args}) # Hash key.
            elif by == 'instance':
                method_signature = SciUnit.dict_hash({'id':id(model),'args':method_args}) # Hash key.
            else:
                raise ValueError("Cache type must be 'value' or 'instance'")
            if method_signature not in cache:
                print("Method with this signature not found in the cache. Running...")
                f = getattr(model,method)
                f(**method_args)
                cache[method_signature] = (datetime.now(),model.__dict__.copy())
            else:
                print("Method with this signature found in the cache. Restoring...")
                _,attrs = cache[method_signature]
                model.__dict__.update(attrs)
            return func(*args, **kwargs)
        return decorate
    return decorate_
1115345
@VisibleForTesting
    static List<DecoratorAndOrder> collectDecorators(Class<?> clazz, Method method) {
        final List<DecoratorAndOrder> decorators = new ArrayList<>();

        // Class-level decorators are applied before method-level decorators.
        collectDecorators(decorators, getAllAnnotations(clazz));
        collectDecorators(decorators, getAllAnnotations(method));

        // Sort decorators by "order" attribute values.
        decorators.sort(Comparator.comparing(DecoratorAndOrder::order));

        return decorators;
    }
186118
def inject_func_as_property(self, func, method_name=None, class_=None):
    
    if method_name is None:
        method_name = get_funcname(func)
    #new_method = func.__get__(self, self.__class__)
    new_property = property(func)
    setattr(self.__class__, method_name, new_property)
1054593
def initialize_class(data, *args, **kwargs):
    
    if isinstance(data, dict):
        import_path = data.get('import_path')
        data.update(kwargs)
        Class = import_module(import_path)

        return Class(*args, **data)
    else:
        Class = import_module(data)

        return Class(*args, **kwargs)
285990
def decorate_method(wrapped):
    
    def wrapper(self):
        lines = Lines()
        if hasattr(self.model, wrapped.__name__):
            print('            . %s' % wrapped.__name__)
            lines.add(1, method_header(wrapped.__name__, nogil=True))
            for line in wrapped(self):
                lines.add(2, line)
        return lines
    functools.update_wrapper(wrapper, wrapped)
    wrapper.__doc__ = 'Lines of model method %s.' % wrapped.__name__
    return property(wrapper)
1337305
def method_caller(method_name, *args, **kwargs):
	
	def call_method(target):
		func = getattr(target, method_name)
		return func(*args, **kwargs)
	return call_method
449087
def decorate(decorator_cls, *args, **kwargs):
    """"""
    global _wrappers

    wrapper_cls = _wrappers.get(decorator_cls, None)
    if wrapper_cls is None:

        class PythonWrapper(decorator_cls):
            pass

        wrapper_cls = PythonWrapper
        wrapper_cls.__name__ = decorator_cls.__name__ + "PythonWrapper"
        _wrappers[decorator_cls] = wrapper_cls

    def decorator(fn):
        wrapped = wrapper_cls(fn, *args, **kwargs)
        _update_wrapper(wrapped, fn)
        return wrapped

    return decorator
766658
def isset(name):
    
    def wrapped(func):
        @functools.wraps(func)
        def _decorator(*args, **kwargs):
            if core.isset(name):
                return func(*args, **kwargs)
        return _decorator
    return wrapped
709389
def classmethod(func):
    
    attr = abc.abstractmethod(func)
    attr.__iclassmethod__ = True
    attr = _classmethod(attr)
    return attr
589930
def delegate(attribute_name, method_names):
    """"""
    # hack for python 2.7 as nonlocal is not available
    info = {
        'attribute': attribute_name,
        'methods': method_names
    }

    def decorator(cls):
        """Decorate class."""
        attribute = info['attribute']
        if attribute.startswith("__"):
            attribute = "_" + cls.__name__ + attribute
        for name in info['methods']:
            setattr(cls, name, eval("lambda self, *a, **kw: "
                                    "self.{0}.{1}(*a, **kw)".format(attribute, name)))
        return cls
    return decorator
368147
def cached(attr):
    
    def decorator(f):
        @functools.wraps(f)
        def decorated(self):
            try:
                return getattr(self, attr)
            except AttributeError:
                value = f(self)
                setattr(self, attr, value)
                return value

        return decorated
    return decorator
1025374
def _make_decorator(measuring_func):
    """"""
    def _decorator(name = None, metric = call_default):
        def wrapper(func):

            name_ = name if name is not None else func.__module__ + '.' +func.__name__
            class instrument_decorator(object): # must be a class for descriptor magic to work
                @wraps(func)
                def __call__(self, *args, **kwargs):
                    return measuring_func(func(*args, **kwargs), name_, metric)

                def __get__(self, instance, class_):
                    name_ = name if name is not None else\
                        ".".join((class_.__module__, class_.__name__, func.__name__))
                    @wraps(func)
                    def wrapped_method(*args, **kwargs):
                        return measuring_func(func(instance, *args, **kwargs), name_, metric)
                    return wrapped_method
            return instrument_decorator()

        return wrapper
    return _decorator
111526
def _wrap(cls, func):
        

        if isinstance(func, cls):
            return func
        return functools.update_wrapper(cls(func), func)
843470
function apply_methods(Class, methods, descriptor) {
           Object.keys(descriptor).forEach(function (method) {
               methods[method] = descriptor[method];

               if (typeof(descriptor[method]) !== "function") {
                   throw new TypeError(
                       "extend: Method `" + method + "` is not a function"
                   );
               }

               Object.defineProperty(Class.prototype, method, {
                   "configurable" : true,
                   "value" : descriptor[method]
               });
           });
       }
245555
def decorator(caller, _func=None):
    """"""
    if _func is not None:  # return a decorated function
        # this is obsolete behavior; you should use decorate instead
        return decorate(_func, caller)
    # else return a decorator function
    if inspect.isclass(caller):
        name = caller.__name__.lower()
        callerfunc = get_init(caller)
        doc = 'decorator(%s) converts functions/generators into ' \
            'factories of %s objects' % (caller.__name__, caller.__name__)
        fun = getfullargspec(callerfunc).args[1]  # second arg
    elif inspect.isfunction(caller):
        if caller.__name__ == '<lambda>':
            name = '_lambda_'
        else:
            name = caller.__name__
        callerfunc = caller
        doc = caller.__doc__
        fun = getfullargspec(callerfunc).args[0]  # first arg
    else:  # assume caller is an object with a __call__ method
        name = caller.__class__.__name__.lower()
        callerfunc = caller.__call__.__func__
        doc = caller.__call__.__doc__
        fun = getfullargspec(callerfunc).args[1]  # second arg
    evaldict = callerfunc.__globals__.copy()
    evaldict['_call_'] = caller
    evaldict['_decorate_'] = decorate
    return FunctionMaker.create(
        '%s(%s)' % (name, fun),
        'return _decorate_(%s, _call_)' % fun,
        evaldict, call=caller, doc=doc, module=caller.__module__,
        __wrapped__=caller)