These must be handled carefully, because naively registering a handler for each editor will cause the editors to never be garbage collected.
189664
function forEachCodeMirror(f) {
    if (!document.body.getElementsByClassName) return;
    var byClass = document.body.getElementsByClassName("CodeMirror");
    for (var i = 0; i < byClass.length; i++) {
      var cm = byClass[i].CodeMirror;
      if (cm) f(cm);
    }
  }
88486
private function ensureProviders()
	{
		if (!empty($this->lazyProviders)) {
			$this->registerProviders($this->lazyProviders);
			$this->lazyProviders = null;
		}
	}
1074727
function _configureEditorAndResolve() {
                var editor = EditorManager.getActiveEditor();
                if (editor) {
                    if (settings) {
                        editor.setSelections(settings.selections);
                        editor.setScrollPos(settings.scrollPos.x, settings.scrollPos.y);
                    }
                }
                result.resolve(newFile);
            }
1051308
def clean_up(self):
        '''  '''
        self.socket.close()
        for h in self.capture_handlers:
            h['logger'].close()
534814
protected void prepareSimpleCleaningApproachScripts()
   {
      cleaningScripts.addAll(getFKRemovingScripts());
      cleaningScripts.addAll(getSingleDbWorkspaceCleaningScripts());

      committingScripts.addAll(getFKAddingScripts());

      rollbackingScripts.addAll(getFKAddingScripts());
   }
516914
@SuppressWarnings("PMD.AvoidDuplicateLiterals")
    protected void initComponentsHandlers(
            ChannelReplacements channelReplacements) {
        handlers = new ArrayList<HandlerReference>();
        // Have a look at all methods.
        for (Method m : component().getClass().getMethods()) {
            maybeAddHandler(m, channelReplacements);
        }
        handlers = Collections.synchronizedList(handlers);
    }
276193
@SuppressWarnings({"rawtypes", "unchecked"})
  public void initializeEditors(final Object editor) {
    if (editor instanceof HasValueChangeHandlers && valueChangeHandler != null) {
      ((HasValueChangeHandlers) editor).addValueChangeHandler(valueChangeHandler);
      // if widget has a value change handler, validate on change
      if (validateOnVueChangeHandler != null) {
        ((HasValueChangeHandlers) editor).addValueChangeHandler(validateOnVueChangeHandler);
      }
    }
    // if widget has a key up handler, validate on key up
    if (editor instanceof HasKeyUpHandlers && validateOnKeyUpHandler != null) {
      ((HasKeyUpHandlers) editor).addKeyUpHandler(validateOnKeyUpHandler);
    }
    // try to submit form on return
    if (editor instanceof HasKeyPressHandlers && commitOnReturnHandler != null) {
      ((HasKeyPressHandlers) editor).addKeyPressHandler(commitOnReturnHandler);
    }
  }
1193475
def editors(self, value):
        """"""
        warnings.warn(
            _ASSIGNMENT_DEPRECATED_MSG.format("editors", EDITOR_ROLE),
            DeprecationWarning,
        )
        self[EDITOR_ROLE] = value
1051687
void ensurePadding() {
        final int N = mLayerState.mNum;
        if (mPaddingL != null && mPaddingL.length >= N) {
            return;
        }

        mPaddingL = new int[N];
        mPaddingT = new int[N];
        mPaddingR = new int[N];
        mPaddingB = new int[N];
    }
1013831
protected function ensureScripts() {
    $scripts = $this->package->getScripts();
    $scripts[Handler::PLUGIN_KEY][] = "NuvoleWeb\\DrupalComponentScaffold\\Plugin::scaffold";
    $scripts[DrupalScaffold::POST_DRUPAL_SCAFFOLD_CMD][] = "NuvoleWeb\\DrupalComponentScaffold\\Plugin::scaffold";
    $this->package->setScripts($scripts);
  }
