text:
/**
 * @constructor
 * @extends {TreeOutline}
 * @param {!WebInspector.DOMModel} domModel
 * @param {boolean=} omitRootDOMNode
 * @param {boolean=} selectEnabled
 */
WebInspector.ElementsTreeOutline = function(domModel, omitRootDOMNode, selectEnabled)
{
    this._domModel = domModel;
    this._treeElementSymbol = Symbol("treeElement");

    var element = createElement("div");

    this._shadowRoot = WebInspector.createShadowRootWithCoreStyles(element);
    this._shadowRoot.appendChild(WebInspector.Widget.createStyleElement("elements/elementsTreeOutline.css"));
    var outlineDisclosureElement = this._shadowRoot.createChild("div", "elements-disclosure");

    TreeOutline.call(this);
    this._element = this.element;
    this._element.classList.add("elements-tree-outline", "source-code");
    this._element.addEventListener("mousedown", this._onmousedown.bind(this), false);
    this._element.addEventListener("mousemove", this._onmousemove.bind(this), false);
    this._element.addEventListener("mouseleave", this._onmouseleave.bind(this), false);
    this._element.addEventListener("dragstart", this._ondragstart.bind(this), false);
    this._element.addEventListener("dragover", this._ondragover.bind(this), false);
    this._element.addEventListener("dragleave", this._ondragleave.bind(this), false);
    this._element.addEventListener("drop", this._ondrop.bind(this), false);
    this._element.addEventListener("dragend", this._ondragend.bind(this), false);
    this._element.addEventListener("webkitAnimationEnd", this._onAnimationEnd.bind(this), false);
    this._element.addEventListener("contextmenu", this._contextMenuEventFired.bind(this), false);

    outlineDisclosureElement.appendChild(this._element);
    this.element = element;

    this._includeRootDOMNode = !omitRootDOMNode;
    this._selectEnabled = selectEnabled;
    /** @type {?WebInspector.DOMNode} */
    this._rootDOMNode = null;
    /** @type {?WebInspector.DOMNode} */
    this._selectedDOMNode = null;

    this._visible = false;
    this._pickNodeMode = false;

    this._popoverHelper = new WebInspector.PopoverHelper(this._element, this._getPopoverAnchor.bind(this), this._showPopover.bind(this));
    this._popoverHelper.setTimeout(0);

    /** @type {!Map<!WebInspector.DOMNode, !WebInspector.ElementsTreeOutline.UpdateRecord>} */
    this._updateRecords = new Map();
    /** @type {!Set<!WebInspector.ElementsTreeElement>} */
    this._treeElementsBeingUpdated = new Set();

    this._domModel.addEventListener(WebInspector.DOMModel.Events.MarkersChanged, this._markersChanged, this);
}

/** @typedef {{node: !WebInspector.DOMNode, isCut: boolean}} */
WebInspector.ElementsTreeOutline.ClipboardData;

/**
 * @enum {string}
 */
WebInspector.ElementsTreeOutline.Events = {
    NodePicked: "NodePicked",
    SelectedNodeChanged: "SelectedNodeChanged",
    ElementsTreeUpdated: "ElementsTreeUpdated",
    DecorationsClicked: "DecorationsClicked"
}

/**
 * @const
 * @type {!Object.<string, string>}
 */
WebInspector.ElementsTreeOutline.MappedCharToEntity = {
    "\u00a0": "nbsp",
    "\u0093": "#147", // <control>
    "\u00ad": "shy",
    "\u2002": "ensp",
    "\u2003": "emsp",
    "\u2009": "thinsp",
    "\u200a": "#8202", // Hairspace
    "\u200b": "#8203", // ZWSP
    "\u200c": "zwnj",
    "\u200d": "zwj",
    "\u200e": "lrm",
    "\u200f": "rlm",
    "\u202a": "#8234", // LRE
    "\u202b": "#8235", // RLE
    "\u202c": "#8236", // PDF
    "\u202d": "#8237", // LRO
    "\u202e": "#8238", // RLO
    "\ufeff": "#65279" // BOM
}

