Cache stats calls to prevent hammering the API
331600
def cached_read(self, kind):
        """"""
        if not kind in self.cache:
            self.pull_stats(kind)
        if self.epochnow() - self.cache[kind]['lastcall'] > self.cache_timeout:
            self.pull_stats(kind)
        return self.cache[kind]['lastvalue']
1034556
public void onCacheHit(String template, int locality) {
        final String methodName = "onCacheHit()";

        CacheStatsModule csm = null;
        if ((csm = getCSM(template)) == null) {
            return;
        }
        if (tc.isDebugEnabled())
            Tr.debug(tc, methodName + " cacheName=" + _sCacheName + " template=" + template + " locality=" + locality + " enable=" + csm._enable
                    + " parentEnable=" + _enable + " " + this);

        switch (locality) {
        case REMOTE:
            if (csm._enable) {
                if (csm._remoteHitCount != null) {
                    csm._remoteHitCount.increment();
                }
                if (csm._inMemoryAndDiskCacheEntryCount != null) {
                    csm._inMemoryAndDiskCacheEntryCount.increment();
                }
                if (csm._remoteCreationCount != null) {
                    csm._remoteCreationCount.increment();
                }
            }
            break;
        case MEMORY:
            if (csm._enable && csm._hitsInMemoryCount != null)
                csm._hitsInMemoryCount.increment();
            break;
        case DISK:
            if (_csmDisk != null && _csmDisk._enable && _csmDisk._hitsOnDisk != null) {
                _csmDisk._hitsOnDisk.increment();
            }
            if (csm._enable && csm._hitsOnDiskCount != null)
                csm._hitsOnDiskCount.increment();
            break;
        default:
            if (tc.isDebugEnabled())
                Tr.debug(tc, methodName + " Error - Unrecognized locality " + locality + " cacheName=" + _sCacheName);
            break;
        }
        return;
    }
604044
def cleanup(self):
        """"""
        self.num_puts = 0
        cached = []
        for i, url_data in enumerate(self.queue):
            key = url_data.cache_url
            cache = url_data.aggregate.result_cache
            if cache.has_result(key):
                cached.append(i)
        for pos in cached:
            self._move_to_top(pos)
