Implementation of TokenBucket algorithm to do rate limiting: http://stackoverflow.com/a/668327
@return true if should be rate limited, false if it is OK to send the message
14580
public synchronized boolean isRateLimited() {
        final double rate = TOKEN_BUCKET_RATE.get();
        final double window = TOKEN_BUCKET_WINDOW.get();
        final long current = System.currentTimeMillis();
        final double timePassed = current - tkBktLastCheckTime;

        tkBktLastCheckTime = current;
        tkBktAllowance = tkBktAllowance + timePassed * (rate / window);

        if (tkBktAllowance > rate) {
            tkBktAllowance = rate; //cap max to rate
        }

        if (tkBktAllowance < 1.0) {
            return true;
        }

        tkBktAllowance = tkBktAllowance - 1.0;
        return false;
    }
770196
public boolean isValidToken() {
        try {
//            Response response = wsBase.path(TEST_CONFIGS).request(MediaType.APPLICATION_JSON_TYPE).get();
//            return response.getStatusInfo().getFamily() == Response.Status.Family.SUCCESSFUL;

            LoadZone zone = getLoadZone(LoadZone.AMAZON_US_ASHBURN.uid);
            return zone == LoadZone.AMAZON_US_ASHBURN;
        } catch (Exception e) {
            log.info("API token validation failed: " + e);
        }
        return false;
    }
818018
def rate_limiting_resettime(self):
        
        if self.__requester.rate_limiting_resettime == 0:
            self.get_rate_limit()
        return self.__requester.rate_limiting_resettime
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;
    }
710599
public function isRateLimited(): bool
    {

        if (cache()->get($this->getRateLimitKey()) < $this->getRateLimit())
            return false;

        return true;
    }
202724
private boolean doNextBalanceOp(TreeSet<LoadPair> loadSet) {
        LoadPair mostLoaded = loadSet.pollLast();
        LoadPair leastLoaded = loadSet.pollFirst();

        try {
            //Perfection
            if (mostLoaded.tokens.size() == leastLoaded.tokens.size()) return false;
            //Can't improve on off by one, just end up off by one again
            if (mostLoaded.tokens.size() == (leastLoaded.tokens.size() + 1)) return false;
            int token = mostLoaded.tokens.pollFirst();
            leastLoaded.tokens.add(token);
        } finally {
            loadSet.add(mostLoaded);
            loadSet.add(leastLoaded);
        }
        return true;
    }
204627
function TokenBucket(timespan, limit, { distFactor = 1, factor = 20, spread = 500 / timespan, now = Date.now } = {}) {
  this.now = now;

  this.timespan = timespan;
  // this.givenLimit is the limit given to the constructor, this.limit is the
  // functional limit, accounting for this.distFactor.
  this.givenLimit = limit;
  this.factor = factor;
  this.spread = spread;
  this.timespanIndex = Math.ceil(timespan / factor);
  this.total = 0;
  this.time = -1;
  this.buffer = new Array(this.factor + 1).fill(0);

  this.setDistFactor(distFactor);
}
715983
protected void checkLimits() throws RecorderIOException {
        // too much material before finding end of headers? 
        if (messageBodyBeginMark<0) {
            // no mark yet
            if(position>MAX_HEADER_MATERIAL) {
                throw new RecorderTooMuchHeaderException();
            }
        }
        // overlong?
        if(position>maxLength) {
            throw new RecorderLengthExceededException(); 
        }
        // taking too long? 
        long duration = System.currentTimeMillis() - startTime; 
        duration = Math.max(duration,1); // !divzero
        if(duration>timeoutMs) {
            throw new RecorderTimeoutException(); 
        }
        // need to throttle reading to hit max configured rate? 
        if(position/duration >= maxRateBytesPerMs) {
            long desiredDuration = position / maxRateBytesPerMs;
            try {
                Thread.sleep(desiredDuration-duration);
            } catch (InterruptedException e) {
                logger.log(Level.WARNING,
                        "bandwidth throttling sleep interrupted", e);
            } 
        }
    }
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
856565
@Override
  public boolean incrementToken() throws IOException {
    clearAttributes();
    MtasToken token;
    Integer positionIncrement;
    MtasPayloadEncoder payloadEncoder;
    if (tokenCollectionIterator == null) {
      return false;
    } else if (tokenCollectionIterator.hasNext()) {
      token = tokenCollectionIterator.next();
      // compute info
      positionIncrement = token.getPositionStart() - currentPosition;
      currentPosition = token.getPositionStart();
      payloadEncoder = new MtasPayloadEncoder(token, encodingFlags);
      // set info
      termAtt.append(token.getValue());
      positionIncrementAtt.setPositionIncrement(positionIncrement);
      offsetAtt.setOffset(token.getOffsetStart(), token.getOffsetEnd());
      payloadAtt.setPayload(payloadEncoder.getPayload());
      return true;
    }
    return false;
  }
