L1, step 5: ensure UI5 Application Index is updated
483025
function (fnCallbackAsyncL1) {
            async.series([
                me.calcAppIndex.bind(me)
            ], function (oError, oResult) {
                fnCallbackAsyncL1(oError, oResult);
            });
        }
576929
@Deprecated
	private static void updateIndexWithSettingsInElasticsearch(Client client, String index, String settings) throws Exception {
		logger.trace("updateIndex([{}])", index);

		assert client != null;
		assert index != null;

		if (settings != null) {
			logger.trace("Found update settings for index [{}]: [{}]", index, settings);
			logger.debug("updating settings for index [{}]", index);
			client.admin().indices().prepareUpdateSettings(index).setSettings(settings, XContentType.JSON).get();
		}

		logger.trace("/updateIndex([{}])", index);
	}
1250952
private void updateCands() {
        if (!this.dense) { connectOccs(); }
        assert !this.schedule;
        this.schedule = true;
        if (this.schedule = currentCands().empty()) { for (int idx = 1; idx <= maxvar(); idx++) { touch(idx); } }
        this.schedule = true;
        touchFixed();
    }
188727
public void refreshIndexList() throws IOException
   {
      synchronized (updateMonitor)
      {
         // release reader if any
         releaseMultiReader();
         // prepare added/removed sets
         Set<String> newList = new HashSet<String>(indexNames.getNames());

         // remove removed indexes
         Iterator<PersistentIndex> iterator = indexes.iterator();
         while (iterator.hasNext())
         {
            PersistentIndex index = iterator.next();
            String name = index.getName();
            // if current index not in new list, close it, cause it is deleted.
            if (!newList.contains(name))
            {
               index.close();
               iterator.remove();
            }
            else
            {
               // remove from list, cause this segment of index still present and indexes list contains
               // PersistentIndex instance related to this index..
               newList.remove(name);
               // Release everything to make sure that we see the
               // latest changes
               index.releaseWriterAndReaders();
            }
         }
         // now newList contains ONLY new, added indexes, deleted indexes, are removed from list.
         for (String name : newList)
         {
            // only open if it still exists
            // it is possible that indexNames still contains a name for
            // an index that has been deleted, but indexNames has not been
            // written to disk.
            if (!directoryManager.hasDirectory(name))
            {
               LOG.debug("index does not exist anymore: " + name);
               // move on to next index
               continue;
            }
            PersistentIndex index =
               new PersistentIndex(name, handler.getTextAnalyzer(), handler.getSimilarity(), cache, directoryManager,
                  modeHandler);
            index.setMaxFieldLength(handler.getMaxFieldLength());
            index.setUseCompoundFile(handler.getUseCompoundFile());
            index.setTermInfosIndexDivisor(handler.getTermInfosIndexDivisor());
            indexes.add(index);
         }
          // Reset the volatile index to be exactly like the master
          resetVolatileIndex();
      }
   }
