Decorator that creates AFF4 and RELDB cronjobs from a given mixin.
512250
def DualDBSystemCronJob(legacy_name=None, stateful=False):
  """"""

  def Decorator(cls):
    """Decorator producing 2 classes: legacy style one and a new style one."""
    if not legacy_name:
      raise ValueError("legacy_name has to be provided")

    # Legacy cron jobs have different base classes depending on whether they're
    # stateful or not.
    if stateful:
      aff4_base_cls = StatefulSystemCronFlow
    else:
      aff4_base_cls = SystemCronFlow

    # Make sure that we're dealing with a true mixin to avoid subtle errors.
    if issubclass(cls, cronjobs.SystemCronJobBase):
      raise ValueError("Mixin class shouldn't inherit from SystemCronJobBase")

    if issubclass(cls, aff4_base_cls):
      raise ValueError("Mixin class shouldn't inherit from %s" %
                       aff4_base_cls.__name__)

    # Generate legacy class. Register it within the module as it's not going
    # to be returned from the decorator.
    aff4_cls = compatibility.MakeType(
        legacy_name, (cls, LegacyCronJobAdapterMixin, aff4_base_cls), {})
    module = sys.modules[cls.__module__]
    setattr(module, legacy_name, aff4_cls)

    # Generate new class. No need to register it in the module (like the legacy
    # one) since it will replace the original decorated class.
    reldb_cls = compatibility.MakeType(
        compatibility.GetName(cls), (cls, cronjobs.SystemCronJobBase), {})
    return reldb_cls

  return Decorator
414234
def dual_use_decorator(fn):
    """"""
    @functools.wraps(fn)
    def decorator(*args, **kw):
        if len(args) == 1 and not kw and callable(args[0]):
            return fn()(args[0])
        else:
            return fn(*args, **kw)
    return decorator
821854
def decorator(cls, func_or_class):
        """"""
        resources = getattr(func_or_class, 'resources', [])
        resources.append(cls)
        func_or_class.resources = resources
        return func_or_class
479537
def cache(ignore=None):
    
    def decorator(func):
        # Initialize both cached versions
        joblib_cached = constants.joblib_memory.cache(func, ignore=ignore)
        db_cached = DbMemoizedFunc(func, ignore)

        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            """Dynamically choose the cache at call-time, not at import."""
            if func.__name__ == '_sia' and not config.CACHE_SIAS:
                f = func
            elif config.CACHING_BACKEND == 'fs':
                f = joblib_cached
            elif config.CACHING_BACKEND == 'db':
                f = db_cached
            return f(*args, **kwargs)

        return wrapper
    return decorator
562245
def _at_dump_mixins(self, calculator, rule, scope, block):
        
        sys.stderr.write("%s\n" % repr(rule.namespace._mixins))
332328
def context_factory(apply_globally=False, api=None):
    """"""
    def decorator(context_factory_):
        if apply_globally:
            hug.defaults.context_factory = context_factory_
        else:
            apply_to_api = hug.API(api) if api else hug.api.from_object(context_factory_)
            apply_to_api.context_factory = context_factory_
        return context_factory_
    return decorator
54696
def _api_wrapper(fn):
    """"""

    def _convert(value):
        if isinstance(value, _datetime.date):
            return value.strftime('%s')
        return value

    @_six.wraps(fn)
    def _fn(self, command, **params):
        # sanitize the params by removing the None values
        with self.startup_lock:
            if self.timer.ident is None:
                self.timer.setDaemon(True)
                self.timer.start()
        params = dict((key, _convert(value))
                      for key, value in _six.iteritems(params)
                      if value is not None)

        self.semaphore.acquire()
        resp = fn(self, command, **params)
        try:
            respdata = resp.json(object_hook=_AutoCastDict)
        except:
            # use more specific error if available or fallback to ValueError
            resp.raise_for_status()
            raise Exception('No JSON object could be decoded')

        # check for 'error' then check for status due to Poloniex inconsistency
        if 'error' in respdata:
            raise PoloniexCommandException(respdata['error'])

        resp.raise_for_status()
        return respdata

    return _fn
