Adds rate limiting information on to the response object
489468
def _handle_response(self, url, res, suppress_empty=True):
        
        result = Connection._handle_response(self, url, res, suppress_empty)
        if 'X-Rate-Limit-Time-Reset-Ms' in res.headers:
            self.rate_limit = dict(ms_until_reset=int(res.headers['X-Rate-Limit-Time-Reset-Ms']),
                                   window_size_ms=int(res.headers['X-Rate-Limit-Time-Window-Ms']),
                                   requests_remaining=int(res.headers['X-Rate-Limit-Requests-Left']),
                                   requests_quota=int(res.headers['X-Rate-Limit-Requests-Quota']))
            if self.rate_limiting_management:
                if self.rate_limiting_management['min_requests_remaining'] >= self.rate_limit['requests_remaining']:
                    if self.rate_limiting_management['wait']:
                        sleep(ceil(float(self.rate_limit['ms_until_reset']) / 1000))
                    if self.rate_limiting_management.get('callback_function'):
                        callback = self.rate_limiting_management['callback_function']
                        args_dict = self.rate_limiting_management.get('callback_args')
                        if args_dict:
                            callback(args_dict)
                        else:
                            callback()

        return result
542524
def rate_limit(self, name, limit=5, per=60, debug=False):
        
        return RateLimit(self, name, limit, per, debug)
450392
def disable_rate_limit_forward
      headers[Protocol::HEADER_API_KEY] = api_key
      headers.delete(Protocol::HEADER_FORWARDED_IP)
      headers.delete(Protocol::HEADER_FORWARDED_API_KEY)
    end
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;
    }
535194
def _on_capacity_data(self, conn, command, kwargs, response, capacity):
        
        if self._analyzing:
            self.consumed_capacities.append((command, capacity))
        if self._query_rate_limit is not None:
            self._query_rate_limit.on_capacity(
                conn, command, kwargs, response, capacity
            )
        elif self.rate_limit is not None:
            self.rate_limit.callback = self._on_throttle
            self.rate_limit.on_capacity(conn, command, kwargs, response, capacity)
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
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
479220
def _http_resp_rate_limited(response):
        
        parsed = parse.urlparse(response.request.url)
        duration = int(response.headers.get('Retry-After', 3))
        LOGGER.warning('Rate Limited by %s, retrying in %i seconds',
                       parsed.netloc, duration)
        return asyncio.sleep(duration)
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);
        }
      }
    }
  }
1303017
function errorRateLimitExceeded(res) {
  var err = new Error('GitHub rate limit exceeded.');
  err.res = res;
  err.remote = 'github-content-api';
  throw err;
}
690445
def _ratelimited_get(self, *args, **kwargs):
        """"""
        with self._ratelimiter:
            resp = self.session.get(*args, **kwargs)

        # It's possible that Space-Track will return HTTP status 500 with a
        # query rate limit violation. This can happen if a script is cancelled
        # before it has finished sleeping to satisfy the rate limit and it is
        # started again.
        #
        # Let's catch this specific instance and retry once if it happens.
        if resp.status_code == 500:
            # Let's only retry if the error page tells us it's a rate limit
            # violation.
            if 'violated your query rate limit' in resp.text:
                # Mimic the RateLimiter callback behaviour.
                until = time.time() + self._ratelimiter.period
                t = threading.Thread(target=self._ratelimit_callback, args=(until,))
                t.daemon = True
                t.start()
                time.sleep(self._ratelimiter.period)

                # Now retry
                with self._ratelimiter:
                    resp = self.session.get(*args, **kwargs)

        return resp
192115
def limit(value = nil, &block)
      chain { criteria.update_request_options size: block || Integer(value) }
    end
1146193
def _update_range(self, response):
        
        header_value = response.headers.get('x-resource-range', '')
        m = re.match(r'\d+-\d+/(\d+)$', header_value)
        if m:
            self._count = int(m.group(1))
        else:
            self._count = None
1322497
def setUploadRateLimit(infoHash, bytesPerSecond)
      raise "upload rate limit must be an Integer, not a #{bytesPerSecond.class}" if bytesPerSecond && ! bytesPerSecond.is_a?(Integer)
      @handler.setUploadRateLimit(infoHash, bytesPerSecond)
    end
199292
def _update_limits_from_api(self):
        
        self.connect()
        logger.info("Querying RDS DescribeAccountAttributes for limits")
        lims = self.conn.describe_account_attributes()['AccountQuotas']
        for lim in lims:
            if lim['AccountQuotaName'] not in self.API_NAME_TO_LIMIT:
                logger.info('RDS DescribeAccountAttributes returned unknown'
                            'limit: %s (max: %s; used: %s)',
                            lim['AccountQuotaName'], lim['Max'], lim['Used'])
                continue
            lname = self.API_NAME_TO_LIMIT[lim['AccountQuotaName']]
            self.limits[lname]._set_api_limit(lim['Max'])
            if len(self.limits[lname].get_current_usage()) < 1:
                self.limits[lname]._add_current_usage(lim['Used'])
        logger.debug('Done setting limits from API.')
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
803065
def _add_response_info(self):
        """"""
        self.charset = httputil.get_charset(self.headers)
        self.set_content_type()
        self.add_size_info()