see https://www.bitmex.com/app/restAPI#Request-Rate-Limits
346034
protected <T extends HttpResponseAware> T updateRateLimit(Supplier<T> httpResponseAwareSupplier) {
    if (rateLimitReset != null) {
      long waitMillis = rateLimitReset * 1000 - System.currentTimeMillis();
      if (rateLimitRemaining <= 0 && waitMillis >= 0) {
        throw new ExchangeException(
            "The request is not executed due to rate limit, please wait for "
                + (waitMillis / 1000)
                + " seconds, limit:"
                + rateLimit
                + ", reset: "
                + new Date(rateLimitReset * 1000));
      } else {
        rateLimitRemaining--;
      }
    }
    HttpResponseAware responseAware = null;
    boolean rateLimitsUpdated = false;
    try {
      T result = httpResponseAwareSupplier.get();
      responseAware = result;
      return result;
    } catch (BitmexException e) {
      if (e.getHttpStatusCode() == 429) {
        // we are warned !
        try {
          Integer retryAfter = Integer.valueOf(e.getResponseHeaders().get("Retry-After").get(0));
          rateLimitRemaining = 0;
          rateLimitReset = System.currentTimeMillis() / 1000 + retryAfter;
          rateLimitsUpdated = true;
        } catch (Throwable ignored) {
        }
      } else if (e.getHttpStatusCode() == 403) {
        // we are banned now !
        rateLimitRemaining = 0;
        rateLimitReset = System.currentTimeMillis() / 1000 + 5; // lets be quiet for 5 sec
      }
      responseAware = e;
      throw handleError(e);
    } catch (Exception e) {
      throw handleError(e);
    } finally {
      if (responseAware != null && !rateLimitsUpdated) {
        Map<String, List<String>> responseHeaders = responseAware.getResponseHeaders();
        rateLimit = Integer.valueOf(responseHeaders.get("X-RateLimit-Limit").get(0));
        rateLimitRemaining = Integer.valueOf(responseHeaders.get("X-RateLimit-Remaining").get(0));
        rateLimitReset = Long.valueOf(responseHeaders.get("X-RateLimit-Reset").get(0));
        rateLimitsUpdated = true;
      }
      if (rateLimitsUpdated) {
        RateLimitUpdateListener rateLimitUpdateListener = exchange.getRateLimitUpdateListener();
        if (rateLimitUpdateListener != null) {
          rateLimitUpdateListener.rateLimitUpdate(rateLimit, rateLimitRemaining, rateLimitReset);
        }
      }
    }
  }
428959
def str_max_bit_rate(self):
        
        upstream, downstream = self.max_bit_rate
        return (
            fritztools.format_rate(upstream, unit='bits'),
            fritztools.format_rate(downstream, unit ='bits')
        )
302631
def ratelimits(self):
        
        # can't use a dict comprehension because we want python2.6 support
        r = {}
        keys = filter(lambda x: x.startswith("x-ratelimit-"), self.headers.keys())
        for key in keys:
            r[key.replace("x-ratelimit-", "")] = int(self.headers[key])
        return r
94184
def make_request(self, method, path, headers=None, data='', host=None,
                     auth_path=None, sender=None, override_num_retries=None):
        """"""
        http_request = self.build_base_http_request(method, path, auth_path,
                                                    {}, headers, data, host)
        return self._mexe(http_request, sender, override_num_retries)
1007440
def _ratelimit(self, http_method, url, **kwargs):
        

        def time_since_last_call():
            if self.callsafety['lastcalltime'] is not None:
                return int(time() - self.callsafety['lastcalltime'])
            else:
                return None

        lastlimitremaining = self.callsafety['lastlimitremaining']

        if time_since_last_call() is None or time_since_last_call() >= self.ratelimit_request_interval or \
                lastlimitremaining >= self.ratelimit:
            response = http_method(url, **kwargs)
        else:
            # We hit our limit floor and aren't quite at ratelimit_request_interval value in seconds yet..
            log.warning(
                "Safety Limit Reached of %s remaining calls and time since last call is under %s seconds"
                % (self.ratelimit, self.ratelimit_request_interval)
            )
            while time_since_last_call() < self.ratelimit_request_interval:
                remaining_sleep = int(self.ratelimit_request_interval - time_since_last_call())
                log.debug("  -> sleeping: %s more seconds" % remaining_sleep)
                self.check_ratelimit_budget(1)
                sleep(1)
            response = http_method(url, **kwargs)

        self.callsafety['lastcalltime'] = time()
        self.callsafety['lastlimitremaining'] = int(response.headers.get('X-Rate-Limit-Remaining', 0))
        return response