98166
public void setMaxTokenLength(int maxTokenLength)
    {
        if(maxTokenLength < 1)
            throw new IllegalArgumentException("Max token length must be positive, not " + maxTokenLength);
        if(maxTokenLength <= minTokenLength)
            throw new IllegalArgumentException("Max token length must be larger than the min token length");
        this.maxTokenLength = maxTokenLength;
    }
800419
public function rateLimitReached()
    {
        if ($this->isIpWhitelisted()) {
            return false; // we cannot block whitelisted IPs
        }

        if ($this->isIpBlacklisted()) {
            return true;
        }

        $rateLimit = $this->config->get('BlockThreshold', 0);
        if ($rateLimit < 1) {
            return false; // rate limit not used
        }

        // get the last record that's on the end of the rate limit window
        $rc = LoginRateControlEntity::find(['ip' => $this->ip], ['-timestamp'], 1, $rateLimit);
        if (!$rc) {
            return false;
        }

        $blockTtl = $this->config->get('BlockTimelimit', 1) * 60; // defined in minutes, cast to seconds
        if ((time() - $blockTtl) > 60) {
            return false;
        }

        return true;
    }
367688
private void applyVerticalLimit()
    {
        if (mover.getY() < limitBottom && limitBottom != Integer.MIN_VALUE)
        {
            mover.teleportY(limitBottom);
        }
        else if (mover.getY() > limitTop && limitTop != Integer.MAX_VALUE)
        {
            mover.teleportY(limitTop);
        }
    }
721936
public boolean rateLimited(GoogleJsonError e) {
    ErrorInfo errorInfo = getErrorInfo(e);
    if (errorInfo != null) {
      String domain = errorInfo.getDomain();
      String reason = errorInfo.getReason();
      boolean isRateLimitedOrGlobalDomain =
          USAGE_LIMITS_DOMAIN.equals(domain) || GLOBAL_DOMAIN.equals(domain);
      boolean isRateLimitedReason =
          RATE_LIMITED_REASON_CODE.equals(reason) || USER_RATE_LIMITED_REASON_CODE.equals(reason);
      return isRateLimitedOrGlobalDomain && isRateLimitedReason;
    }
    return false;
  }
1041173
public static RateLimiter createBurstingLimiter(final double rate, final double burstBucketSizeInSeconds) {
        final RateLimiter rateLimiter = new SmoothRateLimiter.SmoothBursty(RateLimiter.SleepingStopwatch.createFromSystemTimer(),
                burstBucketSizeInSeconds /* maxBurstSeconds */);
        rateLimiter.setRate(rate);
        return rateLimiter;
    }
1361939
private int getLargestBucketId() {
        int max = 0;
        int rememberId = -1;
        for (int i = 0; i < numberOfBuckets; i++) {
            Bucket<Data> oldBucket = bucketContainer.getBucket(i);
            if (oldBucket.elementsInBucket > max) {
                max = oldBucket.elementsInBucket;
                rememberId = oldBucket.getBucketId();
            }
        }
        return rememberId;
    }
1316389
private static boolean checkRequestAmount(WireRequest request) {
    boolean sufficientBalance = request.getAmount() < MAX_ALLOWABLE_AMOUNT;

    if (!sufficientBalance) {
      LOG.warning(
          String.format("Rejected excessive request of $%d",
              request.getAmount()));
    }

    return sufficientBalance;
  }