Function that makes sure functional counter values survive pg_stat_reset calls.
490610
Double resettableFunctionalCounter(String functionalCounterKey, DoubleSupplier function) {
        Double result = function.getAsDouble();
        Double previousResult = previousValueCacheMap.getOrDefault(functionalCounterKey, 0D);
        Double beforeResetValue = beforeResetValuesCacheMap.getOrDefault(functionalCounterKey, 0D);
        Double correctedValue = result + beforeResetValue;

        if (correctedValue < previousResult) {
            beforeResetValuesCacheMap.put(functionalCounterKey, previousResult);
            correctedValue = previousResult + result;
        }
        previousValueCacheMap.put(functionalCounterKey, correctedValue);
        return correctedValue;
    }
1185168
def std_check_in(dataset, name, allowed_vals):
    
    if not hasattr(dataset, name):
        return 0

    ret_val = 1
    if getattr(dataset, name) in allowed_vals:
        ret_val += 1

    return ret_val
931084
def after_func_accept_retry_state(fn):
    """"""
    if not six.callable(fn):
        return fn

    if func_takes_retry_state(fn):
        return fn

    @_utils.wraps(fn)
    def wrapped_after_sleep_func(retry_state):
        # func, trial_number, trial_time_taken
        warn_about_non_retry_state_deprecation('after', fn, stacklevel=4)
        return fn(
            retry_state.fn,
            retry_state.attempt_number,
            retry_state.seconds_since_start)
    return wrapped_after_sleep_func
175604
def _ensure_counter(self):
        """"""
        if not isinstance(self.sync_counter, self._SynchronizationManager):
            self.sync_counter = self._SynchronizationManager()
183255
function ensureTimestamps(columns, allowSyncedAt) {
  var now = Date.now();
  if (!allowSyncedAt || !columns.syncedAt) {
    columns.syncedAt = now;
  }
  if (!columns.createdAt) {
    // Take the value from the client, if present:
    columns.createdAt = columns.updatedAt;
  }
}
84422
def _ensure_global(self, values=None):
        
        if self._gpayload is None:
            self._gpayload = values or {}
        self.enable()
1104439
def consumer_stats_counter():
        
        return {
            process.Process.ERROR: 0,
            process.Process.PROCESSED: 0,
            process.Process.REDELIVERED: 0
        }
444550
def incr(self, att, val=1):
        """"""
        if att not in self.counters:
            raise ValueError("%s is not a counter.")
        self.db.hincrby(self.key(), att, val)
528434
def _check_count(self, result, func, args):
        #pylint: disable=unused-argument
        
        if result == 0:
            raise ctypes.WinError(ctypes.get_last_error())
        return args
90057
def do_counter_reset(self, element, decl, pseudo):
        """"""
        step = self.state[self.state['current_step']]
        counter_name = ''
        for term in decl.value:
            if type(term) is ast.WhitespaceToken:
                continue

            elif type(term) is ast.IdentToken:
                if counter_name:
                    step['counters'][counter_name] = 0
                counter_name = term.value

            elif type(term) is ast.LiteralToken:
                if counter_name:
                    step['counters'][counter_name] = 0
                    counter_name = ''

            elif type(term) is ast.NumberToken:
                if counter_name:
                    step['counters'][counter_name] = int(term.value)
                    counter_name = ''

            else:
                log(WARN, u"Unrecognized counter-reset term {}"
                    .format(type(term)).encode('utf-8'))
        if counter_name:
            step['counters'][counter_name] = 0
391265
def _count_counters(self, counter):
        
        if getattr(self, 'as_set', False):
            return len(set(counter))
        else:
            return sum(counter.values())
418563
def _locked(func):
    """"""
    def _locking(self, *args, **kwargs):
        try:
            self.lock()
            return func(self, *args, **kwargs)
        finally:
            self.unlock()
    return _locking
