Apply the rate limiter if none of the exceptions apply and all the
 conditions are met.
324504
def apply_rate_limit?(env)
      @exceptions.none? { |e| e.call(env) } && @conditions.all? { |c| c.call(env) }
    end
1024575
def apply(self, event = None):
  """"""
  for section in self.config.sections():
   # Run through the sections to check all the option values:
   for option, o in self.config.config[section].items():
    # Check the actual values against the validators and complain if necessary:
    if not o['include']:
     continue # This value is hidden, so there's no control for it.
    control = self._controls[section][option] # Get the actual control for GetValue
    try:
     value = type(o['value'])(control.GetValue()) # Try and convert the value
    except ValueError as msg:
     self.displayError(section, option, str(msg)) # Woops, something went wrong
     return False # Tells self.onOk not to close the window
    problem = None # Set up the problem variable.
    try:
     problem = o['validate'](value) # See if it passes the test
    except Exception as e:
     problem = str(e) # The lambda raised an exception.
    if problem:
     self.displayError(section, option, problem) # It didn't
     return False # Tells self.onOk not to close the window
    self.config.set(section, option, value) # All clear
  return True
356339
public void setLimit(int lim) {
        if(0<=lim && lim<=rep.length()) {
            limit=lim;
        } else {
            limit=rep.length();
        }
        reachedLimit=false;
    }
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
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
809665
def rate_limit(client, headers, atexit=False):
    """"""
    if not client or not headers:
        return False

    if not getattr(client.config, "rate_limit", False):
        return False

    rate_info = RateLimitsInfo.from_headers(headers)
    if not rate_info or not rate_info.interval:
        return False

    if rate_info.interval:
        cb = getattr(client.config, "rate_limit_callback", None)
        if cb and callable(cb):
            cb(rate_info, atexit=atexit)
        time.sleep(rate_info.interval)
    return True
1364298
public void validate() {
    if (policy == null) {
      if (value == 0) {
        policy = FillPolicy.ZERO;
      } else if (Double.isNaN(value)) {
        policy = FillPolicy.NOT_A_NUMBER;
      } else {
        policy = FillPolicy.SCALAR;
      }
    } else {
      switch (policy) {
      case NONE:
      case NOT_A_NUMBER:
        if (value != 0 && !Double.isNaN(value)) {
          throw new IllegalArgumentException(
              "The value for NONE and NAN must be NaN");
        }
        value = Double.NaN;
        break;
      case ZERO:
        if (value != 0) {
          throw new IllegalArgumentException("The value for ZERO must be 0");
        }
        value = 0;
        break;
      case NULL:
        if (value != 0 && !Double.isNaN(value)) {
          throw new IllegalArgumentException("The value for NULL must be 0");
        }
        value = Double.NaN;
        break;
      case SCALAR: // it CAN be zero
        break;
      }
    }
  }
47711
def apply_limit(kind, seconds = nil)
      @apply_limit ||= {}
      if seconds
        @apply_limit[kind.to_sym] = seconds.to_i
      end
      @apply_limit[kind.to_sym].to_i
    end
339745
protected function applyElementConditions()
    {
        if ($this->element !== null) {
            $this->andWhere(Db::parseParam('elementId', $this->parseElementValue($this->element)));
        }
    }
1333120
def is_rate_limit_exceeded(self):
        """"""
        history = self.get_history()
        if history.amount_api_calls >= settings.UNSHORTEN_DAILY_LIMIT:
            return True
        return False
231805
public void setDefaultRestrictions() {
        try {
            callDefaultRestrictions();
        } catch (CDKException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
771869
def __set_rate_type(self, value):
        '''
        
        '''
        if value not in [RATE_TYPE_FIXED, RATE_TYPE_PERCENTAGE]:
            raise ValueError("Invalid rate type.")

        self.__rate_type = value
454730
def _raise_deferred_exc(self):
    """"""
    if self._deferred_exception:
      try:
        exc_type, exc_value, exc_traceback = self._deferred_exception
        raise_with_traceback(exc_value, exc_traceback)
      except TypeError:
        # If `_deferred_exception` isn't a 3-item tuple (raising a TypeError on the above
        # destructuring), treat it like a bare exception.
        raise self._deferred_exception
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;
}
791922
protected function shouldThrowExceptionForUnappliedStrategy()
    {
        if ( ! array_key_exists(static::CONFIG_FORCE_APPLY, $this->config)) {
            return false;
        }

        return (bool) $this->config[ static::CONFIG_FORCE_APPLY ];
    }
40584
def clean_limit(self):
        ""
        limit = self.cleaned_data.get('limit', None)
        if (settings.SELECTABLE_MAX_LIMIT is not None and
            (not limit or limit > settings.SELECTABLE_MAX_LIMIT)):
            limit = settings.SELECTABLE_MAX_LIMIT
        return limit
941312
def enforce_policy(rule):
    """"""
    def wrapper(func):
        """Decorator used for wrap API."""
        @functools.wraps(func)
        def wrapped(*args, **kwargs):
            if enforcer.enforce(rule, {}, g.cred):
                return func(*args, **kwargs)

        return wrapped

    return wrapper