Checks own cache for history_id for agent_id and instance_id.
        If information is missing fetch it from database. If it is not there
        create the new record.

        BEWARE: This method runs in a thread.
960135
def _get_history_id(self, connection, agent_id, instance_id):
        '''
        
        '''
        cache_key = (agent_id, instance_id, )
        if cache_key in self._history_id_cache:
            history_id = self._history_id_cache[cache_key]
            return history_id
        else:
            command = text_helper.format_block("""
            SELECT id FROM histories WHERE agent_id = ? AND instance_id = ?
            """)
            cursor = connection.cursor()
            cursor.execute(command, (agent_id, instance_id, ))
            res = cursor.fetchall()
            if res:
                history_id = res[0][0]
                self._history_id_cache[cache_key] = history_id
                return history_id
            else:
                command = 'INSERT INTO histories VALUES (NULL, ?, ?)'
                cursor.execute(command, (agent_id, instance_id, ))
                history_id = cursor.lastrowid
                self._history_id_cache[cache_key] = history_id
                return history_id
1286480
def _cache_update_needed(self, course, taskid):
        
        if not id_checker(taskid):
            raise InvalidNameException("Task with invalid name: " + taskid)

        task_fs = self.get_task_fs(course.get_id(), taskid)

        if (course.get_id(), taskid) not in self._cache:
            return True

        try:
            last_update, __, __ = self._get_last_updates(course, taskid, task_fs, False)
        except:
            raise TaskNotFoundException()

        last_modif = self._cache[(course.get_id(), taskid)][1]
        for filename, mftime in last_update.items():
            if filename not in last_modif or last_modif[filename] < mftime:
                return True

        return False
465361
def as_dash_instance(self, cache_id=None):
        ''
        dash_app = self.stateless_app.as_dash_app() # pylint: disable=no-member
        base = self.current_state()
        return dash_app.do_form_dash_instance(replacements=base,
                                              specific_identifier=self.slug,
                                              cache_id=cache_id)
698118
@GET
    @Path("{id}/history/{start: " + DATE_REGEX + "}-{end: " + DATE_REGEX + "}")
    public Response fetchHistory(@PathParam("id") URI_ID id,
                                 @PathParam("start") Timestamp start,
                                 @PathParam("end") Timestamp end) throws Exception {
        return super.fetchHistory(id, start, end);
    }
368687
def has_offline_historical_manager_or_raise(self):
        
        try:
            model = self.instance.__class__.history.model
        except AttributeError:
            model = self.instance.__class__
        field = [field for field in model._meta.fields if field.name == "history_id"]
        if field and not isinstance(field[0], UUIDField):
            raise OfflineHistoricalManagerError(
                f"Field 'history_id' of historical model "
                f"'{model._meta.app_label}.{model._meta.model_name}' "
                "must be an UUIDfield. "
                "For history = HistoricalRecords() use edc_model.HistoricalRecords instead of "
                "simple_history.HistoricalRecords(). "
                f"See '{self.instance._meta.app_label}.{self.instance._meta.model_name}'."
            )
1288473
public void refresh() {
        QueryCache.instance().purgeTableCache(metaModelLocal);
        Model fresh = ModelDelegate.findById(this.getClass(), getId());
        if (fresh == null) {
            throw new StaleModelException("Failed to refresh self because probably record with " +
                    "this ID does not exist anymore. Stale model: " + this);
        }
        fresh.copyTo(this);
        dirtyAttributeNames.clear();
    }
1360531
def cached_instance(model, timeout=None, **filters):
    
    if isinstance(model, basestring):
        model = _str_to_model(model)

    cache_key = generate_cache_key(model, **filters)
    return get_cached(cache_key, model.objects.select_related().get, kwargs=filters)
1018267
def refresh(self):
        
        table   = self.tableType()
        search  = nativestring(self._pywidget.text())
        if search == self._lastSearch:
            return
        
        self._lastSearch = search
        if not search:
            return
        
        if search in self._cache:
            records = self._cache[search]
        else:
            records = table.select(where = self.baseQuery(),
                                   order = self.order())
            records = list(records.search(search, limit=self.limit()))
            self._cache[search] = records
        
        self._records = records
        self.model().setStringList(map(str, self._records))
        self.complete()