1190762
function Sustained (obs, timeThreshold, checkUpdateImmediately) {
  var outputValue = Value(obs())
  var lastValue = null
  var timer = null

  return computed(outputValue, v => v, {
    onListen: () => watch(obs, onChange)
  })

  function onChange (value) {
    if (checkUpdateImmediately && checkUpdateImmediately(value)) {
      clearTimeout(timer)
      update()
    } else if (value !== lastValue) {
      clearTimeout(timer)
      var delay = typeof timeThreshold === 'function' ? timeThreshold(value, outputValue()) : timeThreshold
      timer = setTimeout(update, delay)
    }
    lastValue = value
  }

  function update () {
    var value = obs()
    if (value !== outputValue()) {
      outputValue.set(value)
    }
  }
}
1045924
private function _processFunctionStatement() {
		// Increment the number of functions
		$this->_ncssTotalFunctions ++;
		$this->_ncssFileFunctions ++;

		// Reset the default values
		$this->funcArgString = "";
		$this->_nbFunctionParameters = 0;
		$this->_functionParameters = array();
		$this->_inFunctionStatement = true;
		$this->_functionReturns = false;
		$this->_functionThrows = false;
		$this->_inControlStatement = false;
		$this->_currentStatement = false;
		$this->_inClassStatement = false;
		$this->_inInterfaceStatement = false;
		$this->_functionVisibility = 'PUBLIC';
		$this->_functionStatic = false;

		// Detect the visibility (on the token just before the current one).
		$previousToken = $this->tokenizer->peekPrvsValidToken();
		$this->_detectVisibility($previousToken);
		if ($previousToken->position > 1) {
			$prepreviousToken = $this->tokenizer->peekPrvsValidToken($previousToken->position - 1);
			$this->_detectVisibility($prepreviousToken);
		}

		// Find the function name
		$currentToken = $this->tokenizer->getCurrentToken();
		$curlyOpeningDetected = $this->tokenizer->checkNextToken(T_PARENTHESIS_OPEN);
		$nameDetected = null;
		while ($currentToken !== null && !$curlyOpeningDetected) {
			// Skip the token
			$this->tokenizer->getNextToken();
			$currentToken = $this->tokenizer->getCurrentToken();

			if ($currentToken->id === T_STRING) {
				$nameDetected = $currentToken->text;
			}
			$curlyOpeningDetected = $this->tokenizer->checkNextValidToken(T_PARENTHESIS_OPEN);
		}

		// currentToken should end up being the function name token

		// Tracking the function's name.
		if ($nameDetected !== null && trim($nameDetected) !== "") {
			$functionName = $currentToken->text;

			// Check the PHPDoc presence
			$this->_checkDocExists(T_FUNCTION);
		} else {
			// We have an anonymous function or closure.
			$functionName = 'anonymous';
			$this->_functionVisibility = 'ANONYMOUS';

			// We don't check the PHPDoc for anonymous functions
		}
		$this->_currentFunctionName = $functionName;

		// If the function is private we add it to the list of function to use (and store the line number)
		if ($this->_functionVisibility === 'PRIVATE') {
			$this->_privateFunctions[$functionName] = $functionName;
			$this->_privateFunctionsStartLines[$functionName] = $currentToken->line;
		}

		// Function is a constructor
		$constructorNamingStyle = $this->_config->getTestProperty('constructorNaming', 'naming');
		$useOldConstructorNamingStyle = ($constructorNamingStyle === 'old');
		$useNewConstructorNamingStyle = ($constructorNamingStyle === 'new');
		if (strtolower($functionName) === "__construct" && $this->_isActive('constructorNaming') && $useOldConstructorNamingStyle) {
			$msg = $this->_getMessage('CONSTRUCTOR_NAMING', $this->_currentClassname);

			$this->_writeError('constructorNaming', $msg);
		}

		// Special functions are not checked
		if (!in_array($functionName, $this->_specialFunctions)) {

			// Constructors
			if ($functionName === $this->_currentClassname) {

				// Function is a constructor
				if ($this->_isActive('constructorNaming') && $useNewConstructorNamingStyle) {
					$msg = $this->_getMessage('CONSTRUCTOR_NAMING', '__construct()');
					$this->_writeError('constructorNaming', $msg);
				}
			} else {

				// Other function
				if ($this->_functionVisibility === 'PRIVATE') {
					$this->_checkPrivateFunctionNaming($this->_currentFunctionName);
				} else if ($this->_functionVisibility === 'PROTECTED') {
					$this->_checkProtectedFunctionNaming($this->_currentFunctionName);
				} else {
					$this->_checkFunctionNaming($this->_currentFunctionName);
				}
			}
		}

		// List the arguments of the currently analyzed function.
		// Check the order of the parameters of the function.
		// The parameters having a default value should be in last position.
		$foundDefaultValues = false;
		$functionTokenPosition = $this->tokenizer->getCurrentPosition();

		$functionParamsStart = $this->tokenizer->findNextStringPosition('(', $functionTokenPosition);
		$functionParamsStop = $this->tokenizer->findClosingParenthesisPosition($functionTokenPosition);

		for ($i = $functionParamsStart; $i < $functionParamsStop; $i ++) {
			$functionToken = $this->tokenizer->peekTokenAt($i);

			// Current token is a parameter
			if ($this->tokenizer->checkToken($functionToken, T_VARIABLE)) {
				$this->_nbFunctionParameters ++;
				$parameterName = $functionToken->text;
				$this->_functionParameters[$parameterName] = "unused"; // We flag the parameter as unused

				// Check is this parameter as a default value
				$nextTokenInfo = $this->tokenizer->peekNextValidToken($i + 1);
				$hasDefaultValue = $this->tokenizer->checkToken($nextTokenInfo, T_EQUAL);
				if ($hasDefaultValue) {
					$foundDefaultValues = true;
				}

				// Check if the parameter has a default value
				if ($this->_isActive('defaultValuesOrder')) {
					if ($foundDefaultValues && !$hasDefaultValue) {
						$this->_writeError('defaultValuesOrder', $this->_getMessage('FUNC_DEFAULTVALUE_ORDER'));
						break;
					}
				}
			}
		}

		// Test for the max number of parameters
		if ($this->_isActive('functionMaxParameters')) {
			$paramCount = $this->_nbFunctionParameters;
			$maxParams = $this->_config->getTestProperty('functionMaxParameters', 'maxParameters');
			if ($paramCount > $maxParams) {
				$msg = $this->_getMessage('MAX_PARAMETERS', $this->_currentFunctionName, $paramCount, $maxParams);
				$this->_writeError('functionMaxParameters', $msg);
			}
		}
	}