156371
@Override
    @InterfaceAudience.Private
    public Status updateIndexes(List<ViewStore> inputViews) throws CouchbaseLiteException {
        Log.v(Log.TAG_VIEW, "Re-indexing view: %s", name);
        if (getViewID() <= 0) {
            String msg = "getViewID() < 0";
            throw new CouchbaseLiteException(msg, Status.NOT_FOUND);
        }

        if (!store.beginTransaction())
            throw new CouchbaseLiteException("Error in beginTransaction()", Status.DB_ERROR);

        boolean success = false;
        Cursor cursor = null;
        try {
            // If the view the update is for doesn't need any update, don't do anything:
            final long dbMaxSequence = store.getLastSequence();
            final long forViewLastSequence = getLastSequenceIndexed();
            if (forViewLastSequence >= dbMaxSequence) {
                success = true;
                return new Status(Status.NOT_MODIFIED);
            }

            // Check whether we need to update at all,
            // and remove obsolete emitted results from the 'maps' table:
            long minLastSequence = dbMaxSequence;
            final long[] viewLastSequence = new long[inputViews.size()];
            int deletedCount = 0;
            int i = 0;
            final HashSet<String> docTypes = new HashSet<String>();
            HashMap<String, String> viewDocTypes = null;
            boolean allDocTypes = false;
            final HashMap<Integer, Integer> viewTotalRows = new HashMap<Integer, Integer>();
            final ArrayList<SQLiteViewStore> views = new ArrayList<SQLiteViewStore>();
            final ArrayList<Mapper> mapBlocks = new ArrayList<Mapper>();

            for (ViewStore v : inputViews) {
                assert (v != null);
                SQLiteViewStore view = (SQLiteViewStore) v;
                ViewStoreDelegate delegate = view.getDelegate();
                Mapper map = delegate != null ? delegate.getMap() : null;
                if (map == null) {
                    if (view == this) {
                        String msg = String.format(Locale.ENGLISH, "Cannot index view %s: " +
                                "no map block registered", view.getName());
                        Log.e(Log.TAG_VIEW, msg);
                        throw new CouchbaseLiteException(msg, Status.BAD_REQUEST);
                    }
                    Log.v(Log.TAG_VIEW, "    %s has no map block; skipping it", view.getName());
                    continue;
                }

                views.add(view);
                mapBlocks.add(map);

                int viewID = view.getViewID();
                if (viewID <= 0) {
                    String message = String.format(Locale.ENGLISH, "View '%s' not found in database",
                            view.getName());
                    Log.e(Log.TAG_VIEW, message);
                    throw new CouchbaseLiteException(message, Status.NOT_FOUND);
                }

                int totalRows = view.getTotalRows();
                viewTotalRows.put(viewID, totalRows);

                long last = view == this ? forViewLastSequence : view.getLastSequenceIndexed();
                viewLastSequence[i++] = last;
                if (last < 0) {
                    String msg = String.format(Locale.ENGLISH, "last < 0 (%d)", last);
                    throw new CouchbaseLiteException(msg, Status.INTERNAL_SERVER_ERROR);
                } else if (last < dbMaxSequence) {
                    if (last == 0)
                        view.createIndex();
                    minLastSequence = Math.min(minLastSequence, last);
                    Log.v(Log.TAG_VIEW, "    %s last indexed at #%d", view.getName(), last);

                    String docType = delegate.getDocumentType();
                    if (docType != null) {
                        docTypes.add(docType);
                        if (viewDocTypes == null)
                            viewDocTypes = new HashMap<String, String>();
                        viewDocTypes.put(view.getName(), docType);
                    } else {
                        allDocTypes = true;
                    }

                    int changes = 0;
                    if (last == 0) {
                        changes = store.getStorageEngine().delete(view.queryString("maps_#"), null, null);
                    } else {
                        store.optimizeSQLIndexes();
                        String[] args = {Long.toString(last), Long.toString(last)};
                        changes = store.getStorageEngine().delete(view.queryString("maps_#"),
                                "sequence IN (SELECT parent FROM revs " +
                                        "WHERE sequence>? AND +parent>0 AND +parent<=?)", args);
                    }

                    // Update #deleted rows:
                    deletedCount += changes;

                    // Only count these deletes as changes if this isn't a view reset to 0
                    if (last != 0) {
                        int newTotalRows = viewTotalRows.get(viewID) - changes;
                        viewTotalRows.put(viewID, newTotalRows);
                    }
                }
            }

            if (minLastSequence == dbMaxSequence) {
                Log.v(Log.TAG_VIEW, "minLastSequence (%d) == dbMaxSequence (%d), nothing to do",
                        minLastSequence, dbMaxSequence);
                success = true;
                return new Status(Status.NOT_MODIFIED);
            }

            Log.v(Log.TAG_VIEW, "Updating indexes of (%s) from #%d to #%d ...",
                    viewNames(views), minLastSequence, dbMaxSequence);

            // This is the emit() block, which gets called from within the user-defined map() block
            // that's called down below.
            final AtomicInteger insertedCount = new AtomicInteger(0);
            AbstractMapEmitBlock emitBlock = new AbstractMapEmitBlock() {
                @Override
                public void emit(Object key, Object value) {
                    if (key == null) {
                        Log.w(Log.TAG_VIEW, "emit() called with nil key; ignoring");
                        return;
                    }
                    try {
                        curView.emit(key, value, this.sequence); // emit block's sequence
                        int curViewID = curView.getViewID();
                        viewTotalRows.put(curViewID, viewTotalRows.get(curViewID) + 1);
                    } catch (Exception e) {
                        Log.e(Log.TAG_VIEW, "Error emitting", e);
                        throw new RuntimeException(e);
                    }
                }
            };

            // Now scan every revision added since the last time the view was indexed:

            // NOTE: Below is original Query. In case query result uses a lot of memory,
            //       Android SQLiteDatabase causes null value column. Then it causes the missing
            //       _index data because following logic skip result if column is null.
            //       To avoid the issue, retrieving json field is isolated from original query.
            //       Because json field could be large, maximum size is 2MB.
            // StringBuffer sql = new StringBuffer( "SELECT revs.doc_id, sequence, docid, revid,
            // json, no_attachments, deleted FROM revs, docs WHERE sequence>? AND current!=0 ");

            boolean checkDocTypes = docTypes.size() > 1 || (allDocTypes && docTypes.size() > 0);
            StringBuilder sql = new StringBuilder(
                    "SELECT revs.doc_id, sequence, docid, revid, no_attachments, deleted ");
            if (checkDocTypes)
                sql.append(", doc_type ");
            sql.append("FROM revs ");
            sql.append("JOIN docs ON docs.doc_id = revs.doc_id ");
            sql.append("WHERE sequence>? AND +current>0 ");
            if (minLastSequence == 0) {
                sql.append("AND +deleted=0 ");
            }
            if (!allDocTypes && docTypes.size() > 0) {
                String docTypesString = getJoinedSQLQuotedStrings(
                        docTypes.toArray(new String[docTypes.size()]));
                sql.append("AND doc_type IN (").append(docTypesString).append(") ");
            }
            // order result by deleted ASC so if multiple revs returned the non deleted are the first
            // NOTE: Views broken with concurrent update and delete
            // https://github.com/couchbase/couchbase-lite-java-core/issues/952
            sql.append("ORDER BY +revs.doc_id, +deleted, +revid DESC");
            String[] selectArgs = {Long.toString(minLastSequence)};
            cursor = store.getStorageEngine().rawQuery(sql.toString(), selectArgs);

            boolean keepGoing = cursor.moveToNext(); // Go to first result row
            while (keepGoing) {
                // NOTE: skip row if 1st column is null
                // https://github.com/couchbase/couchbase-lite-java-core/issues/497
                if (cursor.isNull(0)) {
                    keepGoing = cursor.moveToNext();
                    continue;
                }

                long docID = cursor.getLong(0);

                // Reconstitute the document as a dictionary:
                long sequence = cursor.getLong(1);
                String docId = cursor.getString(2);
                if (docId.startsWith("_design/")) {  // design docs don't get indexed!
                    keepGoing = cursor.moveToNext();
                    continue;
                }
                String revID = cursor.getString(3);
                boolean deleted = cursor.getInt(5) > 0;
                String docType = checkDocTypes ? cursor.getString(6) : null;

                // Skip rows with the same doc_id -- these are losing conflicts.
                // NOTE: Or Skip rows if 1st column is null
                // https://github.com/couchbase/couchbase-lite-java-core/issues/497
                ArrayList<String> conflicts = null;
                boolean isNull;
                while ((keepGoing = cursor.moveToNext()) &&
                        ((isNull = cursor.isNull(0)) || cursor.getLong(0) == docID)) {
                    if (isNull)
                        continue;
                    if (!deleted) {
                        if (conflicts == null)
                            conflicts = new ArrayList<String>();
                        conflicts.add(cursor.getString(3));
                    }
                }

                long realSequence = sequence; // because sequence may be changed, below
                if (minLastSequence > 0) {
                    // Find conflicts with documents from previous indexings.
                    Cursor cursor2 = null;
                    try {
                        String[] selectArgs2 = {Long.toString(docID), Long.toString(minLastSequence)};
                        cursor2 = store.getStorageEngine().rawQuery(
                                "SELECT revid, sequence FROM revs "
                                        + "WHERE doc_id=? AND sequence<=? AND current>0 AND deleted=0 "
                                        + "ORDER BY revID DESC ", selectArgs2);

                        if (cursor2.moveToNext()) {
                            String oldRevID = cursor2.getString(0);
                            // This is the revision that used to be the 'winner'.
                            // Remove its emitted rows:
                            long oldSequence = cursor2.getLong(1);
                            String[] args = {Long.toString(oldSequence)};
                            for (SQLiteViewStore view : views) {
                                int changes = view.store.getStorageEngine().
                                        delete(view.queryString("maps_#"), "sequence=?", args);
                                deletedCount += changes;
                                int thisViewID = view.getViewID();
                                int newTotalRows = viewTotalRows.get(thisViewID) - changes;
                                viewTotalRows.put(thisViewID, newTotalRows);
                            }

                            String conflictRevID = oldRevID;
                            if (deleted || RevisionInternal.CBLCompareRevIDs(oldRevID, revID) > 0) {
                                // It still 'wins' the conflict, so it's the one that
                                // should be mapped [again], not the current revision!
                                conflictRevID = revID;
                                revID = oldRevID;
                                deleted = false;
                                sequence = oldSequence;
                            }

                            if (!deleted) {
                                // Conflict revisions:
                                if (conflicts == null)
                                    conflicts = new ArrayList<String>();
                                conflicts.add(conflictRevID);
                                while (cursor2.moveToNext()) {
                                    conflicts.add(cursor2.getString(0));
                                }
                            }
                        }
                    } finally {
                        if (cursor2 != null) {
                            cursor2.close();
                        }
                    }
                }

                if (deleted)
                    continue;

                // Get json blob:
                String[] selectArgs3 = {Long.toString(sequence)};
                byte[] json = SQLiteUtils.byteArrayResultForQuery(store.getStorageEngine(),
                        "SELECT json FROM revs WHERE sequence=?", selectArgs3);

                // Get the document properties, to pass to the map function:
                Map<String, Object> curDoc = store.documentPropertiesFromJSON(
                        json,
                        docId,
                        revID,
                        false,
                        sequence
                );

                if (curDoc == null) {
                    Log.w(Log.TAG_VIEW, "Failed to parse JSON of doc %s rev %s", docID, revID);
                    continue;
                }
                curDoc.put("_local_seq", sequence);

                if (conflicts != null)
                    curDoc.put("_conflicts", conflicts);

                // Call the user-defined map() to emit new key/value pairs from this revision:
                i = -1;
                for (SQLiteViewStore view : views) {
                    curView = view;
                    ++i;
                    if (viewLastSequence[i] < realSequence) {
                        if (checkDocTypes) {
                            String viewDocType = viewDocTypes.get(view.getName());
                            if (viewDocType != null && !viewDocType.equals(docType))
                                continue; // skip; view's documentType doesn't match this doc
                        }
                        Log.v(Log.TAG_VIEW, "#%d: map '%s' for view %s...",
                                sequence, docID, view.getName());
                        try {
                            emitBlock.setSequence(sequence);
                            mapBlocks.get(i).map(curDoc, emitBlock);
                        } catch (Throwable e) {
                            String msg = String.format(Locale.ENGLISH, "Error when calling map block of view '%s'",
                                    view.getName());
                            Log.e(Log.TAG_VIEW, msg, e);
                            throw new CouchbaseLiteException(msg, e, Status.CALLBACK_ERROR);
                        }
                    }
                }
            }

            // Finally, record the last revision sequence number that was indexed and update #rows:
            for (SQLiteViewStore view : views) {
                view.finishCreatingIndex();
                int newTotalRows = viewTotalRows.get(view.getViewID());
                ContentValues updateValues = new ContentValues();
                updateValues.put("lastSequence", dbMaxSequence);
                updateValues.put("total_docs", newTotalRows);
                String[] whereArgs = {Integer.toString(view.getViewID())};
                store.getStorageEngine().update("views", updateValues, "view_id=?", whereArgs);
            }
            Log.v(Log.TAG_VIEW, "...Finished re-indexing (%s) to #%d (deleted %d, added %d)",
                    viewNames(views), dbMaxSequence, deletedCount, insertedCount.intValue());

            success = true;
            return new Status(Status.OK);
        } catch (SQLException ex) {
            throw new CouchbaseLiteException(ex, Status.DB_ERROR);
        } finally {
            curView = null;
            if (cursor != null)
                cursor.close();
            if (store != null) {
                if (!store.endTransaction(success))
                    throw new CouchbaseLiteException("Error in endTransaction()", Status.DB_ERROR);
            }
        }
    }
