Rate limit implementation. Allows up to `limit` of events every `per`
        seconds.

        See :ref:`rate-limit` for more information.
542524
def rate_limit(self, name, limit=5, per=60, debug=False):
        
        return RateLimit(self, name, limit, per, debug)
1205699
def decorate(self, func, limit=0, ttl=0, *anoop, **kwnoop):
        """"""
        self.limit = int(limit)
        self.ttl = int(ttl)
        return super(RateLimitDecorator, self).decorate(func, target=None, *anoop, **kwnoop)
249825
def check_ratelimit_budget(self, seconds_waited):
        
        if self.ratelimit_budget is not None:
            self.ratelimit_budget -= seconds_waited
            if self.ratelimit_budget < 1:
                raise RatelimitBudgetExceeded("Rate limit budget exceeded!")
987260
function limiter(interval, penaltyInterval) {

  var queue = [],
    lastTrigger = 0,
    penaltyCounter = 0,
    skipCounter = 0,
    timer;

  function now() {
    return Date.now();
  }

  function since() {
    return now() - lastTrigger;
  }

  function currentInterval() {
    return penaltyCounter > 0 ? penaltyInterval : interval;
  }

  function runNow(fn) {
    penaltyCounter = 0;
    fn();
    // wait to the next interval unless told to skip
    // to the next operation immediately
    if (skipCounter > 0) {
      skipCounter = 0;
    }
    else {
      lastTrigger = now();
    }
  }

  function deque() {
    timer = undefined;
    if (since() >= currentInterval()) {
      runNow(queue.shift());
    }
    schedule();
  }

  function schedule() {
    var delay;
    if (!timer && queue.length) {
      delay = currentInterval() - since();
      if (delay < 0) {
        return deque();
      }
      timer = setTimeout(deque, delay);
    }
  }

  function trigger(fn) {
    if (since() >= currentInterval() && !queue.length) {
      runNow(fn);
    } else {
      queue.push(fn);
      schedule();
    }
  }

  function penalty() {
    penaltyCounter += 1;
  }

  function skip() {
    skipCounter += 1;
  }

  function cancel() {
    if (timer) {
      clearTimeout(timer);
    }
    queue = [];
  }

  penaltyInterval = penaltyInterval || 5 * interval;
  return {
    trigger: trigger,
    penalty: penalty,
    skip: skip,
    cancel: cancel
  };
}
612621
public void setLimits(long length, long milliseconds, long rateKBps) {
        maxLength = (length>0) ? length : Long.MAX_VALUE;
        timeoutMs = (milliseconds>0) ? milliseconds : Long.MAX_VALUE;
        maxRateBytesPerMs = (rateKBps>0) ? rateKBps*1024/1000 : Long.MAX_VALUE;
    }
1048439
def set_limits_for_pool(self, pool, **kw):
        
        pool_limits = {}

        for time_period in ["year", "month", "week", "day", "hour"]:
            if time_period not in kw:
                continue

            limit = kw.pop(time_period)
            if limit is not None and not isinstance(limit, (float, int)):
                raise TypeError("%s must be a float or int or None",
                                time_period)
            pool_limits[time_period] = limit

        if kw:
            raise ValueError("Unknown time periods specified: %s" %
                             ", ".join(kw.keys()))

        self.cache.set("LIMIT:%s" % pool, json_dumps(pool_limits))
        return
583961
def init_timer(self, max_value):
    
    self.__max_value = max_value
    self.__prev_tick = time.time()
    self.__unit_per_sec = 0
    self.__unit_per_sec_prev = 0
939068
def sleep_and_retry(func):
    '''
    
    '''
    @wraps(func)
    def wrapper(*args, **kargs):
        '''
        Call the rate limited function. If the function raises a rate limit
        exception sleep for the remaing time period and retry the function.

        :param args: non-keyword variable length argument list to the decorated function.
        :param kargs: keyworded variable length argument list to the decorated function.
        '''
        while True:
            try:
                return func(*args, **kargs)
            except RateLimitException as exception:
                time.sleep(exception.period_remaining)
    return wrapper
194674
def rate_limit(self):
        
        rate_limited_msg = False

        while True:
            is_rate_limited = self.limit.is_rate_limited(uuid)
            if is_rate_limited:
                time.sleep(0.3)  # save hammering redis
                if not rate_limited_msg:
                    self.logger.info('Rate limit active..please wait...')
                    rate_limited_msg = True

            if not is_rate_limited:
                self.logger.info('Rate limit clear.')
                self.limit.attempt(uuid)
                return True
