Function decorator for incrementing a statsd stat whenever
    a function is invoked.

    >>> from statsdecor.decorators import increment
    >>> @increment('my.metric')
    >>> def my_func():
    >>>     pass
340737
def increment(name, tags=None):
    
    def wrap(f):
        @wraps(f)
        def decorator(*args, **kwargs):
            stats = client()
            ret = f(*args, **kwargs)
            stats.incr(name, tags=tags)
            return ret
        return decorator
    return wrap
964651
def add(self, func, **kwargs):
        

        params = set(kwargs.keys())
        func_params = set(inspect.getargspec(func).args)

        # ignore self, which is present when extending Notebook.
        if 'self' in func_params:
            func_params.remove('self')

        if params != func_params:
            fatal('Params {} not matching cells function params {}'.format(list(params), list(func_params)))

        lines = inspect.getsourcelines(func)[0][1:]

        buffer = ""
        indent_count = None
        inside_markdown = False
        return_found = False

        for line in lines:

            # remove base indentation of function 'func'
            if len(line.strip()) > 0:
                if not indent_count:
                    indent_count = 0
                    for c in line:
                        if c not in [' ', '\t']:
                            break
                        else:
                            indent_count += 1
                line = line[indent_count:]

            if not inside_markdown and line.strip() == "return":
                logging.info('Encountered "return" statement, ignoring the rest of the notebook.')
                break

            if line.strip() == "'''":  # if md block begin/end, or new cell...
                if len(buffer.strip()) > 0:
                    if not inside_markdown:  # if md block begin: new markdown block! flush buffer
                        self.add_cell_code(buffer)
                    else:  # if md block end: markdown block completed! flush buffer
                        self.add_cell_markdown(buffer)
                buffer = ""
                inside_markdown = not inside_markdown
            else:
                buffer += line

        if len(buffer.strip()) > 0:
            if not inside_markdown:
                self.add_cell_code(buffer)
            else:
                self.add_cell_markdown(buffer)

        if len(kwargs) > 0:
            # We have parameters to inject into the notebook.
            # If the first cell is Markdown, assume that is the title and
            # insert parameters as 2nd cell. Otherwise, as 1st cell.
            if len(self.nb['cells']) > 0 and self.nb['cells'][0].cell_type == 'markdown':
                self.add_cell_params(kwargs, 1)
            else:
                self.add_cell_params(kwargs, 0)
111930
def add_func(self, func, *arg, **kwargs):
        

        return self.groupby(level=1, sort=False).apply(func, *arg, **kwargs)
1103644
def trace_decorator(self):
        """"""

        def decorator(func):

            def wrapper(*args, **kwargs):
                self.tracer.start_span(name=func.__name__)
                return_value = func(*args, **kwargs)
                self.tracer.end_span()
                return return_value

            return wrapper

        return decorator
1004567
def trace(f):
    
    @functools.wraps(f)
    def decorator(*args, **kwargs):
        print 'Calling ' + f.func_name + ' in ' + str(args[0])
        return f(*args, **kwargs)
    return decorator
1374655
def decorate(self, func, limit, ttl, *anoop, **kwnoop):
        """"""
        return super(ratelimit, self).decorate(func, limit, ttl, *anoop, **kwnoop)
265246
def statsd_middleware_factory(app, handler):
    """"""
    @coroutine
    def middleware(request):
        """Send stats to statsd."""
        timer = Timer()
        timer.start()

        statsd = yield from app.ps.metrics.client()
        pipe = statsd.pipe()
        pipe.incr('request.method.%s' % request.method)

        try:
            response = yield from handler(request)
            pipe.incr('response.status.%s' % response.status)
            return response

        except HTTPException as exc:
            pipe.incr('response.status.%s' % exc.status_code)
            raise

        except Exception:
            pipe.incr('response.exception')
            raise

        finally:
            timer.stop()
            pipe.timing('response.time', timer.ms)
            pipe.disconnect()

    return middleware
565977
def param(name, help=""):
    """"""
    def decorator(func):
        params = getattr(func, "params", [])
        _param = Param(name, help)
        # Insert at the beginning so the apparent order is preserved
        params.insert(0, _param)
        func.params = params
        return func

    return decorator
92653
public static <I extends Request, O extends Response>
    Function<Service<I, O>, MetricCollectingService<I, O>> newDecorator(
            MeterIdPrefixFunction meterIdPrefixFunction) {

        requireNonNull(meterIdPrefixFunction, "meterIdPrefixFunction");
        return delegate -> new MetricCollectingService<>(delegate, meterIdPrefixFunction);
    }
1262547
def _increment_plugin_stat(self, name, item):
        '''
        
        '''
        item['ts'] = time.time()
        if 'plugins' in self.stats_dict:
            self.logger.debug("Incremented plugin '{p}' plugin stats"\
                    .format(p=name))
            for key in self.stats_dict['plugins'][name]:
                if key == 'lifetime':
                    self.stats_dict['plugins'][name][key].increment(item)
                else:
                    self.stats_dict['plugins'][name][key].increment()
753740
def _onFunction(self, name, line, pos, absPosition,
                    keywordLine, keywordPos,
                    colonLine, colonPos, level,
                    isAsync, returnAnnotation):
        """"""
        self.__flushLevel(level)
        f = Function(name, line, pos, absPosition, keywordLine, keywordPos,
                     colonLine, colonPos, isAsync, returnAnnotation)
        if self.__lastDecorators is not None:
            f.decorators = self.__lastDecorators
            self.__lastDecorators = None
        self.objectsStack.append(f)
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
837807
def counter(module, name, count=1):
    
    counter = get_metric('counters', module, name, Counter())
    counter.inc(count)
478056
def decorator(func):
        """"""

        def function_timer(*args, **kwargs):
            """A nested function for timing other functions."""
            # Capture start time
            start = time.time()

            # Execute function with arguments
            value = func(*args, **kwargs)

            # Capture end time
            end = time.time()

            # Calculate run time
            runtime = end - start
            if runtime < 60:
                runtime = str('sec: ' + str('{:f}'.format(runtime)))
            else:
                runtime = str('min: ' + str('{:f}'.format(runtime / 60)))
            print('{func:50} --> {time}'.format(func=func.__qualname__, time=runtime))
            return value

        return function_timer
85572
def count_calls_with_dims(**dims):
    
    def counter_wrapper(fn):
        @functools.wraps(fn)
        def fn_wrapper(*args, **kwargs):
            counter("%s_calls" %
                    pyformance.registry.get_qualname(fn), **dims).inc()
            return fn(*args, **kwargs)
        return fn_wrapper
    return counter_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
216400
def log_norm(func):
    
    @wraps(func)
    def decorated_func(*args, **kwargs):
        norm, kwargs = format_norm(kwargs)
        kwargs['norm'] = norm
        return func(*args, **kwargs)
    return decorated_func