Load data from remote store if stale
196882
@Override
    public synchronized boolean load() {
        Either<Void, T> oldData = data;
        long oldModified = modified;
        String oldKey = versionedKey;
        try {
            if (isOutOfDate() || needsData()) {
                String newVersionedKey = reader.getAsString(key)
                                               .orElse(null);
                val loaded = nonAtomicload(newVersionedKey);
                data = Either.right((T) loaded._2());
                modified = loaded._1();
                versionedKey = newVersionedKey;
            } else {
                return false;
            }
        } catch (Throwable e) {
            data = oldData;
            versionedKey = oldKey;
            modified = oldModified;
            logger.info(e.getMessage(), e);
            throw ExceptionSoftener.throwSoftenedException(e);
        }
        return true;
    }
86621
def _wait_for_reader(self):
        """"""
        if self.max_size <= 0:  # Unlimited queue
            return
        if self.write_item_offset - self.cached_remote_offset <= self.max_size:
            return  # Hasn't reached max size
        remote_offset = internal_kv._internal_kv_get(self.read_ack_key)
        if remote_offset is None:
            # logger.debug("[writer] Waiting for reader to start...")
            while remote_offset is None:
                time.sleep(0.01)
                remote_offset = internal_kv._internal_kv_get(self.read_ack_key)
        remote_offset = int(remote_offset)
        if self.write_item_offset - remote_offset > self.max_size:
            logger.debug(
                "[writer] Waiting for reader to catch up {} to {} - {}".format(
                    remote_offset, self.write_item_offset, self.max_size))
            while self.write_item_offset - remote_offset > self.max_size:
                time.sleep(0.01)
                remote_offset = int(
                    internal_kv._internal_kv_get(self.read_ack_key))
        self.cached_remote_offset = remote_offset
855334
function(name, autoFlushExpired) {
        var storeName;

        function __construct(name) {
            try {
                storeName = validateStoreName(name);

                if (autoFlushExpired === undefined || autoFlushExpired !== false) {
                    flushExpired();
                }
            } catch(error) {
                console.error(error);
            }
        }

        /**
         * Set a defined key with the given value
         * @param  {string} key          The name of the value
         * @param  {mixed}  data         The data to store, can be any datatype
         * @param  {int}    [expiresAt]  When should this value expire
         * @return {void}
         */
        function set(key, data, expiresAt) {
            try {
                if (expiresAt !== undefined && typeof expiresAt === 'number') {
                    STORE.setItem(storeName + key + EXPIRE_KEY, expiresAt.toString());
                }

                STORE.setItem(storeName + key, decodeObjectString(data));

                return true;
            } catch(error) {
                console.error(error);
                return false;
            }
        }

        /**
         * Get the value stored under the given key, or the whole store
         * @param  {string} [key] Index defined in @set
         * @return {mixed}        Stored value
         */
        function get(key) {
            try {
                if (key !== undefined) {
                    var result = encodeObjectString(STORE.getItem(storeName + key));
                    return result !== null ? result : false;
                } else {
                    var resultAll = {};

                    Object.keys(STORE).map(function(key) {
                        if (key.indexOf(storeName) === 0 && key.indexOf(EXPIRE_KEY) === -1) {
                            var varKey = key.replace(storeName, '');
                            resultAll[varKey] = get(varKey);
                        }
                    });

                    return resultAll;
                }
            } catch(error) {
                console.error(error)
                return false;
            }
        }

        /**
         * Check if the given key exists in the store
         * @param  {string}  key  index of the value to test
         * @return {boolean}      Key defined or not
         */
        function isset(key) {
            return STORE.getItem(storeName + key) !== null ? true : false;
        }

        /**
         * Flush all values, that are stored in the store instance
         * @return {void}
         */
        function flush() {
            util.flush(storeName);
        }

        /**
         * Remove an item, by the given key and its expire if set
         * @param  {string} key  Index of the value
         * @return {void}
         */
        function remove(key) {
            util.remove(storeName + key);
        }

        /**
         * flush expired values defined in this store
         * @return {void}
         */
        function flushExpired() {
            util.flushExpired(storeName);
        }

        /**
         * generate a store name
         * @param  {string} storeName  The name of the store instance
         * @return {string}            The generated name
         * @throws {TypeError}
         */
        function validateStoreName(storeName) {
            if (storeName === undefined) {
                throw new TypeError('Please provide a storename');
            }

            if (typeof(storeName) !== 'string') {
                throw new TypeError('The storename has to be a string');
            }

            var chargedStoreName = storeName = ROOT + storeName + '-';
            return chargedStoreName;
        }

        /**
         * decode a value if its type is a object
         * @private
         * @param  {mixed}  data  Value to decode
         * @return {mixed}        The decoded value
         */
        function decodeObjectString(data) {
            if (typeof data === 'object') {
                return JSON.stringify(data);
            }

            return data;
        }

        /**
         * encode a value if the value is a object
         * @param  {mixed} data  The value to encode
         * @return {mixed}       The encoded value
         */
        function encodeObjectString(data) {
            if (typeof data === 'string') {
                try {
                    return JSON.parse(data);
                } catch(e) {
                    return data;
                }
            }
        }

        __construct(name);

        // define public interface
        return {
            set    : set,
            get    : get,
            flush  : flush,
            remove : remove,
            isset  : isset
        }
    }
799655
def _persist(self) -> None:
        
        if self._store:
            self._store.save(self._key, self._snapshot)
533110
def reload_stale
      reload_check = should_reload?
      self.last_reload = Time.now

      return if ! reload_check
      reset!

      self.scripts.each do |f|
        debug_log "reload #{f}"
        load f
      end
    end
