# modifies olditem in place
    # any ref that does not exactly match the new proposed reference (not including retrieved) is kept
332767
def update_retrieved_if_new_multiple_refs(olditem, newitem, days=180, retrieved_pid='P813'):
    

    def is_equal_not_retrieved(oldref, newref):
        """
        Return True if the oldref == newref, NOT including any "retrieved" statements
        :param oldref:
        :param newref:
        :return:
        """
        if len(oldref) != len(newref):
            return False
        oldref_minus_retrieved = [x for x in oldref if x.get_prop_nr() != retrieved_pid]
        newref_minus_retrieved = [x for x in newref if x.get_prop_nr() != retrieved_pid]
        if not all(x in oldref_minus_retrieved for x in newref_minus_retrieved):
            return False
        oldref_retrieved = [x for x in oldref if x.get_prop_nr() == retrieved_pid]
        newref_retrieved = [x for x in newref if x.get_prop_nr() == retrieved_pid]
        if (len(newref_retrieved) != len(oldref_retrieved)):
            return False
        return True

    def ref_overwrite(oldref, newref, days):
        """
        If the newref is the same as the oldref except the retrieved date is `days` newer, return True
                                                       the retrieved date is NOT `days` newer, return False
        the refs are different, return True
        """
        if len(oldref) != len(newref):
            return True
        oldref_minus_retrieved = [x for x in oldref if x.get_prop_nr() != retrieved_pid]
        newref_minus_retrieved = [x for x in newref if x.get_prop_nr() != retrieved_pid]
        if not all(x in oldref_minus_retrieved for x in newref_minus_retrieved):
            return True
        oldref_retrieved = [x for x in oldref if x.get_prop_nr() == retrieved_pid]
        newref_retrieved = [x for x in newref if x.get_prop_nr() == retrieved_pid]
        if (len(newref_retrieved) != len(oldref_retrieved)) or not (
                        len(newref_retrieved) == len(oldref_retrieved) == 1):
            return True
        datefmt = '+%Y-%m-%dT%H:%M:%SZ'
        retold = list([datetime.strptime(r.get_value()[0], datefmt) for r in oldref if r.get_prop_nr() == retrieved_pid])[0]
        retnew = list([datetime.strptime(r.get_value()[0], datefmt) for r in newref if r.get_prop_nr() == retrieved_pid])[0]
        return (retnew - retold).days >= days

    newrefs = newitem.references
    oldrefs = olditem.references

    found_mate = [False] * len(newrefs)
    for new_n, newref in enumerate(newrefs):
        for old_n, oldref in enumerate(oldrefs):
            if is_equal_not_retrieved(oldref, newref):
                found_mate[new_n] = True
                if ref_overwrite(oldref, newref, days):
                    oldrefs[old_n] = newref
    for f_idx, f in enumerate(found_mate):
        if not f:
            oldrefs.append(newrefs[f_idx])
515815
def delete_reference(self, opaque_ref, global_ref=False):
        
        opaque_ref_value = self._get_reference_value(opaque_ref)
        if global_ref:
            del self.global_refs[opaque_ref_value]
        else:
            del self.local_refs[opaque_ref_value]
374160
function updateIndicies(modifiedElements, cachedRecords) {
                        var updatedCachedRecords = {};

                        for (var i = 0, len = modifiedElements.length; i < len; i++) {
                            var modifiedElementLookup = modifiedElements[i];
                            var cachedRecord = cachedRecords[modifiedElementLookup.oldIndex];
                            if (cachedRecord) {
                                updatedCachedRecords[modifiedElementLookup.newIndex] = cachedRecord;
                                cachedRecord.element = modifiedElementLookup.element;
                                delete cachedRecords[modifiedElementLookup.oldIndex];
                            }
                        }
                        var cachedRecordKeys = Object.keys(cachedRecords);
                        for (var i = 0, len = cachedRecordKeys.length; i < len; i++) {
                            var key = cachedRecordKeys[i],
                                record = cachedRecords[key];
                            // We need to filter out containers which were removed from the DOM. If container's item
                            // wasn't realized container can be removed without adding record to modifiedItems.
                            if (!record.element || existingContainers[uniqueID(record.element)]) {
                                updatedCachedRecords[key] = record;
                            }
                        }
                        return updatedCachedRecords;
                    }