131545
function _updateUIStates() {
        var spriteIndex,
            ICON_CLASSES = ["splitview-icon-none", "splitview-icon-vertical", "splitview-icon-horizontal"],
            layoutScheme = MainViewManager.getLayoutScheme();

        if (layoutScheme.columns > 1) {
            spriteIndex = 1;
        } else if (layoutScheme.rows > 1) {
            spriteIndex = 2;
        } else {
            spriteIndex = 0;
        }

        // SplitView Icon
        $splitViewMenu.removeClass(ICON_CLASSES.join(" "))
                      .addClass(ICON_CLASSES[spriteIndex]);

        // SplitView Menu
        _cmdSplitNone.setChecked(spriteIndex === 0);
        _cmdSplitVertical.setChecked(spriteIndex === 1);
        _cmdSplitHorizontal.setChecked(spriteIndex === 2);

        // Options icon
        _updateWorkingSetState();
    }
894819
private void updateDelta(Applications delta) {
        int deltaCount = 0;
        for (Application app : delta.getRegisteredApplications()) {
            for (InstanceInfo instance : app.getInstances()) {
                ++deltaCount;
                if (ActionType.ADDED.equals(instance.getActionType())) {
                    Application existingApp = getApplications()
                            .getRegisteredApplications(instance.getAppName());
                    if (existingApp == null) {
                        getApplications().addApplication(app);
                    }
                    logger.debug("Added instance {} to the existing apps ",
                            instance.getId());
                    getApplications().getRegisteredApplications(
                            instance.getAppName()).addInstance(instance);
                } else if (ActionType.MODIFIED.equals(instance.getActionType())) {
                    Application existingApp = getApplications()
                            .getRegisteredApplications(instance.getAppName());
                    if (existingApp == null) {
                        getApplications().addApplication(app);
                    }
                    logger.debug("Modified instance {} to the existing apps ",
                            instance.getId());

                    getApplications().getRegisteredApplications(
                            instance.getAppName()).addInstance(instance);

                } else if (ActionType.DELETED.equals(instance.getActionType())) {
                    Application existingApp = getApplications()
                            .getRegisteredApplications(instance.getAppName());
                    if (existingApp == null) {
                        getApplications().addApplication(app);
                    }
                    logger.debug("Deleted instance {} to the existing apps ",
                            instance.getId());
                    getApplications().getRegisteredApplications(
                            instance.getAppName()).removeInstance(instance);
                }
            }
        }
        logger.debug(
                "The total number of instances fetched by the delta processor : {}",
                deltaCount);

    }