729000
function saveSync(store, conf) {
  try {
    this.save(store, conf);
  }catch(e) {
    log.warning('failed to save rdb snapshot: %s', e.message);
  }
}
1264413
def _load_data(self, reset=False):
        ''' 
        '''

        log = logging.getLogger("%s.%s" % (self.log_name,
                                           inspect.stack()[0][3]))
        log.setLevel(self.log_level)
        for attr, obj in self.datafile_obj.items():
            if reset or obj['latest_mod'] > obj['last_json_mod']:
                conn = obj['conn']
                sparql = "DROP ALL;"
                if os.path.isdir(obj['cache_path']):
                    shutil.rmtree(obj['cache_path'], ignore_errors=True)
                os.makedirs(obj['cache_path'])
                drop_extensions = conn.update_query(sparql)
                rdf_resource_templates = []
                rdf_data = []
                for path, files in obj['files'].items():
                    for file in files:
                        file_path = os.path.join(path, file)
                        # data = open(file_path).read()
                        # log.info(" uploading file: %s | namespace: %s",
                        #          file,
                        #          conn.namespace)
                        # data_type = file.split('.')[-1]
                        result = conn.load_data(file_path,
                                                #datatype=data_type,
                                                graph=str(getattr(NSM.kdr,
                                                                  file)),
                                                is_file=True)
                        if result.status_code > 399:
                            raise ValueError("Cannot load '{}' into {}".format(
                                file_name, conn))
759392
private void loadAllAndKeepExisting(Set<? extends K> keys) {
    List<K> keysToLoad = keys.stream()
        .filter(key -> !cache.asMap().containsKey(key))
        .collect(toList());
    Map<K, V> result = cacheLoader.get().loadAll(keysToLoad);
    for (Map.Entry<K, V> entry : result.entrySet()) {
      if ((entry.getKey() != null) && (entry.getValue() != null)) {
        putIfAbsentNoAwait(entry.getKey(), entry.getValue(), /* publishToWriter */ false);
      }
    }
  }
1160169
def get_load(jid):
    '''
    
    '''
    with _get_serv(ret=None, commit=True) as cur:

        sql = '''SELECT load FROM jids WHERE jid = %s;'''
        cur.execute(sql, (jid,))
        data = cur.fetchone()
        if data:
            return data[0]
        return {}
704212
private void loadDataFromInternetAndSave() throws IOException {
		InputStream is = null;
		FileOutputStream fos = null;
		try {
			URL url = new URL(DATA_RETRIVE_URL);
			is = url.openStream();
			fos = new FileOutputStream(getCacheFile());
			byte[] buff = new byte[1024 * 8];
			int len = 0;
			while ((len = is.read(buff)) != -1) {
				fos.write(buff, 0, len);
			}
		} finally {
			if (is != null) {
				is.close();
			}
			if (fos != null) {
				fos.close();
			}
		}

	}
1096428
public void store(K key, V loader) {
        // Clean up stale entries on every put.
        // This should avoid a slow memory leak of reference objects.
        cleanUpStaleEntries();
        map.put(key, new WeakKeyedRef<K, V>(key, loader, q));
    }
1068845
def update_stale(self):
        """"""
        # Some events don't post an inactive XML, only active.
        # If we don't get an active update for 5 seconds we can
        # assume the event is no longer active and update accordingly.
        for etype, echannels in self.event_states.items():
            for eprop in echannels:
                if eprop[3] is not None:
                    sec_elap = ((datetime.datetime.now()-eprop[3])
                                .total_seconds())
                    # print('Seconds since last update: {}'.format(sec_elap))
                    if sec_elap > 5 and eprop[0] is True:
                        _LOGGING.debug('Updating stale event %s on CH(%s)',
                                       etype, eprop[1])
                        attr = [False, eprop[1], eprop[2],
                                datetime.datetime.now()]
                        self.update_attributes(etype, eprop[1], attr)
                        self.publish_changes(etype, eprop[1])
590205
def remote():
    """"""
    logger.info("Fetching latest data from PyPI.")
    results = defaultdict(list)
    packages = PackageVersion.objects.exclude(is_editable=True)
    for pv in packages:
        pv.update_from_pypi()
        results[pv.diff_status].append(pv)
        logger.debug("Updated package from PyPI: %r", pv)
    results['refreshed_at'] = tz_now()
    return results
494535
function load(ctx, loader, params, onUpdate) {
    // Create an object that holds the loadedData promise, so we can compare on handleLoadResult, and ignore promises that
    // did not originate from the very last load that happened.
    const loadedData = {
        loading: true, // Start off "loading", but once the promise below resolves, this value is false.
    };

    loadedData.promise = loader(params, handleLoadResult.bind(null, ctx, loadedData, onUpdate, undefined)) // Do not affect loading status.
                                  .then(handleLoadResult.bind(null, ctx, loadedData, onUpdate, false, undefined)) // Success, not loading.
                                 .catch(handleLoadResult.bind(null, ctx, loadedData, onUpdate, false)); // Failed, not loading.

    // Return promise for data.
    return loadedData.promise;
}
1218236
function flushExpired () {
  return storage.keys().then(keys => {
    const cacheKeys = keys.filter(key => key.indexOf(expire) === 0)
    return Promise.all(cacheKeys.map(key => get(key.slice(prefix.length))))
  })
}
1367028
def load(self):
        """"""
        if self.is_persisted:
            with open(self.file_name, 'rb') as f:
                self.object_property = pickle.load(f)
963770
def _itemsLoadedDone(self, data):
        
        if data is None:
            return
        self.continuation   = data.get('continuation', None)
        self.lastUpdated    = data.get('updated', None)
        self.lastLoadLength = len(data.get('items', []))
        self.googleReader.itemsToObjects(self, data.get('items', []))
        self.lastLoadOk = True