936971
function handleExtractToVariable() {
        var editor = EditorManager.getActiveEditor();

        if (editor.getSelections().length > 1) {
            editor.displayErrorMessageAtCursor(Strings.ERROR_EXTRACTTO_VARIABLE_MULTICURSORS);
            return;
        }

        initializeSession(editor);

        var selection = editor.getSelection(),
            doc       = editor.document,
            retObj    = RefactoringUtils.normalizeText(editor.getSelectedText(), editor.indexFromPos(selection.start),
                        editor.indexFromPos(selection.end), true),
            text      = retObj.text,
            start     = retObj.start,
            end       = retObj.end,
            ast,
            scopes,
            expns,
            inlineMenu;

        function callExtractToVariable(startPos, endPos, value) {
            RefactoringUtils.getScopeData(session, editor.posFromIndex(startPos))
                .done(function(expnscope) {
                    scopes = RefactoringUtils.getAllScopes(ast, expnscope, doc.getText());
                    extractToVariable(ast, startPos, endPos, value, scopes);
                }).fail(function() {
                    editor.displayErrorMessageAtCursor(Strings.ERROR_TERN_FAILED);
                });
        }

        RefactoringUtils.getScopeData(session, editor.posFromIndex(start)).done(function(scope) {
            ast = RefactoringUtils.getAST(doc.getText());
            scopes = RefactoringUtils.getAllScopes(ast, scope, doc.getText());

            if (editor.hasSelection()) {
                extractToVariable(ast, start, end, text, scopes);
            } else {
                expns = getExpressions(ast, start, end);

                expns.forEach(function(expn, index) {
                    expn.value = doc.getText().substr(expn.start, expn.end - expn.start);
                });

                // Sort expressions by their length
                expns.sort(function(a, b) {
                    return a.value.length - b.value.length;
                });

                if (!expns || !expns.length) {
                    session.editor.displayErrorMessageAtCursor(Strings.ERROR_EXTRACTTO_VARIABLE_NOT_VALID);
                    return;
                }

                // Filter expns based on length of first surrounding expression
                var firstExpnLength = RefactoringUtils.numLines(expns[0].value);
                expns = expns.filter(function(expn) {
                    return RefactoringUtils.numLines(expn.value) === firstExpnLength;
                });

                // Add name for the expression based on its value
                expns.forEach(function(expn, index) {
                    // If expn name is multi-line, display only first line
                    if (RefactoringUtils.numLines(expn.value) > 1) {
                        expn.name = expn.value.substr(0, expn.value.indexOf("\n")) + "...";
                    } else {
                        expn.name = expn.value;
                    }
                });

                // If only one surround expression, extract
                if (expns.length === 1) {
                    callExtractToVariable(expns[0].start, expns[0].end, expns[0].value);
                    return;
                }

                expns.forEach(function(expn, index) {
                    expn.id = index;
                });

                // UI for extract to variable
                inlineMenu = new InlineMenu(session.editor, Strings.EXTRACTTO_VARIABLE_SELECT_EXPRESSION);

                inlineMenu.onHover(function (expnId) {
                    // Remove the scroll Handlers If already Attached.
                    editor.off("scroll.inlinemenu");
                    // Add a scroll handler If Selection Range is not View.
                    // This is Added for a Bug, where Menu used not to open for the first Time
                    if(!editor.isLineVisible(editor.posFromIndex(expns[expnId].end).line)) {
                        editor.on("scroll.inlinemenu", function() {
                            // Remove the Handlers so that If scroll event is triggerd again by any other operation
                            // Menu should not be reopened.
                            // Menu Should be reopened only if Scroll event is triggered by onHover.
                            editor.off("scroll.inlinemenu");
                            inlineMenu.openRemovedMenu();
                        });
                    }
                    editor.setSelection(editor.posFromIndex(expns[expnId].start), editor.posFromIndex(expns[expnId].end));
                });

                inlineMenu.open(expns);

                inlineMenu.onSelect(function (expnId) {
                    callExtractToVariable(expns[expnId].start, expns[expnId].end, expns[expnId].value);
                    inlineMenu.close();
                });

                inlineMenu.onClose(function () {
                    inlineMenu.close();
                });
            }
        }).fail(function() {
            editor.displayErrorMessageAtCursor(Strings.ERROR_TERN_FAILED);
        });
    }
