Wrapper for the HTTP requests,
        rate limit backoff is handled here,
        responses are processed with ResourceBuilder.
183257
def _request(self, method, url, query_or_data=None, **kwargs):
        

        if query_or_data is None:
            query_or_data = {}

        request_method = getattr(self, '_http_{0}'.format(method))
        response = retry_request(self)(request_method)(url, query_or_data, **kwargs)

        if self.raw_mode:
            return response

        if response.status_code >= 300:
            error = get_error(response)
            if self.raise_errors:
                raise error
            return error

        # Return response object on NoContent
        if response.status_code == 204 or not response.text:
            return response

        return ResourceBuilder(
            self,
            self.default_locale,
            response.json()
        ).build()
58242
def process(self, context, data):
        
        context.target_backend = self.requester_mapping[data.requester]
        return super().process(context, data)
119960
function buildRequestor(clientOptions) {
  if(clientOptions.requestor) return clientOptions.requestor;

  var requestorConfig =
    _.pick(clientOptions, 'maxRetryDurationSeconds', 'calcRetryBackoff');

  if(requestorConfig.maxRetryDurationSeconds)
    requestorConfig.maxRetryDurationMillis = requestorConfig.maxRetryDurationSeconds * 1000;

  requestorConfig.logger = buildLogger(clientOptions);

  return require('./lib/utils/httpRequestor.js')
    .create(requestorConfig);
}
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);
        }
      }
    }
  }
1267052
def is_rate_limited(response):
        
        if (response.status_code == codes.too_many_requests and 'Retry-After' in response.headers and
                int(response.headers['Retry-After']) >= 0):
            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
1283725
function done( error, response, data ) {
		var info;
		if ( arguments.length === 1 ) {
			debug( 'No available rate limit information.' );
			return clbk( error );
		}
		debug( 'Request completed.' );

		// Get rate limit information:
		info = ratelimit( response.headers );
		debug( 'Rate limit: %d', info.limit );
		debug( 'Rate limit remaining: %d', info.remaining );
		debug( 'Rate limit reset: %s', (new Date( info.reset*1000 )).toISOString() );

		if ( error ) {
			return clbk( error, null, info );
		}
		clbk( null, data, info );
	}
894173
private static Response wrap(final Response res, final Fallback fbk,
        final Request req) {
        // @checkstyle AnonInnerLengthCheck (50 lines)
        return new Response() {
            @Override
            public Iterable<String> head() throws IOException {
                final long start = System.currentTimeMillis();
                Iterable<String> head;
                try {
                    head = res.head();
                } catch (final HttpException ex) {
                    head = fbk.route(
                        TkFallback.fallback(req, start, ex, ex.code())
                    ).get().head();
                } catch (final Throwable ex) {
                    head = fbk.route(
                        TkFallback.fallback(
                            req, start, ex,
                            HttpURLConnection.HTTP_INTERNAL_ERROR
                        )
                    ).get().head();
                }
                return head;
            }

            @Override
            public InputStream body() throws IOException {
                final long start = System.currentTimeMillis();
                InputStream body;
                try {
                    body = res.body();
                } catch (final HttpException ex) {
                    body = fbk.route(
                        TkFallback.fallback(req, start, ex, ex.code())
                    ).get().body();
                } catch (final Throwable ex) {
                    body = fbk.route(
                        TkFallback.fallback(
                            req, start, ex,
                            HttpURLConnection.HTTP_INTERNAL_ERROR
                        )
                    ).get().body();
                }
                return body;
            }
        };
    }
774515
def _rate_limit_status(self, api=None, mode=None):
        
        if api == None:
            api = self.connectToAPI()

        if mode == None:
            print json.dumps(api.rate_limit_status(), indent=2)
            raw_input("<Press ENTER>")
        else:
            # Testing if we have enough queries
            while True:
                allLimits = api.rate_limit_status()
                if mode == "get_user":
                    limit = allLimits["resources"]["users"]["/users/show/:id"]["limit"]
                    remaining = allLimits["resources"]["users"]["/users/show/:id"]["remaining"]
                    reset = allLimits["resources"]["users"]["/users/show/:id"]["reset"]
                elif mode == "get_followers":
                    limit = allLimits["resources"]["followers"]["/followers/ids"]["limit"]
                    remaining = allLimits["resources"]["followers"]["/followers/ids"]["remaining"]
                    reset = allLimits["resources"]["followers"]["/followers/ids"]["reset"]
                elif mode == "get_friends":
                    limit = allLimits["resources"]["friends"]["/friends/ids"]["limit"]
                    remaining = allLimits["resources"]["friends"]["/friends/ids"]["remaining"]
                    reset = allLimits["resources"]["friends"]["/friends/ids"]["reset"]
                elif mode == "search_users":
                    limit = allLimits["resources"]["users"]["/users/search"]["limit"]
                    remaining = allLimits["resources"]["users"]["/users/search"]["remaining"]
                    reset = allLimits["resources"]["users"]["/users/search"]["reset"]
                else:
                    remaining = 1
                """elif mode == "get_all_docs":
                    limit = allLimits["resources"]REPLACEME["limit"]
                    remaining = allLimits["resources"]REPLACEME["remaining"]
                    reset = allLimits["resources"]REPLACEME["reset"]elif mode == "get_users":
                    limit = allLimits["resources"]REPLACEME["limit"]
                    remaining = allLimits["resources"]REPLACEME["remaining"]
                    reset = allLimits["resources"]REPLACEME["reset"] else:
                    remaining = 1"""
                # Checking if we have enough remaining queries
                if remaining > 0:
                    #raw_input(str(remaining) + " queries yet...")
                    break
                else:
                    waitTime = 60
                    print "No more queries remaining, sleeping for " + str(waitTime) +" seconds..."
                    time.sleep(waitTime)

        return 0