945080
function changedActiveItems(dataSource) {
  reviseLegendHelper(dataSource);
  updateEntitiesAndExtent(dataSource); // Only does anything if there are lat & lon columns.
  dataSource._changed.raiseEvent(dataSource);
}
630189
function removeReference(name, opposite) {
  const ref = this.references[name]
  _.unset(this.references, name)
  if (ref.opposite !== undefined) {
    if (opposite) {
      _.unset(ref.type.references, ref.opposite)
    } else {
      _.unset(ref.type.references[ref.opposite], 'opposite')
    }
  }
}
113510
def modify(self, sort=None, purge=False, done=None, undone=None):
        
        self.model.modifyInPlace(
            sort=self._getPattern(sort),
            purge=purge,
            done=self._getDone(done, undone)
        )
948616
def _set_backreferences(self, context, items, **kwargs):
        

        # Don't set any references during initialization.
        # This might cause a recursion error when calling `getRaw` to fetch the
        # current set UIDs!
        initializing = kwargs.get('_initializing_', False)
        if initializing:
            return

        # UID of the current object
        uid = api.get_uid(context)
        # current set UIDs
        raw = self.getRaw(context) or []
        # handle single reference fields
        if isinstance(raw, basestring):
            raw = [raw, ]
        cur = set(raw)
        # UIDs to be set
        new = set(map(api.get_uid, items))
        # removed UIDs
        removed = cur.difference(new)

        # Unlink removed UIDs from the source
        for uid in removed:
            source = api.get_object_by_uid(uid, None)
            if source is None:
                logger.warn("UID {} does not exist anymore".format(uid))
                continue
            self.unlink_reference(source, context)

        # Link backrefs
        for item in items:
            self.link_reference(item, context)
1004235
function last(newitem) {
    if (newitem) {
      this.mappings.push({});
    }

    var m = this.mappings[this.mappings.length - 1];

    if (m && m.attribute && m.value && m.dataKey && m.replace) {
      m.re = new RegExp(m.attribute + '=([\'"]?)' + m.value + '\\1');
    } else if (m) {
      delete m.re;
    }

    return m;
  }
565216
function (newItems) {

            var itemsListener = this._itemsListener;
            var json = this.json;
            var oldItems = this._data.items;
            var numberOfItems;

            if (oldItems == newItems) {
                // items did not change
                // return;
                numberOfItems = newItems.length;
            } else {
                if (oldItems) {
                    // remove the listener on the old items object:
                    for (var i = 0, l = oldItems.length; i < l; i++) {
                        json.removeListener(oldItems[i], null, itemsListener);
                    }
                }
                json.setValue(this._data, "items", newItems);

                if (newItems) {
                    numberOfItems = newItems.length;
                    // add the listener on the new items object:
                    for (var i = 0, l = newItems.length; i < l; i++) {
                        json.addListener(newItems[i], null, itemsListener);
                    }
                    var view = this._data.itemsView;
                    if (view) {
                        view.initialArray = newItems;
                        view.refresh(view.CHANGED_INITIAL_ARRAY);
                    }
                }
            }

            if (this._data.displayOptions) {
                this._calcRowCols(this._data.displayOptions.flowOrientation, this._data.numberOfRows, this._data.numberOfColumns, numberOfItems);
            }

        }
269103
function() {
        var assetKey, newEntry, oldEntry;

        // Reuse existing metadata.
        for ( assetKey in oldAvailableLists ) {
            oldEntry = oldAvailableLists[assetKey];
            newEntry = newAvailableLists[assetKey];
            // List no longer exists. If a stock list, try to convert to
            // imported list if it was selected.
            if ( newEntry === undefined ) {
                µb.removeFilterList(assetKey);
                if ( assetKey.indexOf('://') === -1 ) {
                    customListFromStockList(assetKey);
                }
                continue;
            }
            if ( oldEntry.entryCount !== undefined ) {
                newEntry.entryCount = oldEntry.entryCount;
            }
            if ( oldEntry.entryUsedCount !== undefined ) {
                newEntry.entryUsedCount = oldEntry.entryUsedCount;
            }
            // This may happen if the list name was pulled from the list
            // content.
            // https://github.com/chrisaljoudi/uBlock/issues/982
            // There is no guarantee the title was successfully extracted from
            // the list content.
            if (
                newEntry.title === '' &&
                typeof oldEntry.title === 'string' &&
                oldEntry.title !== ''
            ) {
                newEntry.title = oldEntry.title;
            }
        }

        // Remove unreferenced imported filter lists.
        var dict = new Set(importedListKeys);
        for ( assetKey in newAvailableLists ) {
            newEntry = newAvailableLists[assetKey];
            if ( newEntry.submitter !== 'user' ) { continue; }
            if ( dict.has(assetKey) ) { continue; }
            delete newAvailableLists[assetKey];
            µb.assets.unregisterAssetSource(assetKey);
            µb.removeFilterList(assetKey);
        }
    }