190201
function attachHandlers() {

        function handleDragOver(event) {
            event = event.originalEvent || event;

            var files = event.dataTransfer.files;

            stopURIListPropagation(files, event);

            if (files && files.length) {
                event.stopPropagation();
                event.preventDefault();

                var dropEffect = "none";

                // Don't allow drag-and-drop of files/folders when a modal dialog is showing.
                if ($(".modal.instance").length === 0 && isValidDrop(event.dataTransfer.items)) {
                    dropEffect = "copy";
                }
                event.dataTransfer.dropEffect = dropEffect;
            }
        }

        function handleDrop(event) {
            event = event.originalEvent || event;

            var files = event.dataTransfer.files;

            stopURIListPropagation(files, event);

            if (files && files.length) {
                event.stopPropagation();
                event.preventDefault();

                brackets.app.getDroppedFiles(function (err, paths) {
                    if (!err) {
                        openDroppedFiles(paths);
                    }
                });
            }
        }

        // For most of the window, only respond if nothing more specific in the UI has already grabbed the event (e.g.
        // the Extension Manager drop-to-install zone, or an extension with a drop-to-upload zone in its panel)
        $(window.document.body)
            .on("dragover", handleDragOver)
            .on("drop", handleDrop);

        // Over CodeMirror specifically, always pre-empt CodeMirror's drag event handling if files are being dragged - CM stops
        // propagation on any drag event it sees, even when it's not a text drag/drop. But allow CM to handle all non-file drag
        // events. See bug #10617.
        window.document.body.addEventListener("dragover", function (event) {
            if ($(event.target).closest(".CodeMirror").length) {
                handleDragOver(event);
            }
        }, true);
        window.document.body.addEventListener("drop", function (event) {
            if ($(event.target).closest(".CodeMirror").length) {
                handleDrop(event);
            }
        }, true);
    }
1110859
function handleRename() {
        var editor = EditorManager.getActiveEditor(),
            offset, handleFindRefs, token;

        if (!editor) {
            return;
        }

        if (editor.getSelections().length > 1) {
            editor.displayErrorMessageAtCursor(Strings.ERROR_RENAME_MULTICURSOR);
            return;
        }
        initializeSession(editor);


        if (!editor || editor.getModeForSelection() !== "javascript") {
            return;
        }

        token = TokenUtils.getTokenAt(editor._codeMirror, editor._codeMirror.posFromIndex(session.getOffset()));

        if (keywords.indexOf(token.string) >= 0) {
            editor.displayErrorMessageAtCursor(Strings.ERROR_RENAME_GENERAL);
            return;
        }

        var result = new $.Deferred();

        function isInSameFile(obj, refsResp) {
            var projectRoot = ProjectManager.getProjectRoot(),
                projectDir,
                fileName = "";
            if (projectRoot) {
                projectDir = projectRoot.fullPath;
            }

            // get the relative path of File as Tern can also return
            // references with file name as a relative path wrt projectRoot
            // so refernce file name will be compared with both relative and absolute path to check if it is same file
            if (projectDir && refsResp && refsResp.file && refsResp.file.indexOf(projectDir) === 0) {
                fileName = refsResp.file.slice(projectDir.length);
            }
            // In case of unsaved files, After renameing once Tern is returning filename without forward slash
            return (obj && (obj.file === refsResp.file || obj.file === fileName
                            || obj.file === refsResp.file.slice(1, refsResp.file.length)));
        }

        /**
         * Check if references are in this file only
         * If yes then select all references
         */
        function handleFindRefs (refsResp) {
            if (!refsResp || !refsResp.references || !refsResp.references.refs) {
                return;
            }

            var inlineWidget = EditorManager.getFocusedInlineWidget(),
                editor = EditorManager.getActiveEditor(),
                refs = refsResp.references.refs,
                type = refsResp.references.type;

            //In case of inline widget if some references are outside widget's text range then don't allow for rename
            if (inlineWidget) {
                var isInTextRange  = !refs.find(function(item) {
                    return (item.start.line < inlineWidget._startLine || item.end.line > inlineWidget._endLine);
                });
                
                if (!isInTextRange) {
                    editor.displayErrorMessageAtCursor(Strings.ERROR_RENAME_QUICKEDIT);
                    return;
                }
            }

            var currentPosition = editor.posFromIndex(refsResp.offset),
                refsArray = refs;
            if (type !== "local") {
                refsArray = refs.filter(function (element) {
                    return isInSameFile(element, refsResp);
                });
            }

            // Finding the Primary Reference in Array
            var primaryRef = refsArray.find(function (element) {
                return ((element.start.line === currentPosition.line || element.end.line === currentPosition.line)
                        && currentPosition.ch <= element.end.ch && currentPosition.ch >= element.start.ch);
            });
            // Setting the primary flag of Primary Refence to true
            primaryRef.primary = true;

            editor.setSelections(refsArray);
        }

        /**
         * Make a find ref request.
         * @param {Session} session - the session
         * @param {number} offset - the offset of where to jump from
         */
        function requestFindReferences(session, offset) {
            var response = requestFindRefs(session, session.editor.document, offset);

            if (response && response.hasOwnProperty("promise")) {
                response.promise.done(handleFindRefs).fail(function () {
                    result.reject();
                });
            }
        }

        offset = session.getOffset();
        requestFindReferences(session, offset);

        return result.promise();
    }