820096
public Response fetchHistory(@PathParam("id") URI_ID id) throws Exception {
        final MODEL_ID mId = tryConvertId(id);
        matchedFetchHistory(mId);
        final Query<MODEL> query = server.find(modelType);

        defaultFindOrderBy(query);

        final Ref<FutureRowCount> rowCount = Refs.emptyRef();
        Object entity = executeTx(t -> {
            configDefaultQuery(query);
            configFetchHistoryQuery(query, mId);
            applyUriQuery(query, false);
            applyPageConfig(query);
            List<Version<MODEL>> list = query.findVersions();
            rowCount.set(fetchRowCount(query));
            return processFetchedHistoryModelList(list, mId);
        });

        if (isEmptyEntity(entity)) {
            return Response.noContent().build();
        }
        Response response = Response.ok(entity).build();
        applyRowCountHeader(response.getHeaders(), query, rowCount.get());
        return response;
    }
755240
def check_instance_state(self, instance_id, wait=True):
        
        '''
            
        '''

        title = '%s.check_instance_state' % self.__class__.__name__

    # validate inputs
        input_fields = {
            'instance_id': instance_id
        }
        for key, value in input_fields.items():
            object_title = '%s(%s=%s)' % (title, key, str(value))
            self.fields.validate(value, '.%s' % key, object_title)

    # notify state check
        self.iam.printer('Querying AWS region %s for state of instance %s.' % (self.iam.region_name, instance_id))

    # check connection to API
        try:
            self.connection.describe_instances()
        except:
            raise AWSConnectionError(title)
                
    # check existence of instance
        try:
            response = self.connection.describe_instances(
                InstanceIds=[ instance_id ]
            )
        except:
            raise ValueError('\nInstance %s does not exist.' % instance_id)
        if not 'Reservations' in response.keys():
            raise ValueError('\nInstance %s does not exist.' % instance_id)
        elif not response['Reservations']:
            raise ValueError('\nInstance %s does not exist.' % instance_id)
        elif not 'Instances' in response['Reservations'][0].keys():
            raise ValueError('\nInstance %s does not exist.' % instance_id)
        elif not response['Reservations'][0]['Instances'][0]:
            raise ValueError('\nInstance %s does not exist.' % instance_id)
                
    # check into state of instance
        elif not 'State' in response['Reservations'][0]['Instances'][0].keys():
            from time import sleep
            from timeit import timeit as timer
            self.iam.printer('Checking into the status of instance %s ... ' % instance_id, flush=True)
            state_timeout = 0
            while not 'State' in response['Reservations'][0]['Instances'][0].keys():
                self.iam.printer('.', flush=True)
                sleep(3)
                state_timeout += 1
                response = self.connection.describe_instances(
                    InstanceIds=[ instance_id ]
                )
                if state_timeout > 3:
                    raise Exception('\nFailure to determine status of instance %s.' % instance_id)
            self.iam.printer('done.')
            
    # return None if instance has already been terminated
        instance_state = response['Reservations'][0]['Instances'][0]['State']['Name']
        if instance_state == 'shutting-down' or instance_state == 'terminated':
            self.iam.printer('Instance %s has already been terminated.' % instance_id)
            return None
            
    # wait while instance is pending
        elif instance_state == 'pending':
            self.iam.printer('Instance %s is %s.' % (instance_id, instance_state), flush=True)
            if not wait:
                return instance_state
            else:
                from time import sleep
                from timeit import timeit as timer
                delay = 3
                while instance_state == 'pending':
                    self.iam.printer('.', flush=True)
                    sleep(delay)
                    t3 = timer()
                    response = self.connection.describe_instances(
                        InstanceIds=[ instance_id ]
                    )
                    t4 = timer()
                    response_time = t4 - t3
                    if 3 - response_time > 0:
                        delay = 3 - response_time
                    else:
                        delay = 0
                    instance_state = response['Reservations'][0]['Instances'][0]['State']['Name']
                self.iam.printer(' done.')

    # report outcome
        self.iam.printer('Instance %s is %s.' % (instance_id, instance_state))

        return instance_state