WebInspector.ElementsTreeOutline.prototype = {
    /**
     * @return {symbol}
     */
    treeElementSymbol: function()
    {
        return this._treeElementSymbol;
    },

    focus: function()
    {
        this._element.focus();
    },

    /**
     * @return {boolean}
     */
    hasFocus: function()
    {
        return this._element === WebInspector.currentFocusElement();
    },

    /**
     * @param {boolean} wrap
     */
    setWordWrap: function(wrap)
    {
        this._element.classList.toggle("elements-tree-nowrap", !wrap);
    },

    /**
     * @param {!Event} event
     */
    _onAnimationEnd: function(event)
    {
        event.target.classList.remove("elements-tree-element-pick-node-1");
        event.target.classList.remove("elements-tree-element-pick-node-2");
    },

    /**
     * @return {boolean}
     */
    pickNodeMode: function()
    {
        return this._pickNodeMode;
    },

    /**
     * @param {boolean} value
     */
    setPickNodeMode: function(value)
    {
        this._pickNodeMode = value;
        this._element.classList.toggle("pick-node-mode", value);
    },

    /**
     * @param {!Element} element
     * @param {?WebInspector.DOMNode} node
     * @return {boolean}
     */
    handlePickNode: function(element, node)
    {
        if (!this._pickNodeMode)
            return false;

        this.dispatchEventToListeners(WebInspector.ElementsTreeOutline.Events.NodePicked, node);
        var hasRunningAnimation = element.classList.contains("elements-tree-element-pick-node-1") || element.classList.contains("elements-tree-element-pick-node-2");
        element.classList.toggle("elements-tree-element-pick-node-1");
        if (hasRunningAnimation)
            element.classList.toggle("elements-tree-element-pick-node-2");
        return true;
    },

    /**
     * @return {!WebInspector.DOMModel}
     */
    domModel: function()
    {
        return this._domModel;
    },

    /**
     * @param {?WebInspector.InplaceEditor.Controller} multilineEditing
     */
    setMultilineEditing: function(multilineEditing)
    {
        this._multilineEditing = multilineEditing;
    },

    /**
     * @return {number}
     */
    visibleWidth: function()
    {
        return this._visibleWidth;
    },

    /**
     * @param {number} width
     */
    setVisibleWidth: function(width)
    {
        this._visibleWidth = width;
        if (this._multilineEditing)
            this._multilineEditing.setWidth(this._visibleWidth);
    },

    /**
     * @param {?WebInspector.ElementsTreeOutline.ClipboardData} data
     */
    _setClipboardData: function(data)
    {
        if (this._clipboardNodeData) {
            var treeElement = this.findTreeElement(this._clipboardNodeData.node);
            if (treeElement)
                treeElement.setInClipboard(false);
            delete this._clipboardNodeData;
        }

        if (data) {
            var treeElement = this.findTreeElement(data.node);
            if (treeElement)
                treeElement.setInClipboard(true);
            this._clipboardNodeData = data;
        }
    },

    /**
     * @param {!WebInspector.DOMNode} removedNode
     */
    resetClipboardIfNeeded: function(removedNode)
    {
        if (this._clipboardNodeData && this._clipboardNodeData.node === removedNode)
            this._setClipboardData(null);
    },

    /**
     * @param {boolean} isCut
     * @param {!Event} event
     */
    handleCopyOrCutKeyboardEvent: function(isCut, event)
    {
        this._setClipboardData(null);

        // Don't prevent the normal copy if the user has a selection.
        if (!event.target.isComponentSelectionCollapsed())
            return;

        // Do not interfere with text editing.
        if (WebInspector.isEditing())
            return;

        var targetNode = this.selectedDOMNode();
        if (!targetNode)
            return;

        event.clipboardData.clearData();
        event.preventDefault();

        this.performCopyOrCut(isCut, targetNode);
    },

    /**
     * @param {boolean} isCut
     * @param {?WebInspector.DOMNode} node
     */
    performCopyOrCut: function(isCut, node)
    {
        if (isCut && (node.isShadowRoot() || node.ancestorUserAgentShadowRoot()))
            return;

        node.copyNode();
        this._setClipboardData({ node: node, isCut: isCut });
    },

    /**
     * @param {!WebInspector.DOMNode} targetNode
     * @return {boolean}
     */
    canPaste: function(targetNode)
    {
        if (targetNode.isShadowRoot() || targetNode.ancestorUserAgentShadowRoot())
            return false;

        if (!this._clipboardNodeData)
            return false;

        var node = this._clipboardNodeData.node;
        if (this._clipboardNodeData.isCut && (node === targetNode || node.isAncestor(targetNode)))
            return false;

        if (targetNode.target() !== node.target())
            return false;
        return true;
    },

    /**
     * @param {!WebInspector.DOMNode} targetNode
     */
    pasteNode: function(targetNode)
    {
        if (this.canPaste(targetNode))
            this._performPaste(targetNode);
    },

    /**
     * @param {!Event} event
     */
    handlePasteKeyboardEvent: function(event)
    {
        // Do not interfere with text editing.
        if (WebInspector.isEditing())
            return;

        var targetNode = this.selectedDOMNode();
        if (!targetNode || !this.canPaste(targetNode))
            return;

        event.preventDefault();
        this._performPaste(targetNode);
    },

    /**
     * @param {!WebInspector.DOMNode} targetNode
     */
    _performPaste: function(targetNode)
    {
        if (this._clipboardNodeData.isCut) {
            this._clipboardNodeData.node.moveTo(targetNode, null, expandCallback.bind(this));
            this._setClipboardData(null);
        } else {
            this._clipboardNodeData.node.copyTo(targetNode, null, expandCallback.bind(this));
        }

        /**
         * @param {?Protocol.Error} error
         * @param {!DOMAgent.NodeId} nodeId
         * @this {WebInspector.ElementsTreeOutline}
         */
        function expandCallback(error, nodeId)
        {
            if (error)
                return;
            var pastedNode = this._domModel.nodeForId(nodeId);
            if (!pastedNode)
                return;
            this.selectDOMNode(pastedNode);
        }
    },

    /**
     * @param {boolean} visible
     */
    setVisible: function(visible)
    {
        this._visible = visible;
        if (!this._visible) {
            this._popoverHelper.hidePopover();
            if (this._multilineEditing)
                this._multilineEditing.cancel();
            return;
        }

        this.runPendingUpdates();
        if (this._selectedDOMNode)
            this._revealAndSelectNode(this._selectedDOMNode, false);
    },

    get rootDOMNode()
    {
        return this._rootDOMNode;
    },

    set rootDOMNode(x)
    {
        if (this._rootDOMNode === x)
            return;

        this._rootDOMNode = x;

        this._isXMLMimeType = x && x.isXMLNode();

        this.update();
    },

    get isXMLMimeType()
    {
        return this._isXMLMimeType;
    },

    /**
     * @return {?WebInspector.DOMNode}
     */
    selectedDOMNode: function()
    {
        return this._selectedDOMNode;
    },

    /**
     * @param {?WebInspector.DOMNode} node
     * @param {boolean=} focus
     */
    selectDOMNode: function(node, focus)
    {
        if (this._selectedDOMNode === node) {
            this._revealAndSelectNode(node, !focus);
            return;
        }

        this._selectedDOMNode = node;
        this._revealAndSelectNode(node, !focus);

        // The _revealAndSelectNode() method might find a different element if there is inlined text,
        // and the select() call would change the selectedDOMNode and reenter this setter. So to
        // avoid calling _selectedNodeChanged() twice, first check if _selectedDOMNode is the same
        // node as the one passed in.
        if (this._selectedDOMNode === node)
            this._selectedNodeChanged();
    },

    /**
     * @return {boolean}
     */
    editing: function()
    {
        var node = this.selectedDOMNode();
        if (!node)
            return false;
        var treeElement = this.findTreeElement(node);
        if (!treeElement)
            return false;
        return treeElement.isEditing() || false;
    },

    update: function()
    {
        var selectedTreeElement = this.selectedTreeElement;
        if (!(selectedTreeElement instanceof WebInspector.ElementsTreeElement))
            selectedTreeElement = null;

        var selectedNode = selectedTreeElement ? selectedTreeElement.node() : null;

        this.removeChildren();

        if (!this.rootDOMNode)
            return;

        var treeElement;
        if (this._includeRootDOMNode) {
            treeElement = this._createElementTreeElement(this.rootDOMNode);
            this.appendChild(treeElement);
        } else {
            // FIXME: this could use findTreeElement to reuse a tree element if it already exists
            var node = this.rootDOMNode.firstChild;
            while (node) {
                treeElement = this._createElementTreeElement(node);
                this.appendChild(treeElement);
                node = node.nextSibling;
            }
        }

        if (selectedNode)
            this._revealAndSelectNode(selectedNode, true);
    },

    updateSelection: function()
    {
        if (!this.selectedTreeElement)
            return;
        var element = this.selectedTreeElement;
        element.updateSelection();
    },

    /**
     * @param {!WebInspector.DOMNode} node
     */
    updateOpenCloseTags: function(node)
    {
        var treeElement = this.findTreeElement(node);
        if (treeElement)
            treeElement.updateTitle(this._updateRecordForHighlight(node));
        var closingTagElement = treeElement.lastChild();
        if (closingTagElement && closingTagElement.isClosingTag())
            closingTagElement.updateTitle(this._updateRecordForHighlight(node));
    },

    _selectedNodeChanged: function()
    {
        this.dispatchEventToListeners(WebInspector.ElementsTreeOutline.Events.SelectedNodeChanged, this._selectedDOMNode);
    },

    /**
     * @param {!Array.<!WebInspector.DOMNode>} nodes
     */
    _fireElementsTreeUpdated: function(nodes)
    {
        this.dispatchEventToListeners(WebInspector.ElementsTreeOutline.Events.ElementsTreeUpdated, nodes);
    },

    /**
     * @param {!WebInspector.DOMNode} node
     * @return {?WebInspector.ElementsTreeElement}
     */
    findTreeElement: function(node)
    {
        var treeElement = this._lookUpTreeElement(node);
        if (!treeElement && node.nodeType() === Node.TEXT_NODE) {
            // The text node might have been inlined if it was short, so try to find the parent element.
            treeElement = this._lookUpTreeElement(node.parentNode);
        }

        return /** @type {?WebInspector.ElementsTreeElement} */ (treeElement);
    },

    /**
     * @param {?WebInspector.DOMNode} node
     * @return {?TreeElement}
     */
    _lookUpTreeElement: function(node)
    {
        if (!node)
            return null;

        var cachedElement = node[this._treeElementSymbol];
        if (cachedElement)
            return cachedElement;

        // Walk up the parent pointers from the desired node
        var ancestors = [];
        for (var currentNode = node.parentNode; currentNode; currentNode = currentNode.parentNode) {
            ancestors.push(currentNode);
            if (currentNode[this._treeElementSymbol])  // stop climbing as soon as we hit
                break;
        }

        if (!currentNode)
            return null;

        // Walk down to populate each ancestor's children, to fill in the tree and the cache.
        for (var i = ancestors.length - 1; i >= 0; --i) {
            var treeElement = ancestors[i][this._treeElementSymbol];
            if (treeElement)
                treeElement.onpopulate();  // fill the cache with the children of treeElement
        }

        return node[this._treeElementSymbol];
    },

    /**
     * @param {!WebInspector.DOMNode} node
     * @return {?WebInspector.ElementsTreeElement}
     */
    createTreeElementFor: function(node)
    {
        var treeElement = this.findTreeElement(node);
        if (treeElement)
            return treeElement;
        if (!node.parentNode)
            return null;

        treeElement = this.createTreeElementFor(node.parentNode);
        return treeElement ? this._showChild(treeElement, node) : null;
    },

    set suppressRevealAndSelect(x)
    {
        if (this._suppressRevealAndSelect === x)
            return;
        this._suppressRevealAndSelect = x;
    },

    /**
     * @param {?WebInspector.DOMNode} node
     * @param {boolean} omitFocus
     */
    _revealAndSelectNode: function(node, omitFocus)
    {
        if (this._suppressRevealAndSelect)
            return;

        if (!this._includeRootDOMNode && node === this.rootDOMNode && this.rootDOMNode)
            node = this.rootDOMNode.firstChild;
        if (!node)
            return;
        var treeElement = this.createTreeElementFor(node);
        if (!treeElement)
            return;

        treeElement.revealAndSelect(omitFocus);
    },

    /**
     * @return {?TreeElement}
     */
    _treeElementFromEvent: function(event)
    {
        var scrollContainer = this.element.parentElement;

        // We choose this X coordinate based on the knowledge that our list
        // items extend at least to the right edge of the outer <ol> container.
        // In the no-word-wrap mode the outer <ol> may be wider than the tree container
        // (and partially hidden), in which case we are left to use only its right boundary.
        var x = scrollContainer.totalOffsetLeft() + scrollContainer.offsetWidth - 36;

        var y = event.pageY;

        // Our list items have 1-pixel cracks between them vertically. We avoid
        // the cracks by checking slightly above and slightly below the mouse
        // and seeing if we hit the same element each time.
        var elementUnderMouse = this.treeElementFromPoint(x, y);
        var elementAboveMouse = this.treeElementFromPoint(x, y - 2);
        var element;
        if (elementUnderMouse === elementAboveMouse)
            element = elementUnderMouse;
        else
            element = this.treeElementFromPoint(x, y + 2);

        return element;
    },

    /**
     * @param {!Element} element
     * @param {!Event} event
     * @return {!Element|!AnchorBox|undefined}
     */
    _getPopoverAnchor: function(element, event)
    {
        var anchor = element.enclosingNodeOrSelfWithClass("webkit-html-resource-link");
        if (!anchor || !anchor.href)
            return;

        return anchor;
    },

    /**
     * @param {!WebInspector.DOMNode} node
     * @param {function()} callback
     */
    _loadDimensionsForNode: function(node, callback)
    {
        if (!node.nodeName() || node.nodeName().toLowerCase() !== "img") {
            callback();
            return;
        }

        node.resolveToObject("", resolvedNode);

        function resolvedNode(object)
        {
            if (!object) {
                callback();
                return;
            }

            object.callFunctionJSON(features, undefined, callback);
            object.release();

            /**
             * @return {!{offsetWidth: number, offsetHeight: number, naturalWidth: number, naturalHeight: number, currentSrc: (string|undefined)}}
             * @suppressReceiverCheck
             * @this {!Element}
             */
            function features()
            {
                return { offsetWidth: this.offsetWidth, offsetHeight: this.offsetHeight, naturalWidth: this.naturalWidth, naturalHeight: this.naturalHeight, currentSrc: this.currentSrc };
            }
        }
    },

    /**
     * @param {!Element} anchor
     * @param {!WebInspector.Popover} popover
     */
    _showPopover: function(anchor, popover)
    {
        var listItem = anchor.enclosingNodeOrSelfWithNodeName("li");
        var node = /** @type {!WebInspector.ElementsTreeElement} */ (listItem.treeElement).node();
        this._loadDimensionsForNode(node, WebInspector.DOMPresentationUtils.buildImagePreviewContents.bind(WebInspector.DOMPresentationUtils, node.target(), anchor.href, true, showPopover));

        /**
         * @param {!Element=} contents
         */
        function showPopover(contents)
        {
            if (!contents)
                return;
            popover.setCanShrink(false);
            popover.showForAnchor(contents, anchor);
        }
    },

    _onmousedown: function(event)
    {
        var element = this._treeElementFromEvent(event);

        if (!element || element.isEventWithinDisclosureTriangle(event))
            return;

        element.select();
    },

    _onmousemove: function(event)
    {
        var element = this._treeElementFromEvent(event);
        if (element && this._previousHoveredElement === element)
            return;

        if (this._previousHoveredElement) {
            this._previousHoveredElement.hovered = false;
            delete this._previousHoveredElement;
        }

        if (element) {
            element.hovered = true;
            this._previousHoveredElement = element;
        }

        if (element instanceof WebInspector.ElementsTreeElement) {
            this._domModel.highlightDOMNodeWithConfig(element.node().id, { mode: "all", showInfo: !WebInspector.KeyboardShortcut.eventHasCtrlOrMeta(event) });
            return;
        }

        if (element instanceof WebInspector.ElementsTreeOutline.ShortcutTreeElement)
            this._domModel.highlightDOMNodeWithConfig(undefined, { mode: "all", showInfo: !WebInspector.KeyboardShortcut.eventHasCtrlOrMeta(event) }, element.backendNodeId());
    },

    _onmouseleave: function(event)
    {
        if (this._previousHoveredElement) {
            this._previousHoveredElement.hovered = false;
            delete this._previousHoveredElement;
        }

        WebInspector.DOMModel.hideDOMNodeHighlight();
    },

    _ondragstart: function(event)
    {
        if (!event.target.isComponentSelectionCollapsed())
            return false;
        if (event.target.nodeName === "A")
            return false;

        var treeElement = this._treeElementFromEvent(event);
        if (!this._isValidDragSourceOrTarget(treeElement))
            return false;

        if (treeElement.node().nodeName() === "BODY" || treeElement.node().nodeName() === "HEAD")
            return false;

        event.dataTransfer.setData("text/plain", treeElement.listItemElement.textContent.replace(/\u200b/g, ""));
        event.dataTransfer.effectAllowed = "copyMove";
        this._treeElementBeingDragged = treeElement;

        WebInspector.DOMModel.hideDOMNodeHighlight();

        return true;
    },

    _ondragover: function(event)
    {
        if (!this._treeElementBeingDragged)
            return false;

        var treeElement = this._treeElementFromEvent(event);
        if (!this._isValidDragSourceOrTarget(treeElement))
            return false;

        var node = treeElement.node();
        while (node) {
            if (node === this._treeElementBeingDragged._node)
                return false;
            node = node.parentNode;
        }

        treeElement.updateSelection();
        treeElement.listItemElement.classList.add("elements-drag-over");
        this._dragOverTreeElement = treeElement;
        event.preventDefault();
        event.dataTransfer.dropEffect = 'move';
        return false;
    },

    _ondragleave: function(event)
    {
        this._clearDragOverTreeElementMarker();
        event.preventDefault();
        return false;
    },

    /**
     * @param {?TreeElement} treeElement
     * @return {boolean}
     */
    _isValidDragSourceOrTarget: function(treeElement)
    {
        if (!treeElement)
            return false;

        if (!(treeElement instanceof WebInspector.ElementsTreeElement))
            return false;
        var elementsTreeElement = /** @type {!WebInspector.ElementsTreeElement} */ (treeElement);

        var node = elementsTreeElement.node();
        if (!node.parentNode || node.parentNode.nodeType() !== Node.ELEMENT_NODE)
            return false;

        return true;
    },

    _ondrop: function(event)
    {
        event.preventDefault();
        var treeElement = this._treeElementFromEvent(event);
        if (treeElement)
            this._doMove(treeElement);
    },

    /**
     * @param {!TreeElement} treeElement
     */
    _doMove: function(treeElement)
    {
        if (!this._treeElementBeingDragged)
            return;

        var parentNode;
        var anchorNode;

        if (treeElement.isClosingTag()) {
            // Drop onto closing tag -> insert as last child.
            parentNode = treeElement.node();
        } else {
            var dragTargetNode = treeElement.node();
            parentNode = dragTargetNode.parentNode;
            anchorNode = dragTargetNode;
        }

        var wasExpanded = this._treeElementBeingDragged.expanded;
        this._treeElementBeingDragged._node.moveTo(parentNode, anchorNode, this.selectNodeAfterEdit.bind(this, wasExpanded));

        delete this._treeElementBeingDragged;
    },

    _ondragend: function(event)
    {
        event.preventDefault();
        this._clearDragOverTreeElementMarker();
        delete this._treeElementBeingDragged;
    },

    _clearDragOverTreeElementMarker: function()
    {
        if (this._dragOverTreeElement) {
            this._dragOverTreeElement.updateSelection();
            this._dragOverTreeElement.listItemElement.classList.remove("elements-drag-over");
            delete this._dragOverTreeElement;
        }
    },

    _contextMenuEventFired: function(event)
    {
        var treeElement = this._treeElementFromEvent(event);
        if (!(treeElement instanceof WebInspector.ElementsTreeElement) || WebInspector.isEditing())
            return;

        var contextMenu = new WebInspector.ContextMenu(event);
        var isPseudoElement = !!treeElement.node().pseudoType();
        var isTag = treeElement.node().nodeType() === Node.ELEMENT_NODE && !isPseudoElement;
        var textNode = event.target.enclosingNodeOrSelfWithClass("webkit-html-text-node");
        if (textNode && textNode.classList.contains("bogus"))
            textNode = null;
        var commentNode = event.target.enclosingNodeOrSelfWithClass("webkit-html-comment");
        contextMenu.appendApplicableItems(event.target);
        if (textNode) {
            contextMenu.appendSeparator();
            treeElement.populateTextContextMenu(contextMenu, textNode);
        } else if (isTag) {
            contextMenu.appendSeparator();
            treeElement.populateTagContextMenu(contextMenu, event);
        } else if (commentNode) {
            contextMenu.appendSeparator();
            treeElement.populateNodeContextMenu(contextMenu);
        } else if (isPseudoElement) {
            treeElement.populateScrollIntoView(contextMenu);
        }

        contextMenu.appendApplicableItems(treeElement.node());
        contextMenu.show();
    },

    runPendingUpdates: function()
    {
        this._updateModifiedNodes();
    },

    handleShortcut: function(event)
    {
        var node = this.selectedDOMNode();
        if (!node)
            return;
        var treeElement = node[this._treeElementSymbol];
        if (!treeElement)
            return;

        if (WebInspector.KeyboardShortcut.eventHasCtrlOrMeta(event) && node.parentNode) {
            if (event.keyIdentifier === "Up" && node.previousSibling) {
                node.moveTo(node.parentNode, node.previousSibling, this.selectNodeAfterEdit.bind(this, treeElement.expanded));
                event.handled = true;
                return;
            }
            if (event.keyIdentifier === "Down" && node.nextSibling) {
                node.moveTo(node.parentNode, node.nextSibling.nextSibling, this.selectNodeAfterEdit.bind(this, treeElement.expanded));
                event.handled = true;
                return;
            }
        }
    },

    /**
     * @param {!WebInspector.DOMNode} node
     * @param {boolean=} startEditing
     * @param {function()=} callback
     */
    toggleEditAsHTML: function(node, startEditing, callback)
    {
        var treeElement = node[this._treeElementSymbol];
        if (!treeElement || !treeElement.hasEditableNode())
            return;

        if (node.pseudoType())
            return;

        var parentNode = node.parentNode;
        var index = node.index;
        var wasExpanded = treeElement.expanded;

        treeElement.toggleEditAsHTML(editingFinished.bind(this), startEditing);

        /**
         * @this {WebInspector.ElementsTreeOutline}
         * @param {boolean} success
         */
        function editingFinished(success)
        {
            if (callback)
                callback();
            if (!success)
                return;

            // Select it and expand if necessary. We force tree update so that it processes dom events and is up to date.
            this.runPendingUpdates();

            var newNode = parentNode ? parentNode.children()[index] || parentNode : null;
            if (!newNode)
                return;

            this.selectDOMNode(newNode, true);

            if (wasExpanded) {
                var newTreeItem = this.findTreeElement(newNode);
                if (newTreeItem)
                    newTreeItem.expand();
            }
        }
    },

    /**
     * @param {boolean} wasExpanded
     * @param {?Protocol.Error} error
     * @param {!DOMAgent.NodeId=} nodeId
     * @return {?WebInspector.ElementsTreeElement} nodeId
     */
    selectNodeAfterEdit: function(wasExpanded, error, nodeId)
    {
        if (error)
            return null;

        // Select it and expand if necessary. We force tree update so that it processes dom events and is up to date.
        this.runPendingUpdates();

        var newNode = nodeId ? this._domModel.nodeForId(nodeId) : null;
        if (!newNode)
            return null;

        this.selectDOMNode(newNode, true);

        var newTreeItem = this.findTreeElement(newNode);
        if (wasExpanded) {
            if (newTreeItem)
                newTreeItem.expand();
        }
        return newTreeItem;
    },

    /**
     * Runs a script on the node's remote object that toggles a class name on
     * the node and injects a stylesheet into the head of the node's document
     * containing a rule to set "visibility: hidden" on the class and all it's
     * ancestors.
     *
     * @param {!WebInspector.DOMNode} node
     * @param {function(?WebInspector.RemoteObject, boolean=)=} userCallback
     */
    toggleHideElement: function(node, userCallback)
    {
        var pseudoType = node.pseudoType();
        var effectiveNode = pseudoType ? node.parentNode : node;
        if (!effectiveNode)
            return;

        var hidden = node.marker("hidden-marker");

        function resolvedNode(object)
        {
            if (!object)
                return;

            /**
             * @param {?string} pseudoType
             * @param {boolean} hidden
             * @suppressGlobalPropertiesCheck
             * @suppressReceiverCheck
             * @this {!Element}
             */
            function toggleClassAndInjectStyleRule(pseudoType, hidden)
            {
                const classNamePrefix = "__web-inspector-hide";
                const classNameSuffix = "-shortcut__";
                const styleTagId = "__web-inspector-hide-shortcut-style__";
                var selectors = [];
                selectors.push(".__web-inspector-hide-shortcut__");
                selectors.push(".__web-inspector-hide-shortcut__ *");
                selectors.push(".__web-inspector-hidebefore-shortcut__::before");
                selectors.push(".__web-inspector-hideafter-shortcut__::after");
                var selector = selectors.join(", ");
                var ruleBody = "    visibility: hidden !important;";
                var rule = "\n" + selector + "\n{\n" + ruleBody + "\n}\n";
                var className = classNamePrefix + (pseudoType || "") + classNameSuffix;
                this.classList.toggle(className, hidden);

                var localRoot = this;
                while (localRoot.parentNode)
                    localRoot = localRoot.parentNode;
                if (localRoot.nodeType === Node.DOCUMENT_NODE)
                    localRoot = document.head;

                var style = localRoot.querySelector("style#" + styleTagId);
                if (style)
                    return;

                style = document.createElement("style");
                style.id = styleTagId;
                style.type = "text/css";
                style.textContent = rule;

                localRoot.appendChild(style);
            }

            object.callFunction(toggleClassAndInjectStyleRule, [{ value: pseudoType }, { value: !hidden}], userCallback);
            object.release();
            node.setMarker("hidden-marker", hidden ? null : true);
        }

        effectiveNode.resolveToObject("", resolvedNode);
    },

    /**
     * @param {!WebInspector.DOMNode} node
     * @return {boolean}
     */
    isToggledToHidden: function(node)
    {
        return !!node.marker("hidden-marker");
    },

    _reset: function()
    {
        this.rootDOMNode = null;
        this.selectDOMNode(null, false);
        this._popoverHelper.hidePopover();
        delete this._clipboardNodeData;
        WebInspector.DOMModel.hideDOMNodeHighlight();
        this._updateRecords.clear();
    },

    wireToDOMModel: function()
    {
        this._domModel.addEventListener(WebInspector.DOMModel.Events.NodeInserted, this._nodeInserted, this);
        this._domModel.addEventListener(WebInspector.DOMModel.Events.NodeRemoved, this._nodeRemoved, this);
        this._domModel.addEventListener(WebInspector.DOMModel.Events.AttrModified, this._attributeModified, this);
        this._domModel.addEventListener(WebInspector.DOMModel.Events.AttrRemoved, this._attributeRemoved, this);
        this._domModel.addEventListener(WebInspector.DOMModel.Events.CharacterDataModified, this._characterDataModified, this);
        this._domModel.addEventListener(WebInspector.DOMModel.Events.DocumentUpdated, this._documentUpdated, this);
        this._domModel.addEventListener(WebInspector.DOMModel.Events.ChildNodeCountUpdated, this._childNodeCountUpdated, this);
        this._domModel.addEventListener(WebInspector.DOMModel.Events.DistributedNodesChanged, this._distributedNodesChanged, this);
    },

    unwireFromDOMModel: function()
    {
        this._domModel.removeEventListener(WebInspector.DOMModel.Events.NodeInserted, this._nodeInserted, this);
        this._domModel.removeEventListener(WebInspector.DOMModel.Events.NodeRemoved, this._nodeRemoved, this);
        this._domModel.removeEventListener(WebInspector.DOMModel.Events.AttrModified, this._attributeModified, this);
        this._domModel.removeEventListener(WebInspector.DOMModel.Events.AttrRemoved, this._attributeRemoved, this);
        this._domModel.removeEventListener(WebInspector.DOMModel.Events.CharacterDataModified, this._characterDataModified, this);
        this._domModel.removeEventListener(WebInspector.DOMModel.Events.DocumentUpdated, this._documentUpdated, this);
        this._domModel.removeEventListener(WebInspector.DOMModel.Events.ChildNodeCountUpdated, this._childNodeCountUpdated, this);
        this._domModel.removeEventListener(WebInspector.DOMModel.Events.DistributedNodesChanged, this._distributedNodesChanged, this);
    },

    /**
     * @param {!WebInspector.DOMNode} node
     * @return {!WebInspector.ElementsTreeOutline.UpdateRecord}
     */
    _addUpdateRecord: function(node)
    {
        var record = this._updateRecords.get(node);
        if (!record) {
            record = new WebInspector.ElementsTreeOutline.UpdateRecord();
            this._updateRecords.set(node, record);
        }
        return record;
    },

    /**
     * @param {!WebInspector.DOMNode} node
     * @return {?WebInspector.ElementsTreeOutline.UpdateRecord}
     */
    _updateRecordForHighlight: function(node)
    {
        if (!this._visible)
            return null;
        return this._updateRecords.get(node) || null;
    },

    /**
     * @param {!WebInspector.Event} event
     */
    _documentUpdated: function(event)
    {
        var inspectedRootDocument = event.data;

        this._reset();

        if (!inspectedRootDocument)
            return;

        this.rootDOMNode = inspectedRootDocument;
    },

    /**
     * @param {!WebInspector.Event} event
     */
    _attributeModified: function(event)
    {
        var node = /** @type {!WebInspector.DOMNode} */ (event.data.node);
        this._addUpdateRecord(node).attributeModified(event.data.name);
        this._updateModifiedNodesSoon();
    },

    /**
     * @param {!WebInspector.Event} event
     */
    _attributeRemoved: function(event)
    {
        var node = /** @type {!WebInspector.DOMNode} */ (event.data.node);
        this._addUpdateRecord(node).attributeRemoved(event.data.name);
        this._updateModifiedNodesSoon();
    },

    /**
     * @param {!WebInspector.Event} event
     */
    _characterDataModified: function(event)
    {
        var node = /** @type {!WebInspector.DOMNode} */ (event.data);
        this._addUpdateRecord(node).charDataModified();
        // Text could be large and force us to render itself as the child in the tree outline.
        if (node.parentNode && node.parentNode.firstChild === node.parentNode.lastChild)
            this._addUpdateRecord(node.parentNode).childrenModified();
        this._updateModifiedNodesSoon();
    },

    /**
     * @param {!WebInspector.Event} event
     */
    _nodeInserted: function(event)
    {
        var node = /** @type {!WebInspector.DOMNode} */ (event.data);
        this._addUpdateRecord(/** @type {!WebInspector.DOMNode} */ (node.parentNode)).nodeInserted(node);
        this._updateModifiedNodesSoon();
    },

    /**
     * @param {!WebInspector.Event} event
     */
    _nodeRemoved: function(event)
    {
        var node = /** @type {!WebInspector.DOMNode} */ (event.data.node);
        var parentNode = /** @type {!WebInspector.DOMNode} */ (event.data.parent);
        this.resetClipboardIfNeeded(node);
        this._addUpdateRecord(parentNode).nodeRemoved(node);
        this._updateModifiedNodesSoon();
    },

    /**
     * @param {!WebInspector.Event} event
     */
    _childNodeCountUpdated: function(event)
    {
        var node = /** @type {!WebInspector.DOMNode} */ (event.data);
        this._addUpdateRecord(node).childrenModified();
        this._updateModifiedNodesSoon();
    },

    /**
     * @param {!WebInspector.Event} event
     */
    _distributedNodesChanged: function(event)
    {
        var node = /** @type {!WebInspector.DOMNode} */ (event.data);
        this._addUpdateRecord(node).childrenModified();
        this._updateModifiedNodesSoon();
    },

    _updateModifiedNodesSoon: function()
    {
        if (!this._updateRecords.size)
            return;
        if (this._updateModifiedNodesTimeout)
            return;
        this._updateModifiedNodesTimeout = setTimeout(this._updateModifiedNodes.bind(this), 50);
    },

    _updateModifiedNodes: function()
    {
        if (this._updateModifiedNodesTimeout) {
            clearTimeout(this._updateModifiedNodesTimeout);
            delete this._updateModifiedNodesTimeout;
        }

        var updatedNodes = this._updateRecords.keysArray();
        var hidePanelWhileUpdating = updatedNodes.length > 10;
        if (hidePanelWhileUpdating) {
            var treeOutlineContainerElement = this.element.parentNode;
            var originalScrollTop = treeOutlineContainerElement ? treeOutlineContainerElement.scrollTop : 0;
            this._element.classList.add("hidden");
        }

        if (this._rootDOMNode && this._updateRecords.get(this._rootDOMNode) && this._updateRecords.get(this._rootDOMNode).hasChangedChildren()) {
            // Document's children have changed, perform total update.
            this.update();
        } else {
            for (var node of this._updateRecords.keys()) {
                if (this._updateRecords.get(node).hasChangedChildren())
                    this._updateModifiedParentNode(node);
                else
                    this._updateModifiedNode(node);
            }
        }

        if (hidePanelWhileUpdating) {
            this._element.classList.remove("hidden");
            if (originalScrollTop)
                treeOutlineContainerElement.scrollTop = originalScrollTop;
            this.updateSelection();
        }

        this._updateRecords.clear();
        this._fireElementsTreeUpdated(updatedNodes);
    },

    _updateModifiedNode: function(node)
    {
        var treeElement = this.findTreeElement(node);
        if (treeElement)
            treeElement.updateTitle(this._updateRecordForHighlight(node));
    },

    _updateModifiedParentNode: function(node)
    {
        var parentTreeElement = this.findTreeElement(node);
        if (parentTreeElement) {
            parentTreeElement.setExpandable(this._hasVisibleChildren(node));
            parentTreeElement.updateTitle(this._updateRecordForHighlight(node));
            if (parentTreeElement.populated)
                this._updateChildren(parentTreeElement);
        }
    },

    /**
     * @param {!WebInspector.ElementsTreeElement} treeElement
     */
    populateTreeElement: function(treeElement)
    {
        if (treeElement.childCount() || !treeElement.isExpandable())
            return;

        this._updateModifiedParentNode(treeElement.node());
    },

    /**
     * @param {!WebInspector.DOMNode} node
     * @param {boolean=} closingTag
     * @return {!WebInspector.ElementsTreeElement}
     */
    _createElementTreeElement: function(node, closingTag)
    {
        var treeElement = new WebInspector.ElementsTreeElement(node, closingTag);
        treeElement.setExpandable(!closingTag && this._hasVisibleChildren(node));
        treeElement.selectable = this._selectEnabled;
        return treeElement;
    },

    /**
     * @param {!WebInspector.ElementsTreeElement} treeElement
     * @param {!WebInspector.DOMNode} child
     * @return {?WebInspector.ElementsTreeElement}
     */
    _showChild: function(treeElement, child)
    {
        if (treeElement.isClosingTag())
            return null;

        var index = this._visibleChildren(treeElement.node()).indexOf(child);
        if (index === -1)
            return null;

        if (index >= treeElement.expandedChildrenLimit())
            this.setExpandedChildrenLimit(treeElement, index + 1);
        return /** @type {!WebInspector.ElementsTreeElement} */ (treeElement.childAt(index));
    },

    /**
     * @param {!WebInspector.DOMNode} node
     * @return {!Array.<!WebInspector.DOMNode>} visibleChildren
     */
    _visibleChildren: function(node)
    {
        var visibleChildren = WebInspector.ElementsTreeElement.visibleShadowRoots(node);

        if (node.importedDocument())
            visibleChildren.push(node.importedDocument());

        if (node.templateContent())
            visibleChildren.push(node.templateContent());

        var beforePseudoElement = node.beforePseudoElement();
        if (beforePseudoElement)
            visibleChildren.push(beforePseudoElement);

        if (node.childNodeCount())
            visibleChildren = visibleChildren.concat(node.children());

        var afterPseudoElement = node.afterPseudoElement();
        if (afterPseudoElement)
            visibleChildren.push(afterPseudoElement);

        return visibleChildren;
    },

    /**
     * @param {!WebInspector.DOMNode} node
     * @return {boolean}
     */
    _hasVisibleChildren: function(node)
    {
        if (node.importedDocument())
            return true;
        if (node.templateContent())
            return true;
        if (WebInspector.ElementsTreeElement.visibleShadowRoots(node).length)
            return true;
        if (node.hasPseudoElements())
            return true;
        if (node.isInsertionPoint())
            return true;
        return !!node.childNodeCount() && !WebInspector.ElementsTreeElement.canShowInlineText(node);
    },

    /**
     * @param {!WebInspector.ElementsTreeElement} treeElement
     */
    _createExpandAllButtonTreeElement: function(treeElement)
    {
        var button = createTextButton("", handleLoadAllChildren.bind(this));
        button.value = "";
        var expandAllButtonElement = new TreeElement(button);
        expandAllButtonElement.selectable = false;
        expandAllButtonElement.expandAllButton = true;
        expandAllButtonElement.button = button;
        return expandAllButtonElement;

        /**
         * @this {WebInspector.ElementsTreeOutline}
         * @param {!Event} event
         */
        function handleLoadAllChildren(event)
        {
            var visibleChildCount = this._visibleChildren(treeElement.node()).length;
            this.setExpandedChildrenLimit(treeElement, Math.max(visibleChildCount, treeElement.expandedChildrenLimit() + WebInspector.ElementsTreeElement.InitialChildrenLimit));
            event.consume();
        }
    },

    /**
     * @param {!WebInspector.ElementsTreeElement} treeElement
     * @param {number} expandedChildrenLimit
     */
    setExpandedChildrenLimit: function(treeElement, expandedChildrenLimit)
    {
        if (treeElement.expandedChildrenLimit() === expandedChildrenLimit)
            return;

        treeElement.setExpandedChildrenLimit(expandedChildrenLimit);
        if (treeElement.treeOutline && !this._treeElementsBeingUpdated.has(treeElement))
            this._updateModifiedParentNode(treeElement.node());
    },

    /**
     * @param {!WebInspector.ElementsTreeElement} treeElement
     */
    _updateChildren: function(treeElement)
    {
        if (!treeElement.isExpandable()) {
            var selectedTreeElement = treeElement.treeOutline.selectedTreeElement;
            if (selectedTreeElement && selectedTreeElement.hasAncestor(treeElement))
                treeElement.select(true);
            treeElement.removeChildren();
            return;
        }

        console.assert(!treeElement.isClosingTag());

        treeElement.node().getChildNodes(childNodesLoaded.bind(this));

       /**
         * @param {?Array.<!WebInspector.DOMNode>} children
         * @this {WebInspector.ElementsTreeOutline}
         */
        function childNodesLoaded(children)
        {
            // FIXME: sort this out, it should not happen.
            if (!children)
                return;
            this._innerUpdateChildren(treeElement);
        }
    },

    /**
     * @param {!WebInspector.ElementsTreeElement} treeElement
     * @param {!WebInspector.DOMNode} child
     * @param {number} index
     * @param {boolean=} closingTag
     * @return {!WebInspector.ElementsTreeElement}
     */
    insertChildElement: function(treeElement, child, index, closingTag)
    {
        var newElement = this._createElementTreeElement(child, closingTag);
        treeElement.insertChild(newElement, index);
        return newElement;
    },

    /**
     * @param {!WebInspector.ElementsTreeElement} treeElement
     * @param {!WebInspector.ElementsTreeElement} child
     * @param {number} targetIndex
     */
    _moveChild: function(treeElement, child, targetIndex)
    {
        if (treeElement.indexOfChild(child) === targetIndex)
            return;
        var wasSelected = child.selected;
        if (child.parent)
            child.parent.removeChild(child);
        treeElement.insertChild(child, targetIndex);
        if (wasSelected)
            child.select();
    },

    /**
     * @param {!WebInspector.ElementsTreeElement} treeElement
     */
    _innerUpdateChildren: function(treeElement)
    {
        if (this._treeElementsBeingUpdated.has(treeElement))
            return;

        this._treeElementsBeingUpdated.add(treeElement);

        var node = treeElement.node();
        var visibleChildren = this._visibleChildren(node);
        var visibleChildrenSet = new Set(visibleChildren);

        // Remove any tree elements that no longer have this node as their parent and save
        // all existing elements that could be reused. This also removes closing tag element.
        var existingTreeElements = new Map();
        for (var i = treeElement.childCount() - 1; i >= 0; --i) {
            var existingTreeElement = treeElement.childAt(i);
            if (!(existingTreeElement instanceof WebInspector.ElementsTreeElement)) {
                // Remove expand all button and shadow host toolbar.
                treeElement.removeChildAtIndex(i);
                continue;
            }
            var elementsTreeElement = /** @type {!WebInspector.ElementsTreeElement} */ (existingTreeElement);
            var existingNode = elementsTreeElement.node();

            if (visibleChildrenSet.has(existingNode)) {
                existingTreeElements.set(existingNode, existingTreeElement);
                continue;
            }

            treeElement.removeChildAtIndex(i);
        }

        for (var i = 0; i < visibleChildren.length && i < treeElement.expandedChildrenLimit(); ++i) {
            var child = visibleChildren[i];
            var existingTreeElement = existingTreeElements.get(child) || this.findTreeElement(child);
            if (existingTreeElement && existingTreeElement !== treeElement) {
                // If an existing element was found, just move it.
                this._moveChild(treeElement, existingTreeElement, i);
            } else {
                // No existing element found, insert a new element.
                var newElement = this.insertChildElement(treeElement, child, i);
                if (this._updateRecordForHighlight(node) && treeElement.expanded)
                    WebInspector.ElementsTreeElement.animateOnDOMUpdate(newElement);
                // If a node was inserted in the middle of existing list dynamically we might need to increase the limit.
                if (treeElement.childCount() > treeElement.expandedChildrenLimit())
                    this.setExpandedChildrenLimit(treeElement, treeElement.expandedChildrenLimit() + 1);
            }
        }

        // Update expand all button.
        var expandedChildCount = treeElement.childCount();
        if (visibleChildren.length > expandedChildCount) {
            var targetButtonIndex = expandedChildCount;
            if (!treeElement.expandAllButtonElement)
                treeElement.expandAllButtonElement = this._createExpandAllButtonTreeElement(treeElement);
            treeElement.insertChild(treeElement.expandAllButtonElement, targetButtonIndex);
            treeElement.expandAllButtonElement.button.textContent = WebInspector.UIString("Show All Nodes (%d More)", visibleChildren.length - expandedChildCount);
        } else if (treeElement.expandAllButtonElement) {
            delete treeElement.expandAllButtonElement;
        }

        // Insert shortcuts to distrubuted children.
        if (node.isInsertionPoint()) {
            for (var distributedNode of node.distributedNodes())
                treeElement.appendChild(new WebInspector.ElementsTreeOutline.ShortcutTreeElement(distributedNode));
        }

        // Insert close tag.
        if (node.nodeType() === Node.ELEMENT_NODE && treeElement.isExpandable())
            this.insertChildElement(treeElement, node, treeElement.childCount(), true);

        this._treeElementsBeingUpdated.delete(treeElement);
    },

    /**
     * @param {!WebInspector.Event} event
     */
    _markersChanged: function(event)
    {
        var node = /** @type {!WebInspector.DOMNode} */ (event.data);
        var treeElement = node[this._treeElementSymbol];
        if (treeElement)
            treeElement.updateDecorations();
    },

    __proto__: TreeOutline.prototype
}