1147118
public boolean rateLimited(Throwable throwable) {
    GoogleJsonResponseException jsonException = getJsonResponseExceptionOrNull(throwable);
    if (jsonException != null) {
      return rateLimited(getDetails(jsonException));
    }
    return false;
  }
1147391
def _http_get(self, url, query):
        

        if not self.authorization_as_header:
            query.update({'access_token': self.access_token})

        response = None

        self._normalize_query(query)

        kwargs = {
            'params': query,
            'headers': self._request_headers()
        }

        if self._has_proxy():
            kwargs['proxies'] = self._proxy_parameters()

        response = requests.get(
            self._url(url),
            **kwargs
        )

        if response.status_code == 429:
            raise RateLimitExceededError(response)

        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
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
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
334436
private static void __serveStream(HttpServletRequest request, HttpServletResponse response, InputStream is, String path, String mime, int bufferSize, long lastModified) throws IOException {
        Map<String, String> reqHeaders = __getRequestHeaderMap(request);

        String queryString = request.getQueryString();
        if (queryString == null) {
            queryString = "";
        }

        // Calculate etag
        String etag = Integer.toHexString((path + lastModified + queryString + is.available()).hashCode());

        // Support (simple) skipping:
        long startFrom = 0;
        long endAt = -1;

        String range = reqHeaders.get("range");
        if (range != null) {
            if (range.startsWith("bytes=")) {
                range = range.substring("bytes=".length());
                int minus = range.indexOf('-');

                if (minus > 0) {
                    startFrom = __parseLong(range.substring(0, minus), 0);
                    endAt = __parseLong(range.substring(minus + 1), -1);
                }
            }
        }

        response.addHeader("Accept-Ranges", "bytes");

        // Change return code and add Content-Range header when skipping is requested
        long fileLen = is.available();
        if (range != null && startFrom >= 0) {
            if (startFrom >= fileLen) {
                response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                response.setContentType("text/plain");
                response.addHeader("Content-Range", "bytes 0-0/" + fileLen);
                response.addHeader("ETag", etag);
            } else {
                if (endAt < 0) {
                    endAt = fileLen - 1;
                }

                long newLen = endAt - startFrom + 1;

                if (newLen < 0) {
                    newLen = 0;
                }

                final long dataLen = newLen;

                is.skip(startFrom);

                response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
                response.setContentType(mime);
                __flush(is, response.getOutputStream(), bufferSize);
                response.addHeader("Content-Length", "" + dataLen);
                response.addHeader("Content-Range", "bytes " + startFrom + "-" + endAt + "/" + fileLen);
                response.addHeader("ETag", etag);
            }
        } else {
            if (etag.equals(reqHeaders.get("if-none-match"))) {
                response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                response.setContentType(mime);
            } else {
                response.setStatus(HttpServletResponse.SC_OK);
                response.setContentType(mime);
                __flush(is, response.getOutputStream(), bufferSize);
                response.addHeader("Content-Length", "" + fileLen);
                response.addHeader("ETag", etag);
            }
        }

    }
1020680
def _api_call(self, path, data={}, http_method=requests.get):
        '''  '''
        log.info('performing api request', path=path)
        response = http_method('/'.join([self.api_url, path]),
                               params={'auth_token': self.api_key},
                               data=data)
        log.debug('{} remaining calls'.format(
            response.headers['x-ratelimit-remaining']))
        return response.json()
103181
def get_rate_limits():
    """"""
    client = get_rates_api()

    with catch_raise_api_exception():
        data, _, headers = client.rates_limits_list_with_http_info()

    ratelimits.maybe_rate_limit(client, headers)

    return {
        k: RateLimitsInfo.from_dict(v)
        for k, v in six.iteritems(data.to_dict().get("resources", {}))
    }