712754
def _idle_loop(self):
        
        while not self._stop_update_flag:
            time.sleep(self.update_interval)
            with self.update_lock:
                try:
                    self.idle()
                except:
                    self._log.error("exception in App.idle method", exc_info=True)
                if self._need_update_flag:
                    try:
                        self.do_gui_update()
                    except:
                        self._log.error('''exception during gui update. It is advisable to 
                            use App.update_lock using external threads.''', exc_info=True)
305252
def upgradePrivateApplication4to5(old):
    
    new = old.upgradeVersion(
        PrivateApplication.typeName, 4, 5,
        preferredTheme=old.preferredTheme,
        privateKey=old.privateKey,
        website=old.website,
        customizedPublicPage=old.customizedPublicPage,
        authenticationApplication=old.authenticationApplication,
        preferenceAggregator=old.preferenceAggregator,
        defaultPreferenceCollection=old.defaultPreferenceCollection,
        searchAggregator=old.searchAggregator)
    new.store.powerUp(new, IWebViewer)
    return new
675474
function updateNewIndicesAfterSlot(slot, indexDelta) {
                    // Adjust all the indexNews after this slot
                    for (slot = slot.next; slot; slot = slot.next) {
                        if (slot.firstInSequence) {
                            var indexNew = (slot.indexNew !== undefined ? slot.indexNew : slot.index);
                            if (indexNew !== undefined) {
                                slot.indexNew = indexNew + indexDelta;
                            }
                        }
                    }

                    // Adjust the overall count
                    countDelta += indexDelta;

                    indexUpdateDeferred = true;

                    // Increment currentRefreshID so any outstanding fetches don't cause trouble.  If a refresh is in progress,
                    // restart it (which will also increment currentRefreshID).
                    if (refreshInProgress) {
                        beginRefresh();
                    } else {
                        currentRefreshID++;
                    }
                }