/**
 * @constructor
 */
WebInspector.ElementsTreeOutline.UpdateRecord = function()
{
}

WebInspector.ElementsTreeOutline.UpdateRecord.prototype = {
    /**
     * @param {string} attrName
     */
    attributeModified: function(attrName)
    {
        if (this._removedAttributes && this._removedAttributes.has(attrName))
            this._removedAttributes.delete(attrName);
        if (!this._modifiedAttributes)
            this._modifiedAttributes = /** @type {!Set.<string>} */ (new Set());
        this._modifiedAttributes.add(attrName);
    },

    /**
     * @param {string} attrName
     */
    attributeRemoved: function(attrName)
    {
        if (this._modifiedAttributes && this._modifiedAttributes.has(attrName))
            this._modifiedAttributes.delete(attrName);
        if (!this._removedAttributes)
            this._removedAttributes = /** @type {!Set.<string>} */ (new Set());
        this._removedAttributes.add(attrName);
    },

    /**
     * @param {!WebInspector.DOMNode} node
     */
    nodeInserted: function(node)
    {
        this._hasChangedChildren = true;
    },

    nodeRemoved: function(node)
    {
        this._hasChangedChildren = true;
        this._hasRemovedChildren = true;
    },

    charDataModified: function()
    {
        this._charDataModified = true;
    },

    childrenModified: function()
    {
        this._hasChangedChildren = true;
    },

    /**
     * @param {string} attributeName
     * @return {boolean}
     */
    isAttributeModified: function(attributeName)
    {
        return this._modifiedAttributes && this._modifiedAttributes.has(attributeName);
    },

    /**
     * @return {boolean}
     */
    hasRemovedAttributes: function()
    {
        return !!this._removedAttributes && !!this._removedAttributes.size;
    },

    /**
     * @return {boolean}
     */
    isCharDataModified: function()
    {
        return !!this._charDataModified;
    },

    /**
     * @return {boolean}
     */
    hasChangedChildren: function()
    {
        return !!this._hasChangedChildren;
    },

    /**
     * @return {boolean}
     */
    hasRemovedChildren: function()
    {
        return !!this._hasRemovedChildren;
    }
}

