This is where we apply rate limiting and make the HTTP request.
176934
def _request(self, request, proxies, timeout, verify, **_):
        

        settings = self.http.merge_environment_settings(
            request.url, proxies, False, verify, None)

        self._delay()
        response = self.http.send(
            request, timeout=timeout, allow_redirects=False, **settings)
        self._update(response.headers)

        return response
678211
function makeHttpRequest(next) {
  var start;
  var payload = '#\u00A0#';

  var httpReq = http.request({
    host: 'localhost',
    port: 1337,
    method: 'POST',
    path: '/upper'
  }, function(res) {
    res.setEncoding('utf8'); // VCR will ignore this
    var body = '';
    res.on('data', function(chunk) {
      body += chunk;
    });

    res.on('end', function() {
      var time = Date.now() - start;

      console.log('UNICODE');
      console.log('  status:', res.statusCode);
      console.log('  body  :', body);
      console.log('  time  :', time);

      common.verify(function() {
        body.should.eql(payload);
        common.shouldBeDynamicallyTimed(time);
      });

      console.log();

      next();
    });
  });

  start = Date.now();
  httpReq.end(payload);
}
675358
def do_request(self, request, proxies, timeout, **_):
        """"""
        print('{0} {1}'.format(request.method, request.url))
        response = self.http.send(request, proxies=proxies, timeout=timeout,
                                  allow_redirects=False)
        response.raw = None  # Make pickleable
        return response
11748
function makeHttpRequest(encoding, next) {
  var start = Date.now();

  request(
    {
      url: 'http://localhost:1337/' + encoding,
      method: 'GET',
      headers: {
        'accept-encoding': encoding,
      },
    },
    function(err, data, body) {
      var time = Date.now() - start;

      console.log(encoding.toUpperCase() + ' COMPRESSION:');
      console.log('  status:', data.statusCode);
      console.log('  body  :', body);
      console.log('  time  :', time);

      common.verify(function() {
        data.headers.should.not.have.property('content-encoding');
        body.should.equal('hello, ' + encoding);
      });

      console.log();

      next();
    }
  );
}
1338339
def modify_request(self, http_request=None):
    """"""
    if http_request is None:
      http_request = HttpRequest()
    if http_request.uri is None:
      http_request.uri = Uri()
    # Determine the correct scheme.
    if self.scheme:
      http_request.uri.scheme = self.scheme
    if self.port:
      http_request.uri.port = self.port
    if self.host:
      http_request.uri.host = self.host
    # Set the relative uri path
    if self.path:
      http_request.uri.path = self.path
    if self.query:
      http_request.uri.query = self.query.copy()
    return http_request
875885
function runApp(config) {
  const app = express()
  const token = new Token(config)

  // Configure rate limiting. Allow at most 1 request per IP every 60 sec.
  const opts = {
    points: 1,   // Point budget.
    duration: 60, // Reset points consumption every 60 sec.
  }
  const rateLimiter = new RateLimiterMemory(opts)
  const rateLimiterMiddleware = (req, res, next) => {
    // Rate limiting only applies to the /tokens route.
    if (req.url.startsWith('/tokens')) {
      rateLimiter.consume(req.connection.remoteAddress)
        .then(() => {
          // Allow request and consume 1 point.
          next()
        })
        .catch((err) => {
          // Not enough points. Block the request.
          console.log(`Rejecting request due to rate limiting.`)
          res.status(429).send('<h2>Too Many Requests</h2>')
        })
    } else {
      next()
    }
  }
  // Note: register rate limiting middleware *before* all routes
  // so that it gets executed first.
  app.use(rateLimiterMiddleware)

  // Configure directory for public assets.
  app.use(express.static(__dirname + '/public'))

  // Register the /tokens route for crediting tokens.
  app.get('/tokens', async function (req, res, next) {
    const networkId = req.query.network_id
    const wallet = req.query.wallet
    if (!req.query.wallet) {
      res.send('<h2>Error: A wallet address must be supplied.</h2>')
    } else if (!Web3.utils.isAddress(wallet)) {
      res.send(`<h2>Error: ${wallet} is a malformed wallet address.</h2>`)
      return
    }

    try {
      // Transfer NUM_TOKENS to specified wallet.
      const value = token.toNaturalUnit(NUM_TOKENS)
      const contractAddress = token.contractAddress(networkId)
      const receipt = await token.credit(networkId, wallet, value)
      const txHash = receipt.transactionHash
      console.log(`${NUM_TOKENS} OGN -> ${wallet} TxHash=${txHash}`)

      // Send response back to client.
      const resp = `Credited ${NUM_TOKENS} OGN tokens to wallet ${wallet}<br>` +
                  `TxHash = ${txHash}<br>` +
                  `OGN token contract address = ${contractAddress}`
      res.send(resp)
    } catch (err) {
      next(err) // Errors will be passed to Express.
    }
  })

  // Start the server.
  app.listen(
    config.port || DEFAULT_SERVER_PORT,
    () => console.log(`Origin faucet app listening on port ${config.port}!`))
}
657884
def rate_limit_ensembl_requests(self):
        
        
        current_time = time.time()
        diff_time = current_time - self.prior_time
        
        # sleep until the current rate limit period is finished
        if diff_time < self.rate_limit:
            time.sleep(self.rate_limit - diff_time)
        
        # set the access time to now, for later checks
        self.prior_time = time.time()