669913
def ensure_cache_id(self, cache_id_obj):
        """"""
        cache_id = self._get_canonical_id(cache_id_obj)
        if cache_id != self._cache_id_obj:
            raise ValueError(
                "cache mismatch {0} != {1}".format(
                    cache_id, self._cache_id_obj))
265663
def run(self):
        
        self.kwargs['cached'] = self.cached
        self.kwargs['sync'] = self.sync
        self.kwargs['broker'] = self.broker
        self.id = async_iter(self.func, self.args, **self.kwargs)
        self.started = True
        return self.id
885903
def refresh(self):
        """"""
        self._update_id_list()
        for _id in self.history[:]:
            if _id not in self.id_list:
                self.history.remove(_id)
100817
def get(cls, id):
        

        # cached?
        if CACHE:
            if id in _cache['Pool']:
                log.debug('cache hit for pool %d' % id)
                return _cache['Pool'][id]
            log.debug('cache miss for pool %d' % id)

        try:
            pool = Pool.list({'id': id})[0]
        except (IndexError, KeyError):
            raise NipapNonExistentError('no pool with ID ' + str(id) + ' found')

        _cache['Pool'][id] = pool
        return pool
572123
def _create_cache_item_for_pid(self, cache_folder, pid):
        
        try:
            record = self._solr_client.get_solr_record(pid)
        except d1_onedrive.impl.onedrive_exceptions.ONEDriveException:
            pass
        else:
            self._create_cache_item(cache_folder, record)
226976
@Override
    public boolean idExists(String id) {
        if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
            LoggingUtil.SESSION_LOGGER_CORE.entering(methodClassName, methodNames[ID_EXISTS], id);
        }

        Object sessInUse;
        boolean found = false;

        SessionManagerRegistry _sessionManagerRegistry = SessionManagerRegistry.getSessionManagerRegistry();
        // Since the session manager can be configured per application, we need to
        // look at
        // each entry individually since some of the contexts can have database/mtm
        // persistence
        // enabled while others are using memory

        // Look in memory first for improved performance
        Enumeration vEnum = _sessionManagerRegistry.getSessionManagers();
        IStore tempStore;
        while (vEnum.hasMoreElements() && !found) {
            IGenericSessionManager sm = (IGenericSessionManager) vEnum.nextElement();
            if (sm == null) // || sm == this)
                continue;
            tempStore = sm.getIStore();
            if (tempStore == this)
                continue; // don't bother checking our own store
            sessInUse = tempStore.getFromMemory(id);
            if (sessInUse != null)
                found = true;
        }

        if (found) {
            if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINER)) {
                String s = "Found in Cache/Mem";
                LoggingUtil.SESSION_LOGGER_CORE.exiting(methodClassName, methodNames[ID_EXISTS], s);
            }
            return found;
        }

        // Check our current external store first.
        // This is probably the most likely
        // Also, if the sessionId has been recently invalidated and
        // checkRecentlyInvalidList is true, we should return true without checking
        // other backends.
        found = this.isPresentInExternalStore(id);
        if (found) {
            if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
                LoggingUtil.SESSION_LOGGER_CORE.exiting(methodClassName, methodNames[ID_EXISTS], Boolean.valueOf(found));
            }
            return found;
        }

        // Search the persistent stores for the sessionid
        Enumeration enum3 = _sessionManagerRegistry.getSessionManagers();
        while (enum3.hasMoreElements()) {
            IGenericSessionManager sm = (IGenericSessionManager) enum3.nextElement();
            if (sm == null) // || sm == this)
                continue;
            else {
                tempStore = sm.getIStore();
                if (tempStore == this)
                    continue; // don't bother checking our own store as we already checked
                              // it above
                found = tempStore.isPresentInExternalStore(id);
                if (found) {
                    break;
                }
            }
        }

        if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINER)) {
            String s = "After persistent store scan returning: " + found;
            LoggingUtil.SESSION_LOGGER_CORE.exiting(methodClassName, methodNames[ID_EXISTS], s);
        }

        return found;
    }
101282
def get_cached(self, link, default=None):
        ''''''
        if hasattr(link, 'uri'):
            return self.id_map.get(link.uri, default)
        else:
            return self.id_map.get(link, default)