Wraps a function that actually accesses the database.
    It injects a session into the method and attempts to handle
    it after the function has run.

    :param method func: The method that is interacting with the database.
968547
def db_access_point(func):
    
    @wraps(func)
    def wrapper(self, *args, **kwargs):
        """
        Wrapper responsible for handling
        sessions
        """
        session = self.session_handler.get_session()
        try:
            resp = func(self, session, *args, **kwargs)
        except Exception as exc:
            self.session_handler.handle_session(session, exc=exc)
            raise exc
        else:
            self.session_handler.handle_session(session)
            return resp
    return wrapper
1025404
def connected(func):
    
    @wraps(func)
    def wrapper(*args, **kwargs):
        self = args[0]
        if not self.connected:
            self.show_output("Not connected.")
        else:
            try:
                return func(*args, **kwargs)
            except APIError:
                self.show_output("ZooKeeper internal error.")
            except AuthFailedError:
                self.show_output("Authentication failed.")
            except NoAuthError:
                self.show_output("Not authenticated.")
            except BadVersionError:
                self.show_output("Bad version.")
            except ConnectionLoss:
                self.show_output("Connection loss.")
            except NotReadOnlyCallError:
                self.show_output("Not a read-only operation.")
            except BadArgumentsError:
                self.show_output("Bad arguments.")
            except SessionExpiredError:
                self.show_output("Session expired.")
            except UnimplementedError as ex:
                self.show_output("Not implemented by the server: %s." % str(ex))
            except ZookeeperError as ex:
                self.show_output("Unknown ZooKeeper error: %s" % str(ex))

    return wrapper
1197838
def cache(cls, func):
        

        @functools.wraps(func)
        def func_wrapper(*args, **kwargs):
            func_key = cls.get_key(func)
            val_cache = cls.get_cache(func_key)
            lock = cls.get_cache_lock(func_key)

            return cls._get_value_from_cache(
                func, val_cache, lock, *args, **kwargs)

        return func_wrapper
745884
def to_method(func):
    
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        """Wrapper function.
        """
        return func(*args[1:], **kwargs)

    return wrapper
313579
function bind (obj, method) {
    var fn = obj[method];
    obj[method] = function () {
      fn.apply(obj, arguments);
    };
  }
33852
def wrap(self, func, delay=0):
        '''
        
        '''
        def wrapped():
            self.start()
            if delay:
                self.sleep(delay)
            x = None
            try:
                x = func()
            except OSError as oserror:
                log.debug('OSError exception:%s', oserror)
                self.oserror = oserror
                raise EasyProcessError(self, 'wrap error!')
            finally:
                self.stop()
            return x
        return wrapped
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
1170204
def wrap_function(self, func):
        

        def f(*args, **kwds):
            self.enable_by_count()
            try:
                result = func(*args, **kwds)
            finally:
                self.disable_by_count()
            return result
        return f
383872
def shutit_method_scope(func):
	
	def wrapper(self, shutit):
		"""Wrapper to call a shutit module method, notifying the ShutIt object.
		"""
		ret = func(self, shutit)
		return ret
	return wrapper
133289
def run(self, func, *func_args, **func__kwargs):
        
        self._func = func
        self._func_args = func_args
        self._func_kwargs = func__kwargs
        return self
869994
def create_function(self, func, name=None, database=None):
        
        if name is None:
            name = func.name
        database = database or self.current_database

        if isinstance(func, udf.ImpalaUDF):
            stmt = ddl.CreateUDF(func, name=name, database=database)
        elif isinstance(func, udf.ImpalaUDA):
            stmt = ddl.CreateUDA(func, name=name, database=database)
        else:
            raise TypeError(func)
        self._execute(stmt)
924033
def run_func(self, func, load):
        '''
        
        '''
        # Don't honor private functions
        if func.startswith('__'):
            # TODO: return some error? Seems odd to return {}
            return {}, {'fun': 'send'}
        # Run the func
        if hasattr(self, func):
            try:
                start = time.time()
                ret = getattr(self, func)(load)
                log.trace(
                    'Master function call %s took %s seconds',
                    func, time.time() - start
                )
            except Exception:
                ret = ''
                log.error('Error in function %s:\n', func, exc_info=True)
        else:
            log.error(
                'Received function %s which is unavailable on the master, '
                'returning False', func
            )
            return False, {'fun': 'send'}
        # Don't encrypt the return value for the _return func
        # (we don't care about the return value, so why encrypt it?)
        if func == '_return':
            return ret, {'fun': 'send'}
        if func == '_pillar' and 'id' in load:
            if load.get('ver') != '2' and self.opts['pillar_version'] == 1:
                # Authorized to return old pillar proto
                return ret, {'fun': 'send'}
            return ret, {'fun': 'send_private', 'key': 'pillar', 'tgt': load['id']}
        # Encrypt the return
        return ret, {'fun': 'send'}
369636
def use(self, func, when='whenever'):
        '''  '''
        #NOTE A middleware Object ?
        # self.use() is usually called from initialize(), so no logger yet
        print('registering middleware {}'.format(func.__name__))
        self.middlewares.append({
            'call': func,
            'name': func.__name__,
            'args': func.func_code.co_varnames,
            'when': when
        })
182553
def _reduce_method(cls, func):
        

        def wrapped_func(self, **kwargs):
            return self.reduce(func, **kwargs)
        return wrapped_func
633372
def open_connection(func):
    
    @wraps(func)
    def wrapped_func(*args, **kwargs):  # pylint: disable=missing-docstring
        if kwargs.get('connection', None) is None:
            try:
                host = kwargs.pop('host')
            except KeyError:
                raise TypeError("one of `connection` or `host` is required "
                                "to query NDS2 server")
            kwargs['connection'] = auth_connect(host, kwargs.pop('port', None))
        return func(*args, **kwargs)
    return wrapped_func
339623
def transactional(func):
    
    @wraps(func)
    def wrapper(*args, **kwargs):
        with transaction():
            return func(*args, **kwargs)
    return wrapper
867545
def callToThread(method):
    
    def func_wrapped(self, *args, **kwargs):
      self.thread.execute_queue.put_nowait((threading.get_ident(), method, args, kwargs))
      return self.waitResult()
    return func_wrapped