Decorator to mark a method as the handler for a particular VCS.
17540
def register_vcs_handler(vcs, method):  # tyoe: (str, str) -> typing.Callable  # decorator
    """"""
    def decorate(f):
        """Store f in HANDLERS[vcs][method]."""
        if vcs not in HANDLERS:
            HANDLERS[vcs] = {}
        HANDLERS[vcs][method] = f
        return f
    return decorate
1327770
def wrap_handler(self, api_types, methods, endpoints):
        

        def wrapper(fn):
            @wraps(fn)
            def wrapped(*args, **kwargs):
                return fn(*args, **kwargs)

            for api_type in api_types:
                for method in methods:
                    for endpoint in endpoints:
                        key = (api_type, method, endpoint)
                        self._handler_chains.setdefault(key, [])
                        self._handler_chains[key].append(wrapped)
            return wrapped

        return wrapper
1374675
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
    defaultargs, defaults = '', ()
    if inspect.isclass(caller):
        name = caller.__name__.lower()
        doc = 'decorator(%s) converts functions/generators into ' \
            'factories of %s objects' % (caller.__name__, caller.__name__)
    elif inspect.isfunction(caller):
        if caller.__name__ == '<lambda>':
            name = '_lambda_'
        else:
            name = caller.__name__
        doc = caller.__doc__
        nargs = caller.__code__.co_argcount
        ndefs = len(caller.__defaults__ or ())
        defaultargs = ', '.join(caller.__code__.co_varnames[nargs-ndefs:nargs])
        if defaultargs:
            defaultargs += ','
        defaults = caller.__defaults__
    else:  # assume caller is an object with a __call__ method
        name = caller.__class__.__name__.lower()
        doc = caller.__call__.__doc__
    evaldict = dict(_call=caller, _decorate_=decorate)
    dec = FunctionMaker.create(
        '%s(func, %s)' % (name, defaultargs),
        'if func is None: return lambda func:  _decorate_(func, _call, (%s))\n'
        'return _decorate_(func, _call, (%s))' % (defaultargs, defaultargs),
        evaldict, doc=doc, module=caller.__module__, __wrapped__=caller)
    if defaults:
        dec.__defaults__ = (None,) + defaults
    return dec
243432
def __handler(self, connection, event):
        
        try:
            # Find local handler
            method = getattr(self, "on_{0}".format(event.type))
        except AttributeError:
            pass
        else:
            try:
                # Call it
                return method(connection, event)
            except Exception as ex:
                logging.exception("Error calling handler: %s", ex)
568278
def decorate_all_methods(decorator):
  
  def decorate_class(cls):
    for name, m in inspect.getmembers(cls, inspect.ismethod):
      if name != "__init__":
        setattr(cls, name, decorator(m))
    return cls
  return decorate_class
323406
def thread_safe(method):
    

    @functools.wraps(method)
    def _locker(self, *args, **kwargs):
        assert hasattr(self, 'lock'), \
            'thread_safe decorator applied to method {0}.{1}: missing required field {0}.lock'\
            .format(self.__class__.__name__, method.__name__)

        try:
            self.lock.acquire()
            return method(self, *args, **kwargs)
        finally:
            try:
                self.lock.release()
            except:
                sys.stderr.write('Exception on releasing lock at method {0}'.format(method.__name__))
                traceback.print_exc(file=sys.stderr)

    return _locker
348633
def decorator(self, func):
        
        if inspect.isfunction(func):
            func._methodview = self
        elif inspect.ismethod(func):
            func.__func__._methodview = self
        else:
            raise AssertionError('Can only decorate function and methods, {} given'.format(func))
        return func
560828
def is_handler_subclass(cls, classnames=("ViewHandler", "APIHandler")):
    """"""
    if isinstance(cls, list):
        return any(is_handler_subclass(c) for c in cls)
    elif isinstance(cls, type):
        return any(c.__name__ in classnames for c in inspect.getmro(cls))
    else:
        raise TypeError(
            "Unexpected type `{}` for class `{}`".format(
                type(cls),
                cls
            )
        )
1316666
def system_methodHelp(self, method_name):
        """"""

        method = None
        if method_name in self.funcs:
            method = self.funcs[method_name]
        elif self.instance is not None:
            # Instance can implement _methodHelp to return help for a method
            if hasattr(self.instance, '_methodHelp'):
                return self.instance._methodHelp(method_name)
            # if the instance has a _dispatch method then we
            # don't have enough information to provide help
            elif not hasattr(self.instance, '_dispatch'):
                try:
                    method = resolve_dotted_attribute(
                                self.instance,
                                method_name,
                                self.allow_dotted_names
                                )
                except AttributeError:
                    pass

        # Note that we aren't checking that the method actually
        # be a callable object of some kind
        if method is None:
            return ""
        else:
            return pydoc.getdoc(method)
176494
def handler ( method )
      raise TypeError,  error_message(method, __method__) unless method.instance_of? Method
      @handler = method
    end
1211381
def call(method, *args, **kwargs):
    '''
    
    '''
    kwargs = clean_kwargs(**kwargs)
    if not netmiko_device['always_alive']:
        connection = ConnectHandler(**netmiko_device['args'])
        ret = getattr(connection, method)(*args, **kwargs)
        connection.disconnect()
        return ret
    return getattr(netmiko_device['connection'], method)(*args, **kwargs)
281307
def XXX_REMOVEME(func):
    
    @wraps(func)
    def decorator(self, *args, **kwargs):
        msg = "~~~~~~~ XXX REMOVEME marked method called: {}.{}".format(
            self.__class__.__name__, func.func_name)
        raise RuntimeError(msg)
        return func(self, *args, **kwargs)
    return decorator
1173079
def _hook_decorator(self, addr, length=0, kwargs=None):
        

        def hook_decorator(func):
            self.hook(addr, func, length=length, kwargs=kwargs)
            return func

        return hook_decorator
975940
def add_handler(self, f):
        
        if f.__name__.startswith('rpc_'):
            raise ValueError("Server method names cannot start with rpc_.")
        self._json_rpc_methods[f.__name__] = f
        return f
776072
def handler(self, scheme_name=None):
		
		if scheme_name is None:
			return self.__default_handler_cls
		for handler in self.__handlers_cls:
			if handler.scheme_specification().scheme_name() == scheme_name:
				return handler
69341
async def _wrap_ws(self, handler, *args, **kwargs):
        '''  '''
        try:
            method = self.request_method()
            # call the wrapped handler
            data = await handler(self, *args, **kwargs)
            status = self.responses.get(method, OK)
            response = {
                'type': 'response',
                'key': getattr(self.request, 'key', None),
                'status': status,
                'payload': data
            }
        except Exception as ex:
            response = {
                'type': 'response',
                'key': getattr(self.request, 'key', None),
                'status': getattr(ex, 'status', 500),
                'payload': getattr(ex, 'msg', 'general error')
            }
        # return a formatted response object
        return self.format(method, response)
936716
def callwith(context_manager):
    
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwds):
            with context_manager:
                return func(*args, **kwds)
        return wrapper
    return decorator