691092
protected void initEditorChangeHandlers(Element element) {

        Iterator<Element> i = CmsXmlGenericWrapper.elementIterator(element, APPINFO_EDITOR_CHANGE_HANDLER);
        while (i.hasNext()) {
            // iterate all "default" elements in the "defaults" node
            Element handlerElement = i.next();
            String handlerClass = handlerElement.attributeValue(APPINFO_ATTR_CLASS);
            String configuration = handlerElement.attributeValue(APPINFO_ATTR_CONFIGURATION);
            String scope = handlerElement.attributeValue(APPINFO_ATTR_SCOPE);
            try {
                I_CmsXmlContentEditorChangeHandler handler = (I_CmsXmlContentEditorChangeHandler)Class.forName(
                    handlerClass).newInstance();
                handler.setConfiguration(configuration);
                handler.setScope(scope);
                m_editorChangeHandlers.add(handler);
            } catch (Exception e) {
                LOG.error(e.getLocalizedMessage(), e);
            }
        }
    }
570161
protected function registerHandlers() {
		set_exception_handler(function($exception) {
			$this->pushException($exception);
			
			echo $this->renderDebugBar();
		});
		
		register_shutdown_function(function() {
			if ($this->onShutdownCallback !== null) {
				$this->onShutdownCallback->__invoke($this);
			}
			
			// Debug bar rendering for the deferred mode
			if ($this->deferredMode) {
				// Garbage collection
				if ($this->profilesGcEnabled) {
					$this->gcCycle();
				}
				
				// Content creating
				$filePath = $this->deferredDir . DIRECTORY_SEPARATOR . 'profile_' . $this->token . '.html';
				if (file_put_contents($filePath, $this->renderDebugBar()) === false) {
					throw new InvalidPath('Unable to write the debug data into: "' . $filePath . '"');
				}
			}
		});
	}
61320
public synchronized void register(@NonNull EventHandlerWrapper eventHandler) {
        String type = eventHandler.type;
        List<EventHandlerWrapper> handlers = subscribers.get(eventHandler.type);
        if (handlers == null) {
            handlers = new ArrayList<>();
            subscribers.put(type, handlers);
        }
        handlers.add(eventHandler);
    }
1291472
private function registerErrorHandler(): void
    {
        $whoops = new Run();
        $whoops->pushHandler(new PrettyPageHandler());
        $whoops->register();

        $this->errorHandler = $whoops;
    }