/**
 * @constructor
 * @implements {WebInspector.Renderer}
 */
WebInspector.ElementsTreeOutline.Renderer = function()
{
}

WebInspector.ElementsTreeOutline.Renderer.prototype = {
    /**
     * @override
     * @param {!Object} object
     * @return {!Promise.<!Element>}
     */
    render: function(object)
    {
        return new Promise(renderPromise);

        /**
         * @param {function(!Element)} resolve
         * @param {function(!Error)} reject
         */
        function renderPromise(resolve, reject)
        {
            if (object instanceof WebInspector.DOMNode) {
                onNodeResolved(/** @type {!WebInspector.DOMNode} */ (object));
            } else if (object instanceof WebInspector.DeferredDOMNode) {
                (/** @type {!WebInspector.DeferredDOMNode} */ (object)).resolve(onNodeResolved);
            } else if (object instanceof WebInspector.RemoteObject) {
                var domModel = WebInspector.DOMModel.fromTarget((/** @type {!WebInspector.RemoteObject} */ (object)).target());
                if (domModel)
                    domModel.pushObjectAsNodeToFrontend(object, onNodeResolved);
                else
                    reject(new Error("No dom model for given JS object target found."));
            } else {
                reject(new Error("Can't reveal not a node."));
            }

            /**
             * @param {?WebInspector.DOMNode} node
             */
            function onNodeResolved(node)
            {
                if (!node) {
                    reject(new Error("Could not resolve node."));
                    return;
                }
                var treeOutline = new WebInspector.ElementsTreeOutline(node.domModel(), false, false);
                treeOutline.rootDOMNode = node;
                if (!treeOutline.firstChild().isExpandable())
                    treeOutline._element.classList.add("single-node");
                treeOutline.setVisible(true);
                treeOutline.element.treeElementForTest = treeOutline.firstChild();
                resolve(treeOutline.element);
            }
        }
    }
}