60788
def _action(self, res):
        """"""
        try:
            j = res.json()
        except:
            res.raise_for_status()
            j = {}

        if 'Retry-After' in res.headers:
            raise HTTPError('403 Forbidden: API rate-limit has been reached until {}.'
                            'See http://freshdesk.com/api#ratelimit'.format(res.headers['Retry-After']))

        if 'require_login' in j:
            raise HTTPError('403 Forbidden: API key is incorrect for this domain')

        if 'error' in j:
            raise HTTPError('{}: {}'.format(j.get('description'),
                                            j.get('errors')))

        # Catch any other errors
        try:
            res.raise_for_status()
        except Exception as e:
            raise HTTPError("{}: {}".format(e, j))

        return j
82500
public function getRateRemainingLimit()
    {
        if (!$this->lastResponse) {
            return null;
        }

        /** @var Header $limit */
        $limit = $this->lastResponse->getHeader('X-Rate-Limit-Remaining');

        return $limit ? $limit->normalize() : null;
    }
801861
def rate_limits(self):
        """"""
        if not self._rate_limits:
            self._rate_limits = utilities.get_rate_limits(self.response)

        return self._rate_limits
542524
def rate_limit(self, name, limit=5, per=60, debug=False):
        
        return RateLimit(self, name, limit, per, debug)
1230325
def ratelimit(key, limit, per=1, redis=None):
    

    if redis is None:
        redis = connections.redis

    # http://redis.io/commands/INCR
    now = int(time.time())

    k = "ratelimit:%s:%s" % (key, now // per)

    with redis.pipeline(transaction=True) as pipeline:
        pipeline.incr(k, 1)
        pipeline.expire(k, per + 10)
        value = pipeline.execute()

    current = int(value[0]) - 1

    if current >= limit:
        return 0
    else:
        return limit - current
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
860541
def setDownloadRateLimit(infoHash, bytesPerSecond)
      raise "download rate limit must be an Integer, not a #{bytesPerSecond.class}" if bytesPerSecond && ! bytesPerSecond.is_a?(Integer)
      @handler.setDownloadRateLimit(infoHash, bytesPerSecond)
    end
654949
def rate_limit(self, rate_limit):
        
        self._rate_limit = bool(rate_limit)
        self._rate_limit_last_call = None
        self.clear_memoized()
286581
def rate_limit_info():
    
    import json
    import time

    r = requests.get(gh_url + "/rate_limit", auth=login.auth())
    out = json.loads(r.text)
    mins = (out["resources"]["core"]["reset"]-time.time())/60
    return out["resources"]["core"]["remaining"], mins
108520
def add_rate_limit(self, limiter):
        
        if limiter not in self.rate_limiters:
            self.subscribe('capacity', limiter.on_capacity)
            self.rate_limiters.append(limiter)
88817
private boolean isRateLimitReached(ResponseEntity<String> response) {
        HttpHeaders header = response.getHeaders();
        List<String> limit = header.get("X-RateLimit-Remaining");
        boolean rateLimitReached =  CollectionUtils.isEmpty(limit) ? false : Integer.valueOf(limit.get(0)) < settings.getRateLimitThreshold();
        if (rateLimitReached) {
            LOG.error("Github rate limit reached. Threshold =" + settings.getRateLimitThreshold() + ". Current remaining ="+Integer.valueOf(limit.get(0)));
        }
        return rateLimitReached;
    }
1070082
def rates(ctx, opts):
    """"""
    click.echo("Retrieving rate limits ... ", nl=False)

    context_msg = "Failed to retrieve status!"
    with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg):
        with maybe_spinner(opts):
            resources_limits = get_rate_limits()

    click.secho("OK", fg="green")

    headers = ["Resource", "Throttled", "Remaining", "Interval (Seconds)", "Reset"]

    rows = []
    for resource, limits in six.iteritems(resources_limits):
        rows.append(
            [
                click.style(resource, fg="cyan"),
                click.style(
                    "Yes" if limits.throttled else "No",
                    fg="red" if limits.throttled else "green",
                ),
                "%(remaining)s/%(limit)s"
                % {
                    "remaining": click.style(
                        six.text_type(limits.remaining), fg="yellow"
                    ),
                    "limit": click.style(six.text_type(limits.limit), fg="yellow"),
                },
                click.style(six.text_type(limits.interval), fg="blue"),
                click.style(six.text_type(limits.reset), fg="magenta"),
            ]
        )

    if resources_limits:
        click.echo()
        utils.pretty_print_table(headers, rows)

    click.echo()

    num_results = len(resources_limits)
    list_suffix = "resource%s" % ("s" if num_results != 1 else "")
    utils.pretty_print_list_info(num_results=num_results, suffix=list_suffix)