106777
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()
        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__
    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)
    return FunctionMaker.create(
        '%s(func)' % name, 'return _decorate_(func, _call_)',
        evaldict, doc=doc, module=caller.__module__,
        __wrapped__=caller)
224902
def lazyfunc(func):
    
    closuremem_ = [{}]
    def wrapper(*args, **kwargs):
        mem = closuremem_[0]
        key = (repr(args), repr(kwargs))
        try:
            return mem[key]
        except KeyError:
            mem[key] = func(*args, **kwargs)
        return mem[key]
    return wrapper
51437
def DualDBFlow(cls):
  """"""

  if issubclass(cls, flow.GRRFlow):
    raise ValueError("Mixin class shouldn't inherit from GRRFlow.")

  if cls.__name__[-5:] != "Mixin":
    raise ValueError("Flow mixin should have a name that ends in 'Mixin'.")

  flow_name = cls.__name__[:-5]
  aff4_cls = type(flow_name, (cls, flow.GRRFlow), {})
  aff4_cls.__doc__ = cls.__doc__
  setattr(aff4_flows, flow_name, aff4_cls)

  reldb_cls = type(flow_name, (cls, FlowBase), {})
  reldb_cls.__doc__ = cls.__doc__
  setattr(sys.modules[cls.__module__], flow_name, reldb_cls)

  return cls
1117146
def _timed(_logger=None, level="info"):
    

    def fun_wrapper(f):
        @functools.wraps(f)
        def wraps(*args, **kwargs):
            with _timer(f.__name__, _logger=logger, level=level):
                results = f(*args, **kwargs)
            return results

        return wraps

    return fun_wrapper
352751
def beacons(opts, functions, context=None, proxy=None):
    '''
    
    '''
    return LazyLoader(
        _module_dirs(opts, 'beacons'),
        opts,
        tag='beacons',
        pack={'__context__': context, '__salt__': functions, '__proxy__': proxy or {}},
        virtual_funcs=[],
    )
446636
def wraps(__fn, **kw):
        """"""
        kw['assigned'] = kw.get('assigned', WRAPPER_ASSIGNMENTS)
        return functools.wraps(__fn, **kw)
453626
def job(func_or_queue, connection=None, *args, **kwargs):
    """"""
    decorated_func = _job(func_or_queue, connection=connection, *args, **kwargs)

    if callable(func_or_queue):
        @wraps(decorated_func)
        def wrapper(*args, **kwargs):
            with log.fields(uuid=uuid.uuid4(),
                            job_name=decorated_func.__name__):
                return decorated_func(*args, **kwargs)
        return wrapper
    else:
        def decorator(func):
            @decorated_func
            @wraps(func)
            def wrapper(*args, **kwargs):
                with log.fields(uuid=uuid.uuid4(),
                                job_name=func.__name__):
                    return func(*args, **kwargs)
            return wrapper
        return decorator
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
754652
def map_wrap(f):
    
    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        return f(*args, **kwargs)
    return wrapper
942356
def build_map_threaded(function: Callable[[Any], Any] = None,
                       mode=MODE.CONCURRENT, unpack: bool = False):
    
    _mode = mode

    def _build_map_threaded(function: Callable[[Any], Any]):
        @wraps(function)
        def _wrapper(*args, mode=None, **kwargs) -> MapThreaded:
            if 'unpack' in kwargs:
                raise TypeError('"unpack" has to be defined by decorator')
            if mode is None:
                mode = MODE.CONCURRENT if _mode is None else _mode
            return MapThreaded(function, *args, mode=mode, unpack=unpack,
                               **kwargs)
        return _wrapper

    if function:
        return _build_map_threaded(function)

    return _build_map_threaded