/**
 * @constructor
 * @extends {TreeElement}
 * @param {!WebInspector.DOMNodeShortcut} nodeShortcut
 */
WebInspector.ElementsTreeOutline.ShortcutTreeElement = function(nodeShortcut)
{
    TreeElement.call(this, "");
    this.listItemElement.createChild("div", "selection");
    var title = this.listItemElement.createChild("span", "elements-tree-shortcut-title");
    var text = nodeShortcut.nodeName.toLowerCase();
    if (nodeShortcut.nodeType === Node.ELEMENT_NODE)
        text = "<" + text + ">";
    title.textContent = "\u21AA " + text;

    var link = WebInspector.DOMPresentationUtils.linkifyDeferredNodeReference(nodeShortcut.deferredNode);
    this.listItemElement.createTextChild(" ");
    link.classList.add("elements-tree-shortcut-link");
    link.textContent = WebInspector.UIString("reveal");
    this.listItemElement.appendChild(link);
    this._nodeShortcut = nodeShortcut;
}

WebInspector.ElementsTreeOutline.ShortcutTreeElement.prototype = {
    /**
     * @return {boolean}
     */
    get hovered()
    {
        return this._hovered;
    },

    set hovered(x)
    {
        if (this._hovered === x)
            return;
        this._hovered = x;
        this.listItemElement.classList.toggle("hovered", x);
    },

    updateSelection: function()
    {
    },

    /**
     * @return {number}
     */
    backendNodeId: function()
    {
        return this._nodeShortcut.deferredNode.backendNodeId();
    },

    /**
     * @override
     * @param {boolean=} selectedByUser
     * @return {boolean}
     */
    onselect: function(selectedByUser)
    {
        if (!selectedByUser)
            return true;
        this._nodeShortcut.deferredNode.highlight();
        this._nodeShortcut.deferredNode.resolve(resolved.bind(this));
        /**
         * @param {?WebInspector.DOMNode} node
         * @this {WebInspector.ElementsTreeOutline.ShortcutTreeElement}
         */
        function resolved(node)
        {
            if (node) {
                this.treeOutline._selectedDOMNode = node;
                this.treeOutline._selectedNodeChanged();
            }
        }
        return true;
    },

    __proto__: TreeElement.prototype
}


text:
<?php

namespace denbora\R_T_G_Services\services\RESTv3;

use denbora\R_T_G_Services\R_T_G_ServiceException;

class LobbyService extends RestV3Service
{
    const SERVICE_NAME = 'Lobby';

    /**
     * @param string $queryJSON
     * @return array|mixed|object|string
     * @throws R_T_G_ServiceException
     */
    public function getMenusGET($queryJSON = '{}')
    {
        return $this->callMethod(self::SERVICE_NAME, 'GetMenus', $queryJSON);
    }

    /**
     * @param string $queryJSON
     * @return array|mixed|object|string
     * @throws R_T_G_ServiceException
     */
    public function getAllSubMenusGET($queryJSON = '{}')
    {
        return $this->callMethod(self::SERVICE_NAME, 'GetAllSubMenus', $queryJSON);
    }

    /**
     * @param string $queryJSON
     * @return array|mixed|object|string
     * @throws R_T_G_ServiceException
     */
    public function getSubMenusGET($queryJSON = '{}')
    {
        return $this->callMethod(self::SERVICE_NAME, 'GetSubMenus', $queryJSON);
    }

    /**
     * @param string $queryJSON
     * @return array|mixed|object|string
     * @throws R_T_G_ServiceException
     */
    public function getGameInformationGET($queryJSON = '{}')
    {
        return $this->callMethod(self::SERVICE_NAME, 'GetGameInformation', $queryJSON);
    }