827820
function replacePageReferenceVersions(data, version) {
  const replace = _.partial(replaceVersion, _, version);

  return _.mapValues(data, function (value, key) {
    let result;

    if (references.isUri(value)) {
      result = replace(value);
    } else if (_.isArray(value) && key !== 'urlHistory') {
      // urlHistory is an array of old page urls. they're not component refs and shouldn't be versioned
      result = _.map(value, replace);
    } else {
      result = value;
    }
    return result;
  });
}
1174408
function updateItemUsage(self, oItem) {
			if (self._metadata.__byKey__[oItem.oData.key] != null) { // ItemData already exists, we need to remove the old position index
				var oldIndex = self._metadata.__byKey__[oItem.oData.key];
				delete self._metadata.__byIndex__[oldIndex];
				Log.debug("Cache Manager LRUPersistentCache: set/internalset - item already exists, so its indexes are updated");
			}
			self._metadata.__byIndex__[oItem.oData.lu] = oItem.oData.key;
			self._metadata.__byKey__[oItem.oData.key] = oItem.oData.lu;

			seekMetadataLRU(self);
		}
857926
def _add_to_ref(self, rec_curr, line):
        """"""
        # Examples of record lines containing ':' include:
        #   id: GO:0000002
        #   name: mitochondrial genome maintenance
        #   namespace: biological_process
        #   def: "The maintenance of ...
        #   is_a: GO:0007005 ! mitochondrion organization
        if line[:4] == "id: ":
            assert not rec_curr.item_id
            item_id = line[4:]
            rec_curr.item_id = item_id
            rec_curr.id = item_id
        elif line[:8] == "alt_id: ":
            rec_curr.alt_ids.add(line[8:])
        elif line[:6] == "name: ":
            assert not rec_curr.name
            rec_curr.name = line[6:]
        elif line[:11] == "namespace: ":
            assert not rec_curr.namespace
            rec_curr.namespace = line[11:]
        elif line[:6] == "is_a: ":
            rec_curr._parents.add(line[6:].split()[0])
        elif line[:13] == "is_obsolete: " and line[13:] == "true":
            rec_curr.is_obsolete = True
        elif self.optobj and ':' in line:
            self.optobj.update_rec(rec_curr, line)
538785
function fixrefs(scope, i) {
                        // do children first; order shouldn't matter
                        for (i = scope.children.length; --i >= 0;)
                                fixrefs(scope.children[i]);
                        for (i in scope.refs) if (HOP(scope.refs, i)) {
                                // find origin scope and propagate the reference to origin
                                for (var origin = scope.has(i), s = scope; s; s = s.parent) {
                                        s.refs[i] = origin;
                                        if (s === origin) break;
                                }
                        }
                }
1000855
protected function processReferencesChanged()
    {
        $cache = $this->_cache;
        $attrs = $this->getAttrs();
        foreach ($cache as $key => $item) {
            if(!isset($attrs[$key])) continue;
            $attr = $attrs[$key];
            if ($attr['type'] == self::DATA_TYPE_REFERENCES) {
                if ($item instanceof Collection && (!isset($this->cleanData[$key]) || $this->cleanData[$key] !== $item->makeRef())) {
                    $this->__setter($key, $item);
                }
            }
        }
    }
31638
public boolean replaceRef(Object oldRef, Object newRef)
        throws IOException
    {
        Integer value = (Integer) _refs.remove(oldRef);

        if (value != null) {
            _refs.put(newRef, value);

            return true;
        }
        else
            return false;
    }
786491
public function replace($oldItem, $newItem, $forceAdd = true)
    {
        $this->emitOnChange(__METHOD__);
        $keys = array_keys($this->items(), $oldItem, true);
        if (count($keys) === 0) {
            if ($forceAdd) {
                $this->add($newItem);
            }
        } else {
            $this->remove($oldItem);
            foreach ($keys as $key) {
                $this->add($newItem);
                // move to old item position
                $newKeys = array_keys($this->items(), $newItem, true);
                $lastAddedKey = array_pop($newKeys);
                $this->items()[$key] = $this->items()[$lastAddedKey];
                unset($this->items()[$lastAddedKey]);
            }
        }
        $this->endEmitOnChange(__METHOD__);
        return $this;
    }