928141
function getCache(key, doesDateMatter, callback) {
    key = key.replace(/\//g, '-');
    var cacheFile = __dirname + '/' + CACHE_PREFIX + key + '.cache';
    fs.exists(cacheFile, function (exists) {
        if (exists) {
            fs.stat(cacheFile, function (err, stats) {
                if (err) {
                    throw err;
                }
                if (!doesDateMatter || (stats.mtime.valueOf() > (new Date().valueOf() - 60 * 60 * 1000))) {
                    // The cache is less than 60 minutes old so return the contents
                    fs.readFile(cacheFile, function (err, data) {
                        if (err) {
                            console.error('Error reading the cache file at ' + cacheFile);
                            throw err;
                        }
                        var dataString = data.toString();
                        var dataObj;
                        try {
                            dataObj = JSON.parse(dataString);
                        } catch(e) {
                            dataObj = null;
                        }

                        callback(dataObj, stats.mtime);
                        return;
                    });
                } else {
                    // The cache is older than 60 minutes
                    callback(null);
                    return;
                }
            });
        } else {
            // The cache doesn't exist
            callback(null);
            return;
        }
    });
}
544353
def collect(self):
        """"""
        for func in self._caches:
            cache = {}
            for key in self._caches[func]:
                if (time.time() - self._caches[func][key][1]) < self._timeouts[func]:
                    cache[key] = self._caches[func][key]
            self._caches[func] = cache
990365
def _cached_request(self, base_url, client_id, client_secret,
                        parameters, **kwargs):
        """"""
        key = (base_url, client_id, tuple(parameters.items()))
        cached = self._cache.get(key, {})

        if not cached.get('access_token') or self._expired(cached):
            cached = yield self._request(base_url, client_id, client_secret,
                                         parameters, **kwargs)
            self._cache[key] = cached
            # Purge cache when adding a new item so it doesn't grow too large
            # It's assumed the cache size is small enough that it's OK to loop
            # over the whole cache regularly. If not, could change this to
            # just pop off the oldest one
            self.purge_cache()

        logging.debug('Using a cached token: %s', cached.get('access_token'))
        raise Return(cached)
790802
public void cacheStatusObjects() {

        cachedStatusObjects = new HashMap<String, byte[]>();

        String statusCode;
        IoBuffer out = IoBuffer.allocate(256);
        out.setAutoExpand(true);

        for (String s : statusObjects.keySet()) {
            statusCode = s;
            StatusObject statusObject = statusObjects.get(statusCode);
            if (statusObject instanceof RuntimeStatusObject) {
                continue;
            }
            serializeStatusObject(out, statusObject);
            out.flip();
            if (log.isTraceEnabled()) {
                log.trace(HexDump.formatHexDump(out.getHexDump()));
            }
            byte[] cachedBytes = new byte[out.limit()];
            out.get(cachedBytes);
            out.clear();
            cachedStatusObjects.put(statusCode, cachedBytes);
        }
        out.free();
        out = null;
    }
740974
def get_cache_stats():
    
    cache_stats = []
    for name, _ in six.iteritems(settings.CACHES):
        cache_backend = caches[name]

        try:
            cache_backend_stats = cache_backend._cache.get_stats()
        except AttributeError:  # this backend doesn't provide stats
            logger.info(
                'The memcached backend "{0}" does not support or '
                'provide stats.'.format(name)
            )
            continue

        for address, stats in cache_backend_stats:
            cache_stats.append(
                {'name': name, 'address': address, 'stats': stats}
            )
    return cache_stats
25971
def gather_parsing_stats(self):
        """"""
        if self.verbose:
            start_time = time.clock()
            try:
                yield
            finally:
                elapsed_time = time.clock() - start_time
                printerr("Time while parsing:", elapsed_time, "seconds")
                if packrat_cache:
                    hits, misses = ParserElement.packrat_cache_stats
                    printerr("Packrat parsing stats:", hits, "hits;", misses, "misses")
        else:
            yield
435955
def cache_last_modified(request, *argz, **kwz):
	''''''
	response, site, cachekey = kwz.get('_view_data') or initview(request)
	if not response: return None
	return response[1]
402652
def cached_unless_authenticated(timeout=50, key_prefix='default'):
    """"""
    def caching(f):
        @wraps(f)
        def wrapper(*args, **kwargs):
            cache_fun = current_cache.cached(
                timeout=timeout, key_prefix=key_prefix,
                unless=lambda: current_cache_ext.is_authenticated_callback())
            return cache_fun(f)(*args, **kwargs)
        return wrapper
    return caching
241158
def apply_caching(response):
    """"""
    for k, v in config.get('HTTP_HEADERS').items():
        response.headers[k] = v
    return response
105566
def cached(key = None, extradata = {}):
	'''  '''

	def decorator(f):

		@wraps(f)
		def wrapper(*args, **kwargs):

			uid = key
			if not uid:
				from hashlib import md5
				arguments = list(args) + [(a, kwargs[a]) for a in sorted(kwargs.keys())]
				uid = md5(str(arguments)).hexdigest()
			if exists(uid):
				debug('Item \'%s\' is cached (%s).' % (uid, cache))
				return get(uid)
			else:
				debug('Item \'%s\' is not cached (%s).' % (uid, cache))
				result = f(*args, **kwargs)
				debug('Caching result \'%s\' as \'%s\' (%s)...' % (result, uid, cache))
				debug('Extra data: ' + (str(extradata) or 'None'))
				put(uid, result, extradata)
				return result
		return wrapper
	return decorator
451730
function swipeTick (cache) {
  const keys = Object.keys(cache.entries)
  if (keys.length > 10000) {
    cache.entries = {}
    console.warn(
      'Cache inMemory reached max (10000) number of entries, all keys now being deleted.'
    )
    return
  }

  const now = Date.now()
  for (let index = 0; index < keys.length; index++) {
    let key = keys[index]
    let entry = cache.entries[key]
    if (now - entry.created > entry.ttl) {
      delete cache.entries[key]
    }
  }
}
805033
private static void collectUidStats(final UniqueId uid,
                                      final StatsCollector collector) {
    collector.record("uid.cache-hit", uid.cacheHits(), "kind=" + uid.kind());
    collector.record("uid.cache-miss", uid.cacheMisses(), "kind=" + uid.kind());
    collector.record("uid.cache-size", uid.cacheSize(), "kind=" + uid.kind());
    collector.record("uid.random-collisions", uid.randomIdCollisions(),
        "kind=" + uid.kind());
    collector.record("uid.rejected-assignments", uid.rejectedAssignments(),
        "kind=" + uid.kind());
  }
612806
def stat(filename, use_cache_only=False):
    """"""
    filename = pyc2py(filename)
    if filename not in file_cache:
        if not use_cache_only: cache_file(filename)
        if filename not in file_cache:
            return None
        pass
    return file_cache[filename].stat
222858
def dirty(self):
      """"""
      return not os.path.exists(self.cachename) or \
            (os.path.getmtime(self.filename) >
             os.path.getmtime(self.cachename))