346096
def refresh_menu(self):
        """"""
        data = self.model.get_data()
        index = self.currentIndex()
        condition = (not isinstance(data, (tuple, set))) and index.isValid() \
                    and not self.readonly
        self.edit_action.setEnabled( condition )
        self.remove_action.setEnabled( condition )
        self.insert_action.setEnabled( not self.readonly )
        self.duplicate_action.setEnabled(condition)
        condition_rename = not isinstance(data, (tuple, list, set))
        self.rename_action.setEnabled(condition_rename)
        self.refresh_plot_entries(index)
1202529
private boolean notifyOnNext(final int index) {
        boolean result = true;

        for (WizardListener listener : wizardListeners) {
            result &= listener.onNext(index, viewPagerAdapter.getItem(index));
        }

        return result;
    }
76315
function _swapWorkingSetListIndexes(paneId, index1, index2) {
        var pane = _getPane(paneId);

        pane.swapViewListIndexes(index1, index2);
        exports.trigger("workingSetSort", pane.id);
        exports.trigger("_workingSetDisableAutoSort", pane.id);
    }
368810
def _initialize_applicationUiFile():
    

    RuntimeGlobals.ui_file = umbra.ui.common.get_resource_path(UiConstants.ui_file)
    if not foundations.common.path_exists(RuntimeGlobals.ui_file):
        raise foundations.exceptions.FileExistsError("'{0}' ui file is not available, {1} will now close!".format(
            UiConstants.ui_file, Constants.application_name))