341668
function limit() {
  const args = Array.from(arguments);
  const onChange = get(args, isFunction, noop);
  const error = new Error('Too Many Requests');
  error.status = 429;
  const options = Object.assign({
    err: error,
    mid: 100,
    high: 500,
  }, get(args, isObject));
  debug('limit options:', options);
  const mid = parseInt(options.mid, 10);
  const high = parseInt(options.high, 10);
  if (isNaN(mid) || isNaN((high))) {
    throw new Error('mid and high must be a number');
  }
  if (mid <= 0 || high <= 0) {
    throw new Error('mid and high must gt 0');
  }
  if (mid >= high) {
    throw new Error('high must be gt mid');
  }
  let handlingReqTotal = 0;
  let status = '';
  let throwError = options.throwError;
  /* istanbul ignore else */
  if (isUndefined(throwError)) {
    throwError = true;
  }
  const pass = options.pass || noop;
  return (ctx, next) => {
    function checkStatus() {
      if (handlingReqTotal > high) {
        /* istanbul ignore else */
        if (status !== 'high') {
          status = 'high';
          onChange(status);
        }
        /* istanbul ignore else */
        if (throwError) {
          throw options.err;
        }
      } else if (handlingReqTotal > mid) {
        /* istanbul ignore else */
        if (status !== 'mid') {
          status = 'mid';
          onChange(status);
        }
      } /* istanbul ignore else */ else if (status !== 'low') {
        status = 'low';
        onChange(status);
      }
    }

    function done(err) {
      handlingReqTotal -= 1;
      checkStatus();
      if (err) {
        throw err;
      }
    }
    if (pass(ctx)) {
      return next();
    }

    handlingReqTotal += 1;
    checkStatus();
    return next().then(done, done);
  };
}
638435
def rate_limit_sleeper(api, response):
    
    while response.status_code == 429:
        headers = response.headers
        remaining_time = headers.get('X-RateLimit-Reset')
        sleep = int(remaining_time) - int(time.time())
        logger.warning('Rate limit reached! Waiting for [%s]s', sleep)
        time.sleep(sleep + 5)
        response = api.session.send(response.request)
    return response
1333120
def is_rate_limit_exceeded(self):
        """"""
        history = self.get_history()
        if history.amount_api_calls >= settings.UNSHORTEN_DAILY_LIMIT:
            return True
        return False
625009
def _render_rate_limit_page(self, exception=None):
        
        auth = request.args.get('auth')
        is_auth = auth == '1' if auth else bool(self.auth)
        return render_template('limit.html', is_authenticated=is_auth), 403
587598
def rate_limited(max_per_second):
    
    import datetime
    min_request_time = datetime.timedelta(seconds=max_per_second)
    last_time_called = [None]
    def decorate(func):
        def rate_limited_function(*args, **kwargs):
            if last_time_called[0]:
                delta = datetime.datetime.now() - last_time_called[0]
                if delta < datetime.timedelta.min:
                    raise chrw.exceptions.TimeIsBackToFront, "Call the Doc!"
                elif delta < min_request_time:
                    msg = "Last request was {0}, should be at least {1}".format(
                        delta, min_request_time
                    )
                    raise chrw.exceptions.RequestRateTooHigh, msg
            ret = func(*args, **kwargs)
            last_time_called[0] = datetime.datetime.now()
            return ret
        return functools.update_wrapper(rate_limited_function, func)
    return decorate
814792
def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]:
    """"""
    min_interval = 3600.0 / float(max_per_hour)

    def _decorate(func: Callable[..., Any]) -> Callable[..., Any]:
        things = [func.__name__]
        things.extend(args)
        key = "".join(things)
        LOG.debug(f"Rate limiter called for '{key}'.")
        if key not in LAST_CALLED:
            LOG.debug(f"Initializing entry for '{key}'.")
            LAST_CALLED[key] = 0.0

        def _rate_limited_function(*args: Any, **kargs: Any) -> Any:
            last_called = LAST_CALLED[key]
            now = time.time()
            elapsed = now - last_called
            remaining = min_interval - elapsed
            LOG.debug(f"Rate limiter last called for '{key}' at {last_called}.")
            LOG.debug(f"Remaining cooldown time for '{key}' is {remaining}.")

            if remaining > 0 and last_called > 0.0:
                LOG.info(f"Self-enforced rate limit hit, sleeping {remaining} seconds.")
                for i in tui.progress.bar(range(math.ceil(remaining))):
                    time.sleep(1)

            LAST_CALLED[key] = time.time()
            ret = func(*args, **kargs)
            LOG.debug(f"Updating rate limiter last called for '{key}' to {now}.")
            return ret

        return _rate_limited_function
    return _decorate
377905
def on_for_seconds(self, speed, seconds, brake=True, block=True):
        

        if seconds < 0:
            raise ValueError("seconds is negative ({})".format(seconds))

        speed = self._speed_native_units(speed)
        self.speed_sp = int(round(speed))
        self.time_sp = int(seconds * 1000)
        self._set_brake(brake)
        self.run_timed()

        if block:
            self.wait_until('running', timeout=WAIT_RUNNING_TIMEOUT)
            self.wait_until_not_moving()
582007
def rate_limit(limit: int, key=None):
    

    def decorator(func):
        setattr(func, 'throttling_rate_limit', limit)
        if key:
            setattr(func, 'throttling_key', key)
        return func

    return decorator