1325797
def _handle_rate_exceeded(self, response):  # pragma: no cover
        """"""
        waiting_time = int(response.headers.get("Retry-After", 10))
        time.sleep(waiting_time)
18010
def _http_request(self, method, url, request_kwargs=None):
        

        kwargs = request_kwargs if request_kwargs is not None else {}

        headers = self._request_headers()
        headers.update(self.additional_headers)
        if 'headers' in kwargs:
            headers.update(kwargs['headers'])
        kwargs['headers'] = headers

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

        request_url = self._url(
            url,
            file_upload=kwargs.pop('file_upload', False)
        )

        request_method = getattr(requests, method)
        response = request_method(request_url, **kwargs)

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

        return response
324504
def apply_rate_limit?(env)
      @exceptions.none? { |e| e.call(env) } && @conditions.all? { |c| c.call(env) }
    end
348865
def _delay_for_ratelimits(cls, start):
        """"""
        stop = datetime.now()
        duration_microseconds = (stop - start).microseconds
        if duration_microseconds < cls.REQUEST_TIME_MICROSECONDS:
            time.sleep((cls.REQUEST_TIME_MICROSECONDS - duration_microseconds)
                       / MICROSECONDS_PER_SECOND)
123832
def get_rate_limits(self):
        
        resp, body = self.method_get("/limits")
        rate_limits = body.get("limits", {}).get("rate")
        ret = []
        for rate_limit in rate_limits:
            limits = rate_limit["limit"]
            uri_limits = {"uri": rate_limit["uri"],
                    "limits": limits}
            ret.append(uri_limits)
        return ret
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
1156874
function update( curr, info ) {
	// Initialize rate limit info if this is the first time we have received any rate limit information...
	if ( curr === void 0 ) {
		debug( 'Reset: %s. Remaining: %s.', info.reset, info.remaining );
		return info;
	}
	// Only consider responses having the latest reset time...
	if ( info.reset < curr.reset ) {
		debug( 'Response has an old reset time and does not contain any new rate limit information. Reset: %s. Remaining: %s.', curr.reset, curr.remaining );
		return curr;
	}
	// Account for the rate limit being reset during a query sequence...
	if ( info.reset > curr.reset ) {
		debug( 'Rate limit was reset during query sequence. Reset: %s. Remaining: %s.', info.reset, info.remaining );
		return info;
	}
	// Account for responses having the same reset time arriving out-of-order (i.e., a response indicating a higher remaining limit arriving after a response indicating a lower remaining limit)...
	if ( info.remaining < curr.remaining ) {
		debug( 'Reset: %s. Remaining: %s.', info.reset, info.remaining );
		return info;
	}
	debug( 'Reset: %s. Remaining: %s.', curr.reset, curr.remaining );
	return curr;
}
1123042
function makeRequest () {
    request = self.request.apply(null, args);
    requestMiddleware.use(request);
    request.on("response", function (response) {
      var contentEncoding, gzipper;

      //Only cache successful responses
      if (response.statusCode >= 200 && response.statusCode < 300) {
        response.on('error', function (error) {
          self.handleError(error);
        });
        fs.writeFile(self.cacheDirectory + key + ".json", JSON.stringify(response.headers), function (error) {
          if (error) self.handleError(error);
        });

        responseWriter = fs.createWriteStream(self.cacheDirectory + key);

        responseWriter.on('error', function (error) {
          self.handleError(error);
        });

        contentEncoding = response.headers['content-encoding'] || '';
        contentEncoding = contentEncoding.trim().toLowerCase();

        if (contentEncoding === 'gzip') {
          response.on('error', function (error) {
            responseWriter.end();
          });
          response.pipe(responseWriter);
        } else {
          gzipper = zlib.createGzip();
          response.on('error', function (error) {
            gzipper.end();
          });
          gzipper.on('error', function (error) {
            self.handleError(error);
            responseWriter.end();
          });
          responseWriter.on('error', function (error) {
            response.unpipe(gzipper);
            gzipper.end();
          });
          response.pipe(gzipper).pipe(responseWriter);
        }
      }
    });
    self.emit("request", args[0]);
  }
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", {}))
    }
854246
function EaseRate (opts) {
    EaseRate.superclass.constructor.call(this, opts)

    this.rate = opts.rate
}