599484
def refreshFromIndex( self ):
        
        item = self.uiIndexTREE.currentItem()
        if ( not item ):
            return
        
        self.gotoUrl(item.toolTip(0))
733
void update(long index, Instant instant, Type type) {
    this.index = index;
    this.type = type;
    clock.set(instant);
  }
801675
function () {
			var oModel = this._oDialog.getModel("view"),
				sVersionString = oModel.getProperty("/ProductName") + ": " +
					oModel.getProperty("/ProductVersion") + " " +
					this._getControl("versionBuiltAt", this._TECHNICAL_INFO_DIALOG_ID).getText(),
				sVersionOpenUI5String = "OpenUI5 Version: " +
					oModel.getProperty("/OpenUI5ProductVersion") + " " +
					this._getControl("versionOpenUI5BuiltAt", this._TECHNICAL_INFO_DIALOG_ID).getText(),
				sString = sVersionString + "\r\n" +
					(oModel.getProperty("/OpenUI5ProductVersion") ? sVersionOpenUI5String + "\r\n" : "") +
					this._getText("TechInfo.UserAgent.Label") + ": " + oModel.getProperty("/UserAgent") + "\r\n" +
					this._getText("TechInfo.AppUrl.Label") + ": " + oModel.getProperty("/ApplicationURL") + "\r\n";

			this._copyToClipboard(sString, "TechInfo.CopyToClipboard");
		}