1273975
def register_nonzero_counter(network, stats):
  
  if hasattr(network, "__counter_nonzero__"):
    raise ValueError("nonzero counter was already registered for this network")

  if not isinstance(stats, dict):
    raise ValueError("stats must be a dictionary")

  network.__counter_nonzero__ = stats
  handles = []
  for name, module in network.named_modules():
    handles.append(module.register_forward_hook(_nonzero_counter_hook))
    if network != module:
      if hasattr(module, "__counter_nonzero__"):
        raise ValueError("nonzero counter was already registered for this module")

      child_data = dict()
      network.__counter_nonzero__[name] = child_data
      module.__counter_nonzero__ = child_data

  network.__counter_nonzero_handles__ = handles
531620
def counter(self, counter_name, default=0):
    
    return self._state.counters_map.get(counter_name, default)
31776
def enforce_reset(self):
        

        ub = (self.ubnd * (1.0+self.bound_tol)).to_dict()
        lb = (self.lbnd * (1.0 - self.bound_tol)).to_dict()
        #for iname,name in enumerate(self.columns):
            #self.loc[self.loc[:,name] > ub[name],name] = ub[name] * (1.0 + self.bound_tol)
            #self.loc[self.loc[:,name] < lb[name],name] = lb[name].copy() * (1.0 - self.bound_tol)
        #    self.loc[self.loc[:,name] > ub[name],name] = ub[name]
        #    self.loc[self.loc[:,name] < lb[name],name] = lb[name]

        val_arr = self.values
        for iname, name in enumerate(self.columns):
            val_arr[val_arr[:,iname] > ub[name],iname] = ub[name]
            val_arr[val_arr[:, iname] < lb[name],iname] = lb[name]