    /**
     * @param string $queryJSON
     * @return array|mixed|object|string
     * @throws R_T_G_ServiceException
     */
    public function getFullMenuStructureGET($queryJSON = '{}')
    {
        return $this->callMethod(self::SERVICE_NAME, 'GetFullMenuStructure', $queryJSON);
    }

    /**
     * @param string $queryJSON
     * @return array|mixed|object|string
     * @throws R_T_G_ServiceException
     */
    public function getGamesGET($queryJSON = '{}')
    {
        return $this->callMethod(self::SERVICE_NAME, 'GetGames', $queryJSON);
    }

    /**
     * @param string $queryJSON
     * @return array|mixed|object|string
     * @throws R_T_G_ServiceException
     */
    public function getMarqueeMessagesGET($queryJSON = '{}')
    {
        return $this->callMethod(self::SERVICE_NAME, 'GetMarqueeMessages', $queryJSON);
    }

    /**
     * @param string $queryJSON
     * @return array|mixed|object|string
     * @throws R_T_G_ServiceException
     */
    public function getGamesByMenuGET($queryJSON = '{}')
    {
        return $this->callMethod(self::SERVICE_NAME, 'GetGamesByMenu', $queryJSON);
    }

    /**
     * @param string $queryJSON
     * @return array|mixed|object|string
     * @throws R_T_G_ServiceException
     */
    public function getGamesBySubMenuGET($queryJSON = '{}')
    {
        return $this->callMethod(self::SERVICE_NAME, 'GetGamesBySubMenu', $queryJSON);
    }

    /**
     * @param string $queryJSON
     * @return array|mixed|object|string
     * @throws R_T_G_ServiceException
     */
    public function getGamesBySubMenuAndMenuGET($queryJSON = '{}')
    {
        return $this->callMethod(self::SERVICE_NAME, 'GetGamesBySubMenuAndMenu', $queryJSON);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.vmware.vim25;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for DvsVNicProfile complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="DvsVNicProfile">
 *   <complexContent>
 *     <extension base="{urn:vim25}ApplyProfile">
 *       <sequence>
 *         <element name="key" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         <element name="ipConfig" type="{urn:vim25}IpAddressProfile"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "DvsVNicProfile", propOrder = {
    "key",
    "ipConfig"
})
@XmlSeeAlso({
    DvsServiceConsoleVNicProfile.class,
    DvsHostVNicProfile.class
})
public class DvsVNicProfile
    extends ApplyProfile
{

    @XmlElement(required = true)
    protected String key;
    @XmlElement(required = true)
    protected IpAddressProfile ipConfig;

    /**
     * Gets the value of the key property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getKey() {
        return key;
    }

    /**
     * Sets the value of the key property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setKey(String value) {
        this.key = value;
    }

    /**
     * Gets the value of the ipConfig property.
     *
     * @return
     *     possible object is
     *     {@link IpAddressProfile }
     *
     */
    public IpAddressProfile getIpConfig() {
        return ipConfig;
    }

    /**
     * Sets the value of the ipConfig property.
     *
     * @param value
     *     allowed object is
     *     {@link IpAddressProfile }
     *
     */
    public void setIpConfig(IpAddressProfile value) {
        this.ipConfig = value;
    }

}


text:
%!TEX root=../../main.tex

\paragraph{OR'2014} This appendix contains the paper submitted to the $9^{th}$
International Conference on Open Repositories (OR'2014), taking place in
Helsinki, Finland. It is the leading conference in its field, with hundreds of
participants from all around the world. The website of the conference is
\url{http://or2014.helsinki.fi/}.

Note that this paper was authored approximately two months before the end of
the project, and thus, certain details might be missing or inaccurate in
regards to the final state of the deliverable.

Paper follows on next page, the length being of three pages.

\paragraph{AAHEP7} A presentation regarding the annotation developments in
Invenio will be given by Dr. Tibor \v{S}imko at the $7^{th}$ Summit of
Information Providers in Astronomy, Astrophysics and High Energy Physics. This
summit is attended by representatives of organisations providing access to
information in these fields, such as INSPIRE, ADS or arXiv, and major
publishers such as the American Institute of Physics (AIP), American Physical
Society (APS), Elsevier, Institute of Physics (IOP) or Springer. It will take
place at the Stony Brook University, Stony Brook, New York, United States of
America, between 1--3 April, 2014. The event's website is
\url{http://indico.cern.ch/event/262430/}.

\includepdf[pages={1-3},frame=true,noautoscale=true,scale=0.85]{static/pdf/or2014-invenio-annotations.pdf}


text:
namespace MyTunesShop
{
    using System;
    using System.Collections.Generic;

    public class Band : Performer, IBand
    {
        public Band(string name)
            : base(name)
        {
            this.Members = new List<string>();
        }

        public override PerformerType Type
        {
            get
            {
                return PerformerType.Band;
            }
        }

        public IList<string> Members { get; private set; }

        public void AddMember(string memberName)
        {
            this.Members.Add(memberName);
        }
    }
}


text:
update indicators

set chart_label = 'White'
where title = 'wsamehse1y'
;

update indicators
set chart_label = 'Black'
where title = 'bsamehse1y'
;

update indicators
set chart_label = 'Asian/Pacific Islander'
where title = 'asamehse1y'
;

update indicators
set chart_label = 'Other Race'
where title = 'osamehse1y'
;

update indicators
set chart_label = 'Hispanic'
where title = 'hsamehse1y'
;

-- diffhs1y
update indicators
set chart_label = 'White'
where title = 'wdiffhs1y'
;

update indicators
set chart_label = 'Black'
where title = 'bdiffhs1y'
;

update indicators
set chart_label = 'Asian/Pacific Islander'
where title = 'adiffhs1y'
;

update indicators
set chart_label = 'Other Race'
where title = 'odiffhs1y'
;

update indicators
set chart_label = 'Hispanic'
where title = 'hdiffhs1y'
;


text:
package anubis.runtime.java;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.Test;
import anubis.AbstractTest;
import anubis.AnubisObject;
import anubis.runtime.AObjects;

public class SetAdapterTest extends AbstractTest {
	/**
	 * adapter へ add した要素を origin から確認
	 */
	@Test
	public void testAdd() {
		Set<Integer> origin = new HashSet<Integer>();
		Set<AnubisObject> set = new SetAdapter<Integer>(origin, Integer.class);
		set.add(AObjects.getNumber(1));
		set.add(AObjects.getNumber(2));

		assertEquals(2, origin.size());
		assertTrue(origin.contains(1));
		assertTrue(origin.contains(2));
		assertFalse(origin.contains(3));
	}

	/**
	 * origin の要素を adapter から確認
	 */
	@Test
	public void testGet() {
		Set<Integer> origin = new HashSet<Integer>();
		Set<AnubisObject> set = new SetAdapter<Integer>(origin, Integer.class);
		origin.add(1);
		origin.add(2);

		assertEquals(2, set.size());
		assertTrue(set.contains(AObjects.getNumber(1)));
		assertTrue(set.contains(AObjects.getNumber(2)));
		assertFalse(set.contains(AObjects.getNumber(3)));
	}

	/**
	 * adapter から remove した要素を origin から確認
	 */
	@Test
	public void testRemove() {
		List<Integer> origin = new ArrayList<Integer>();
		origin.add(1);
		origin.add(2);
		origin.add(3);
		List<AnubisObject> set = new ListAdapter<Integer>(origin, Integer.class);
		set.remove(AObjects.getNumber(2));

		assertEquals(2, set.size());
		assertTrue(set.contains(AObjects.getNumber(1)));
		assertFalse(set.contains(AObjects.getNumber(2)));
		assertTrue(set.contains(AObjects.getNumber(3)));
	}

	/**
	 * adapter と origin の size が一致することを確認
	 */
	@Test
	public void testSize() {
		Set<Integer> origin = new HashSet<Integer>();
		Set<AnubisObject> set = new SetAdapter<Integer>(origin, Integer.class);
		assertEquals(0, origin.size());
		assertEquals(0, set.size());

		set.add(AObjects.getNumber(1));
		assertEquals(1, origin.size());
		assertEquals(1, set.size());

		origin.add(2);
		assertEquals(2, origin.size());
		assertEquals(2, set.size());
	}
}


text:
layout: default
---

{% include post-overlay.html %}

collapse map

expand map

{% include post-details-view.html %}


text:
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import { Provider } from 'react-redux'

import Posts from './components/Posts'
import PostForm from './components/Postform'

import store from './store'

class App extends Component {
  render() {
    return (
      <Provider store={store}>

Welcome to React

          <PostForm />

          <Posts />

      </Provider>
    );
  }
}

export default App;


text:
package com.asakusafw.utils.java.parser.javadoc;

import java.text.MessageFormat;

import com.asakusafw.utils.java.internal.parser.javadoc.ir.IrLocation;

/**
 * An exception which is occurred when the suitable {@link JavadocBlockParser} is not found while parsing documents.
 */
public class MissingJavadocBlockParserException extends JavadocParseException {

    private static final long serialVersionUID = 1L;

    private final String tagName;

    /**
     * Creates a new instance.
     * @param tagName the target tag name
     * @param location the parsing location
     * @param cause the original exception (nullable)
     */
    public MissingJavadocBlockParserException(String tagName, IrLocation location, Throwable cause) {
        super(buildMessage(tagName), location, cause);
        this.tagName = tagName;
    }

    private static String buildMessage(String tag) {
        String blockName = (tag == null
                ? Messages.getString("MissingJavadocBlockParserException.nameSynopsisBlock") //$NON-NLS-1$
                : tag);
        return MessageFormat.format(
                Messages.getString("MissingJavadocBlockParserException.errorMissingBlockParser"),  //$NON-NLS-1$
                blockName);
    }

    /**
     * Returns the target tag name.
     * @return the target tag name, or {@code null} if the target is a synopsis block
     */
    public String getTagName() {
        return this.tagName;
    }
}


text:
#include "src/fastertransformer/models/gptj/GptJContextDecoder.h"
#include "src/fastertransformer/kernels/gpt_kernels.h"

#include "src/fastertransformer/layers/TensorParallelGeluFfnLayer.h"
#include "src/fastertransformer/layers/attention_layers/TensorParallelGptContextAttentionLayer.h"

namespace fastertransformer {

template<typename T>
void GptJContextDecoder<T>::initialize()
{
    self_attention_layer_ = new TensorParallelGptContextAttentionLayer<T>(max_batch_size_,
                                                                          max_seq_len_,
                                                                          head_num_,
                                                                          size_per_head_,
                                                                          rotary_embedding_dim_,
                                                                          neox_rotary_style_,
                                                                          tensor_para_,
                                                                          stream_,
                                                                          cublas_wrapper_,
                                                                          allocator_,
                                                                          true,
                                                                          is_free_buffer_after_forward_,
                                                                          is_qk_buf_float_,
                                                                          false,
                                                                          custom_all_reduce_comm_,
                                                                          enable_custom_all_reduce_);

    ffn_layer_ = new TensorParallelGeluFfnLayer<T>(max_batch_size_,
                                                   max_seq_len_,
                                                   head_num_,
                                                   size_per_head_,
                                                   inter_size_,
                                                   tensor_para_,
                                                   stream_,
                                                   cublas_wrapper_,
                                                   allocator_,
                                                   true,
                                                   is_free_buffer_after_forward_,
                                                   false,
                                                   0,
                                                   false,  // use_gated_activation = false;
                                                   custom_all_reduce_comm_,
                                                   enable_custom_all_reduce_);
}

template<typename T>
void GptJContextDecoder<T>::allocateBuffer()
{
    FT_CHECK(false);
}

template<typename T>
void GptJContextDecoder<T>::allocateBuffer(size_t batch_size, size_t seq_len)
{
    decoder_normed_input_ = reinterpret_cast<T*>(
        allocator_->reMalloc(decoder_normed_input_, sizeof(T) * batch_size * seq_len * hidden_units_, false));
    self_attn_output_ = reinterpret_cast<T*>(
        allocator_->reMalloc(self_attn_output_, sizeof(T) * batch_size * seq_len * hidden_units_, false));
    ffn_output_ = reinterpret_cast<T*>(
        allocator_->reMalloc(ffn_output_, sizeof(T) * batch_size * seq_len * hidden_units_, false));
    decoder_layer_output_ = reinterpret_cast<T*>(
        allocator_->reMalloc(decoder_layer_output_, sizeof(T) * batch_size * seq_len * hidden_units_, false));
    is_allocate_buffer_ = true;
}

template<typename T>
void GptJContextDecoder<T>::freeBuffer()
{
    if (is_allocate_buffer_ == true) {
        allocator_->free((void**)(&decoder_normed_input_));
        allocator_->free((void**)(&self_attn_output_));
        allocator_->free((void**)(&ffn_output_));
        allocator_->free((void**)(&decoder_layer_output_));
        is_allocate_buffer_ = false;
    }
}

template<typename T>
bool GptJContextDecoder<T>::isValidLayerParallelId(uint l)
{
    int local_num_layer = (int)(ceil(num_layer_ * 1.0f / pipeline_para_.world_size_));
    return l < num_layer_ && (l >= local_num_layer * pipeline_para_.rank_)
           && (l < local_num_layer * (pipeline_para_.rank_ + 1));
}

template<typename T>
bool GptJContextDecoder<T>::isFirstLayerParallelId(uint l)
{
    int local_num_layer = (int)(ceil(num_layer_ * 1.0f / pipeline_para_.world_size_));
    return l < num_layer_ && (l == local_num_layer * pipeline_para_.rank_);
}

template<typename T>
bool GptJContextDecoder<T>::isLastLayerParallelId(uint l)
{
    int local_num_layer = (int)(ceil(num_layer_ * 1.0f / pipeline_para_.world_size_));
    return l < num_layer_ && (l == local_num_layer * (pipeline_para_.rank_ + 1) - 1);
}

template<typename T>
int GptJContextDecoder<T>::getFirstLayerParallelId()
{
    int local_num_layer = (int)(ceil(num_layer_ * 1.0f / pipeline_para_.world_size_));
    return local_num_layer * pipeline_para_.rank_;
}

template<typename T>
GptJContextDecoder<T>::GptJContextDecoder(size_t                              max_batch_size,
                                          size_t                              max_seq_len,
                                          size_t                              head_num,
                                          size_t                              size_per_head,
                                          size_t                              inter_size,
                                          size_t                              num_layer,
                                          size_t                              rotary_embedding_dim,
                                          bool                                neox_rotary_style,
                                          float                               layernorm_eps,
                                          NcclParam                           tensor_para,
                                          NcclParam                           pipeline_para,
                                          cudaStream_t                        stream,
                                          cublasMMWrapper*                    cublas_wrapper,
                                          IAllocator*                         allocator,
                                          bool                                is_free_buffer_after_forward,
                                          bool                                is_qk_buf_float,
                                          std::shared_ptr<AbstractCustomComm> custom_all_reduce_comm,
                                          int                                 enable_custom_all_reduce):
    BaseLayer(stream, cublas_wrapper, allocator, is_free_buffer_after_forward),
    max_batch_size_(max_batch_size),
    max_seq_len_(max_seq_len),
    head_num_(head_num),
    size_per_head_(size_per_head),
    inter_size_(inter_size),
    num_layer_(num_layer),
    rotary_embedding_dim_(rotary_embedding_dim),
    neox_rotary_style_(neox_rotary_style),
    layernorm_eps_(layernorm_eps),
    hidden_units_(head_num * size_per_head),
    tensor_para_(tensor_para),
    pipeline_para_(pipeline_para),
    is_qk_buf_float_(is_qk_buf_float),
    custom_all_reduce_comm_(custom_all_reduce_comm),
    enable_custom_all_reduce_(enable_custom_all_reduce)
{
    initialize();
}

template<typename T>
GptJContextDecoder<T>::GptJContextDecoder(GptJContextDecoder<T> const& decoder):
    BaseLayer(decoder.stream_, decoder.cublas_wrapper_, decoder.allocator_, decoder.is_free_buffer_after_forward_),
    max_batch_size_(decoder.max_batch_size_),
    max_seq_len_(decoder.max_seq_len_),
    head_num_(decoder.head_num_),
    size_per_head_(decoder.size_per_head_),
    inter_size_(decoder.inter_size_),
    num_layer_(decoder.num_layer_),
    rotary_embedding_dim_(decoder.rotary_embedding_dim_),
    layernorm_eps_(decoder.layernorm_eps_),
    hidden_units_(decoder.hidden_units_),
    tensor_para_(decoder.tensor_para_),
    pipeline_para_(decoder.pipeline_para_),
    is_qk_buf_float_(decoder.is_qk_buf_float_),
    custom_all_reduce_comm_(decoder.custom_all_reduce_comm_),
    enable_custom_all_reduce_(decoder.enable_custom_all_reduce_)
{
    initialize();
}

template<typename T>
GptJContextDecoder<T>::~GptJContextDecoder()
{
    delete self_attention_layer_;
    delete ffn_layer_;
    freeBuffer();
}

template<typename T>
void GptJContextDecoder<T>::forward(std::vector<Tensor>*                          output_tensors,
                                    const std::vector<Tensor>*                    input_tensors,
                                    const std::vector<GptJDecoderLayerWeight<T>>* gpt_decoder_layer_weight)
{
    std::unordered_map<std::string, Tensor> input_tensors_map{{"decoder_input", input_tensors->at(0)},
                                                              {"attention_mask", input_tensors->at(1)},
                                                              {"input_lengths", input_tensors->at(2)}};
    std::unordered_map<std::string, Tensor> output_tensors_map{{"decoder_output", output_tensors->at(0)},
                                                               {"key_cache", output_tensors->at(1)},
                                                               {"value_cache", output_tensors->at(2)},
                                                               {"last_token_hidden_units", output_tensors->at(3)}};

    forward(&output_tensors_map, &input_tensors_map, gpt_decoder_layer_weight);
}

template<typename T>
void GptJContextDecoder<T>::forward(std::unordered_map<std::string, Tensor>*       output_tensors,
                                    const std::unordered_map<std::string, Tensor>* input_tensors,
                                    const std::vector<GptJDecoderLayerWeight<T>>*  gpt_decoder_layer_weight)
{
    // input tensors:
    //      decoder_input [batch_size, seq_len, hidden_dimension],
    //      attention_mask [batch_size, 1, seq_len, seq_len + max_prompt_length]
    //      input_lengths [batch_size]
    //      d_prefix_prompt_batch [batch_size],
    //          each element contains ptr with buffer shape[2, local_head_num_, prompt_length, size_per_head]
    //      prefix_prompt_lengths [batch size]

    // output tensors:
    //      decoder_output [batch_size, seq_len, hidden_dimension],
    //      key_cache [num_layer, batch, local_head_num, size_per_head // x, max_seq_len, x]
    //      value_cache [num_layer, batch, local_head_num, max_seq_len, size_per_head]
    //      last_token_hidden_units [batch_size, hidden_dimension]

    // To use layer/pipeline parallelism, we view the shape of 'batch_size' to 'ite * local_batch_size'.
    // For example, the shape of decoder_input becomes [ite, batch_size, seq_len, hidden_dimension] during
    // computing.

    FT_CHECK(input_tensors->size() == 5);
    FT_CHECK(output_tensors->size() == 4);

    const int batch_size = input_tensors->at("decoder_input").shape[0];
    const int seq_len    = input_tensors->at("decoder_input").shape[1];  // max_input_len
    const int max_prompt_length =
        input_tensors->at("attention_mask").shape[3] - input_tensors->at("attention_mask").shape[2];
    const DataType data_type = getTensorType<T>();
    allocateBuffer(batch_size, seq_len);

    T*         decoder_input           = (T*)input_tensors->at("decoder_input").data;
    T*         decoder_output          = (T*)output_tensors->at("decoder_output").data;
    const T*   attention_mask          = (const T*)input_tensors->at("attention_mask").data;
    const T**  d_prefix_prompt_batch   = (const T**)input_tensors->at("d_prefix_prompt_batch").data;
    const int* d_prefix_prompt_lengths = (const int*)input_tensors->at("d_prefix_prompt_lengths").data;

    const int local_batch_size = getLocalBatchSize(batch_size, seq_len, pipeline_para_.world_size_);
    FT_CHECK(batch_size % local_batch_size == 0);
    const int iteration_num = batch_size / local_batch_size;

    Tensor&             k_cache = output_tensors->at("key_cache");
    Tensor&             v_cache = output_tensors->at("value_cache");
    std::vector<size_t> self_k_cache_size;
    self_k_cache_size.push_back(local_batch_size);
    for (auto t = k_cache.shape.begin() + 2; t != k_cache.shape.end(); ++t) {
        self_k_cache_size.push_back(*t);
    }
    std::vector<size_t> self_v_cache_size;
    self_v_cache_size.push_back(local_batch_size);
    for (auto t = v_cache.shape.begin() + 2; t != v_cache.shape.end(); ++t) {
        self_v_cache_size.push_back(*t);
    }

    for (int ite = 0; ite < iteration_num; ite++) {
        for (int l = 0; l < num_layer_; l++) {
            if (isValidLayerParallelId(l) == false) {
                continue;
            }

            const bool is_final = false;  // TODO(bhsueh) remove this flag
            T*         layer_input =
                ((l == 0) ? decoder_input : decoder_layer_output_) + ite * local_batch_size * seq_len * hidden_units_;
            T* layer_output = ((l == num_layer_ - 1) ? decoder_output : decoder_layer_output_)
                              + ite * local_batch_size * seq_len * hidden_units_;

            if (isFirstLayerParallelId(l) && pipeline_para_.rank_ != 0 && pipeline_para_.world_size_ > 1) {
                int data_size = local_batch_size * seq_len * hidden_units_ / tensor_para_.world_size_;
                ftNcclRecv(layer_input + data_size * tensor_para_.rank_,
                           data_size,
                           pipeline_para_.rank_ - 1,
                           pipeline_para_,
                           stream_);
                if (tensor_para_.world_size_ > 1) {
                    ftNcclAllGather(layer_input, layer_input, data_size, tensor_para_.rank_, tensor_para_, stream_);
                }
            }

            invokeGeneralLayerNorm(decoder_normed_input_,
                                   layer_input,
                                   gpt_decoder_layer_weight->at(l).pre_layernorm_weights.gamma,
                                   gpt_decoder_layer_weight->at(l).pre_layernorm_weights.beta,
                                   layernorm_eps_,
                                   local_batch_size * seq_len,
                                   hidden_units_,
                                   stream_);
            sync_check_cuda_error();

            std::vector<Tensor> self_attention_input_tensors{
                Tensor{MEMORY_GPU,
                       data_type,
                       {(size_t)(local_batch_size * seq_len), (size_t)hidden_units_},
                       decoder_normed_input_},
                Tensor{MEMORY_GPU,
                       data_type,
                       {(size_t)local_batch_size, (size_t)1, (size_t)seq_len, (size_t)(seq_len + max_prompt_length)},
                       attention_mask + local_batch_size * ite * seq_len * (seq_len + max_prompt_length)},
                Tensor{MEMORY_CPU, TYPE_BOOL, {(size_t)1}, &is_final},  // NOTE: assume batch size = 1
                Tensor{MEMORY_GPU,
                       data_type,
                       {(size_t)local_batch_size},
                       d_prefix_prompt_batch != nullptr ? d_prefix_prompt_batch + ite * local_batch_size : nullptr},
                Tensor{MEMORY_GPU,
                       TYPE_INT32,
                       {(size_t)local_batch_size},
                       d_prefix_prompt_lengths != nullptr ? d_prefix_prompt_lengths + ite * local_batch_size : nullptr},
                Tensor{MEMORY_CPU, TYPE_INT32, {(size_t)1}, &l}};  // layer_id

            // NOTE: cache offer for specific layer
            size_t cache_offset = l - getFirstLayerParallelId();
            for (auto t = k_cache.shape.begin() + 1; t != k_cache.shape.end(); ++t) {
                cache_offset *= *t;
            };
            size_t ite_cache_offset = ite * local_batch_size;
            for (auto t = k_cache.shape.begin() + 2; t != k_cache.shape.end(); ++t) {
                ite_cache_offset *= *t;
            }
            cache_offset += ite_cache_offset;

            std::vector<Tensor> self_attention_output_tensors{
                Tensor{MEMORY_GPU,
                       data_type,
                       {(size_t)(local_batch_size * seq_len), (size_t)hidden_units_},
                       self_attn_output_},
                Tensor{MEMORY_GPU, data_type, self_k_cache_size, ((const T*)k_cache.data) + cache_offset},
                Tensor{MEMORY_GPU, data_type, self_v_cache_size, ((const T*)v_cache.data) + cache_offset}};

            self_attention_layer_->forward(&self_attention_output_tensors,
                                           &self_attention_input_tensors,
                                           &gpt_decoder_layer_weight->at(l).self_attention_weights);

            if (is_final == false) {
                std::vector<Tensor> ffn_input_tensors{
                    Tensor{MEMORY_GPU,
                           data_type,
                           {(size_t)(local_batch_size * seq_len), (size_t)hidden_units_},
                           decoder_normed_input_}};
                std::vector<Tensor> ffn_output_tensors{Tensor{
                    MEMORY_GPU, data_type, {(size_t)(local_batch_size * seq_len), (size_t)hidden_units_}, ffn_output_}};
                ffn_layer_->forward(
                    &ffn_output_tensors, &ffn_input_tensors, &gpt_decoder_layer_weight->at(l).ffn_weights);

                invokeAddBiasAttentionFfnResidual(layer_output,
                                                  ffn_output_,
                                                  self_attn_output_,
                                                  layer_input,
                                                  gpt_decoder_layer_weight->at(l).ffn_weights.output_weight.bias,
                                                  local_batch_size * seq_len,
                                                  hidden_units_,
                                                  stream_);
                sync_check_cuda_error();

                if (isLastLayerParallelId(l) && pipeline_para_.rank_ != pipeline_para_.world_size_ - 1
                    && pipeline_para_.world_size_ > 1) {
                    int data_size = local_batch_size * seq_len * hidden_units_ / tensor_para_.world_size_;
                    ftNcclSend(layer_output + data_size * tensor_para_.rank_,
                               data_size,
                               pipeline_para_.rank_ + 1,
                               pipeline_para_,
                               stream_);
                }
            }
        }
    }

    // TODO(bhsueh) We could optimize this point by only computing the last token for the last layer
    invokeLookupHiddenStateOfLastToken((T*)output_tensors->at("last_token_hidden_units").data,
                                       (T*)output_tensors->at("decoder_output").data,
                                       (int*)input_tensors->at("input_lengths").data,
                                       seq_len,
                                       batch_size,
                                       hidden_units_,
                                       stream_);
    sync_check_cuda_error();
    if (is_free_buffer_after_forward_ == true) {
        freeBuffer();
    }
}

template class GptJContextDecoder<float>;
template class GptJContextDecoder<half>;
#ifdef ENABLE_BF16
template class GptJContextDecoder<__nv_bfloat16>;
#endif
}  // namespace fastertransformer


text:
<!DOCTYPE html>

    <title>Earthquake Philippines</title>

    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">
    <meta name="theme-color" content="#682591"/>

    <meta name="author" content="Ridvan Baluyos">
    <meta name="description" content="Earthquake Philippines sends SMS and E-mail alerts whenever an earthquake occurs. It also provides safety, graphs and charts, references, and useful information about earthquakes."/>
    <meta name="keywords" content="earthquake today, earthquake philippines, earthquake alert, earthquake alert philippines, phivolcs"/>

    <meta property="og:locale" content="en_US"/>
    <meta property="og:type" content="website"/>
    <meta property="og:title" content="Home"/>
    <meta property="og:description" content="Earthquake Philippines sends SMS and E-mail alerts whenever an earthquake occurs. It also provides earthquake safety tips and information, graphs and charts, references, and other useful information about earthquakes."/>
    <meta property="og:url" content="https://earthquake.ph"/>
    <meta property="og:site_name" content="Earthquake Philippines"/>
    <meta property="og:image" content="https://earthquake.ph/og-image.jpeg "/>

    <link href="https://www.earthquake.ph/amp" rel="amphtml"/>
    <link href="https://www.earthquake.ph" rel="canonical"/>
    <link rel="manifest" href="/manifest.json">

    <link rel="shortcut icon" href="/favicon.gif" type="image/x-icon">
    <link rel="icon" href="/favicon.ico" type="image/x-icon">

<button class="btn-amp-sidebar" on="tap:sidebar.toggle" aria-label="Sidebar Menu"></button>
<amp-sidebar id="sidebar" layout="nodisplay" side="left">

Home

All

Graphs

Heatmap

Safety and Preparedness

Earthquake 101

Hotlines

About

</amp-sidebar>

                                <amp-img alt="Logo" height="30" src="https://2.bp.blogspot.com/-Gwr5P8uOy7I/WARCMkUJUgI/AAAAAAAAHvs/wbnz3_FS8qI-RDwV9Gk4Tkk1LUfN0eCngCK4B/s1600/ampicon2.png" title="AMP HTML ⚡" width="30"></amp-img>
                                Earthquake Philippines

    @yield("content")

                        © 2017

                                earthquake.ph
                             ·

                                source code


text:
<?php
namespace Apps\Models;

use Cygnite\Database\Schema;
use Cygnite\Foundation\Application;
use Cygnite\Common\UrlManager\Url;
use Cygnite\Database\ActiveRecord;

class User extends ActiveRecord
{

    //your database connection name
    protected $database = 'tutorials';

    // your table name here (Optional)
    //protected $tableName = 'shopping_product';

    protected $primaryKey = 'id';

    public function __construct()
    {
        parent::__construct();
    }
}// End of the ShoppingProducts Model


text:
package org.apache.camel.management.mbean;

import org.apache.camel.CamelContext;
import org.apache.camel.api.management.ManagedResource;
import org.apache.camel.api.management.mbean.ManagedTypeConverterRegistryMBean;
import org.apache.camel.spi.TypeConverterRegistry;

/**
 *
 */
@ManagedResource(description = "Managed TypeConverterRegistry")
public class ManagedTypeConverterRegistry extends ManagedService implements ManagedTypeConverterRegistryMBean {

    private final TypeConverterRegistry registry;

    public ManagedTypeConverterRegistry(CamelContext context, TypeConverterRegistry registry) {
        super(context, registry);
        this.registry = registry;
    }

    public TypeConverterRegistry getRegistry() {
        return registry;
    }

    public long getAttemptCounter() {
        return registry.getStatistics().getAttemptCounter();
    }

    public long getHitCounter() {
        return registry.getStatistics().getHitCounter();
    }

    public long getMissCounter() {
        return registry.getStatistics().getMissCounter();
    }

    public long getFailedCounter() {
        return registry.getStatistics().getFailedCounter();
    }

    public void resetTypeConversionCounters() {
        registry.getStatistics().reset();
    }
}


text:
<?php

namespace Kvartiri\ControlPanelBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    public function indexAction()
    {
        $userId = $this->container->get('security.context')->getToken()->getUser()->getId(); // on récupere la fonction de l'utilisateur connecté
        if ($this->get('security.context')->isGranted('ROLE_COMPANY')) {

            return $this->render('KvartiriControlPanelBundle:ControlPanel:layout/layout.html.twig', array('userId' => $userId));

        }

    }

//    public function RedirectionagentAction() {
//
//        $user = $this->container->get('security.context')->getToken()->getUser()->getFonction(); // on récupere la fonction de l'utilisateur connecté
//        $userId = $this->container->get('security.context')->getToken()->getUser()->getId(); // on récupere la fonction de l'utilisateur connecté
//        $StatusProto = $this->getDoctrine()->getEntityManager()->getRepository('Inra2013urzBundle:Protocole')->StatusEncours();
//        $StatusFini=$this->getDoctrine()->getEntityManager()->getRepository('Inra2013urzBundle:Protocole')->StatusTermine() ;
//        $StatusProtoId = $this->getDoctrine()->getEntityManager()->getRepository('Inra2013urzBundle:Protocole')->StatusEncoursId($userId);
//        //   \Doctrine\Common\Util\Debug::dump($StatusFini);
//        if ($this->get('security.context')->isGranted('ROLE_ADMINISTRATEUR')) {
//
//
//            return $this->render("Inra2013urzBundle:Default:IndexAdmin.html.twig");
//
//        } elseif ($this->get('security.context')->isGranted('ROLE_RESPONSABLE')) {
//
//            if ($user == "Laborantin(e)") {
//
//                return $this->render("Inra2013urzBundle:Default:IndexUser.html.twig", array('response' => $StatusProto,'responseFini' => $StatusFini,'User'=>$user));
//
//            } else if ($user == "Chercheur") {
//
//                return $this->render("Inra2013urzBundle:Default:IndexChercheur.html.twig", array('response' => $StatusProtoId));
//            }
//
//        } elseif ($this->get('security.context')->isGranted('ROLE_UTILISATEUR')) {
//
//            if ($user == "Laborantin(e)") {
//
//                return $this->render("Inra2013urzBundle:Default:IndexUser.html.twig", array('response' => $StatusProto,'responseFini' => $StatusFini));
//
//            } else if ($user == "Chercheur") {
//
//                return $this->render("Inra2013urzBundle:Default:IndexChercheur.html.twig", array('response' => $StatusProtoId));
//            }
//        }
//    }
}