text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @constructor
 * @extends {WebInspector.VBox}
 */
WebInspector.DevicesView = function()
{
    WebInspector.VBox.call(this, true);
    this.registerRequiredCSS("devices/devicesView.css");
    this.contentElement.classList.add("devices-view");

    var hbox = this.contentElement.createChild("div", "hbox devices-container");
    var sidebar = hbox.createChild("div", "devices-sidebar");
    sidebar.createChild("div", "devices-view-title").createTextChild(WebInspector.UIString("Devices"));
    this._sidebarList = sidebar.createChild("div", "devices-sidebar-list");

    this._discoveryView = new WebInspector.DevicesView.DiscoveryView();
    this._sidebarListSpacer = this._sidebarList.createChild("div", "devices-sidebar-spacer");
    this._discoveryListItem = this._sidebarList.createChild("div", "devices-sidebar-item");
    this._discoveryListItem.textContent = WebInspector.UIString("Settings");
    this._discoveryListItem.addEventListener("click", this._selectSidebarListItem.bind(this, this._discoveryListItem, this._discoveryView));

    /** @type {!Map<string, !WebInspector.DevicesView.DeviceView>} */
    this._viewById = new Map();
    /** @type {!Array<!Adb.Device>} */
    this._devices = [];
    /** @type {!Map<string, !Element>} */
    this._listItemById = new Map();

    this._viewContainer = hbox.createChild("div", "flex-auto vbox");

    var discoveryFooter = this.contentElement.createChild("div", "devices-footer");
    this._deviceCountSpan = discoveryFooter.createChild("span");
    discoveryFooter.createChild("span").textContent = WebInspector.UIString(" Read ");
    discoveryFooter.appendChild(WebInspector.linkifyURLAsNode("https://developers.google.com/chrome-developer-tools/docs/remote-debugging", WebInspector.UIString("remote debugging documentation"), undefined, true));
    discoveryFooter.createChild("span").textContent = WebInspector.UIString(" for more information.");
    this._updateFooter();
    this._selectSidebarListItem(this._discoveryListItem, this._discoveryView);

    InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.DevicesUpdated, this._devicesUpdated, this);
    InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.DevicesDiscoveryConfigChanged, this._devicesDiscoveryConfigChanged, this);
    InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.DevicesPortForwardingStatusChanged, this._devicesPortForwardingStatusChanged, this);

    this.contentElement.tabIndex = 0;
    this.setDefaultFocusedElement(this.contentElement);
}

WebInspector.DevicesView.prototype = {
    /**
     * @param {!Element} listItem
     * @param {!WebInspector.Widget} view
     */
    _selectSidebarListItem: function(listItem, view)
    {
        if (this._selectedListItem === listItem)
            return;

        if (this._selectedListItem) {
            this._selectedListItem.classList.remove("selected");
            this._visibleView.detach();
        }

        this._visibleView = view;
        this._selectedListItem = listItem;
        this._visibleView.show(this._viewContainer);
        this._selectedListItem.classList.add("selected");
    },

    /**
     * @param {!WebInspector.Event} event
     */
    _devicesUpdated: function(event)
    {
        this._devices = /** @type {!Array.<!Adb.Device>} */ (event.data).slice().filter(d => d.adbSerial.toUpperCase() !== "WEBRTC");
        for (var device of this._devices) {
            if (!device.adbConnected)
                device.adbModel = WebInspector.UIString("Unknown");
        }

        var ids = new Set();
        for (var device of this._devices)
            ids.add(device.id);

        var selectedRemoved = false;
        for (var deviceId of this._viewById.keys()) {
            if (!ids.has(deviceId)) {
                var listItem = /** @type {!Element} */ (this._listItemById.get(deviceId));
                this._listItemById.remove(deviceId);
                this._viewById.remove(deviceId);
                listItem.remove();
                if (listItem === this._selectedListItem)
                    selectedRemoved = true;
            }
        }

        for (var device of this._devices) {
            var view = this._viewById.get(device.id);
            var listItem = this._listItemById.get(device.id);

            if (!view) {
                view = new WebInspector.DevicesView.DeviceView();
                this._viewById.set(device.id, view);
                listItem = this._createSidebarListItem(view);
                this._listItemById.set(device.id, listItem);
                this._sidebarList.insertBefore(listItem, this._sidebarListSpacer);
            }

            listItem._title.textContent = device.adbModel;
            listItem._status.textContent = device.adbConnected ? WebInspector.UIString("Connected") : WebInspector.UIString("Pending Authorization");
            listItem.classList.toggle("device-connected", device.adbConnected);
            view.update(device);
        }

        if (selectedRemoved)
            this._selectSidebarListItem(this._discoveryListItem, this._discoveryView);

        this._updateFooter();
    },

    /**
     * @param {!WebInspector.Widget} view
     * @return {!Element}
     */
    _createSidebarListItem: function(view)
    {
        var listItem = createElementWithClass("div", "devices-sidebar-item");
        listItem.addEventListener("click", this._selectSidebarListItem.bind(this, listItem, view));
        listItem._title = listItem.createChild("div", "devices-sidebar-item-title");
        listItem._status = listItem.createChild("div", "devices-sidebar-item-status");
        return listItem;
    },

    /**
     * @param {!WebInspector.Event} event
     */
    _devicesDiscoveryConfigChanged: function(event)
    {
        var discoverUsbDevices = /** @type {boolean} */ (event.data["discoverUsbDevices"]);
        var portForwardingEnabled = /** @type {boolean} */ (event.data["portForwardingEnabled"]);
        var portForwardingConfig = /** @type {!Adb.PortForwardingConfig} */ (event.data["portForwardingConfig"]);
        this._discoveryView.discoveryConfigChanged(discoverUsbDevices, portForwardingEnabled, portForwardingConfig);
    },

    /**
     * @param {!WebInspector.Event} event
     */
    _devicesPortForwardingStatusChanged: function(event)
    {
        var status = /** @type {!Adb.PortForwardingStatus} */ (event.data);
        for (var deviceId in status) {
            var view = this._viewById.get(deviceId);
            if (view)
                view.portForwardingStatusChanged(status[deviceId]);
        }
        for (var deviceId of this._viewById.keys()) {
            var view = this._viewById.get(deviceId);
            if (view && !(deviceId in status))
                view.portForwardingStatusChanged({ports: {}, browserId: ""});
        }
    },

    _updateFooter: function()
    {
        this._deviceCountSpan.textContent =
            !this._devices.length ? WebInspector.UIString("No devices detected.") :
                this._devices.length === 1 ? WebInspector.UIString("1 device detected.") : WebInspector.UIString("%d devices detected.", this._devices.length);
    },

    /**
     * @override
     */
    wasShown: function()
    {
        WebInspector.PanelWithSidebar.prototype.wasShown.call(this);
        InspectorFrontendHost.setDevicesUpdatesEnabled(true);
    },

    /**
     * @override
     */
    willHide: function()
    {
        WebInspector.PanelWithSidebar.prototype.wasShown.call(this);
        InspectorFrontendHost.setDevicesUpdatesEnabled(false);
    },

    __proto__: WebInspector.VBox.prototype
}

/**
 * @return {!WebInspector.DevicesView}
 */
WebInspector.DevicesView._instance = function()
{
    if (!WebInspector.DevicesView._instanceObject)
        WebInspector.DevicesView._instanceObject = new WebInspector.DevicesView();
    return WebInspector.DevicesView._instanceObject;
}

/**
 * @constructor
 * @extends {WebInspector.VBox}
 * @implements {WebInspector.ListWidget.Delegate}
 */
WebInspector.DevicesView.DiscoveryView = function()
{
    WebInspector.VBox.call(this);
    this.setMinimumSize(100, 100);
    this.element.classList.add("discovery-view");

    this.contentElement.createChild("div", "hbox device-text-row").createChild("div", "view-title").textContent = WebInspector.UIString("Settings");

    var discoverUsbDevicesCheckbox = createCheckboxLabel(WebInspector.UIString("Discover USB devices"));
    discoverUsbDevicesCheckbox.classList.add("usb-checkbox");
    this.element.appendChild(discoverUsbDevicesCheckbox);
    this._discoverUsbDevicesCheckbox = discoverUsbDevicesCheckbox.checkboxElement;
    this._discoverUsbDevicesCheckbox.addEventListener("click", this._updateDiscoveryConfig.bind(this), false);

    var help = this.element.createChild("div", "discovery-help");
    help.createChild("span").textContent = WebInspector.UIString("Need help? Read Chrome ");
    help.appendChild(WebInspector.linkifyURLAsNode("https://developers.google.com/chrome-developer-tools/docs/remote-debugging", WebInspector.UIString("remote debugging documentation."), undefined, true));

    var portForwardingHeader = this.element.createChild("div", "port-forwarding-header");
    var portForwardingEnabledCheckbox = createCheckboxLabel(WebInspector.UIString("Port forwarding"));
    portForwardingEnabledCheckbox.classList.add("port-forwarding-checkbox");
    portForwardingHeader.appendChild(portForwardingEnabledCheckbox);
    this._portForwardingEnabledCheckbox = portForwardingEnabledCheckbox.checkboxElement;
    this._portForwardingEnabledCheckbox.addEventListener("click", this._updateDiscoveryConfig.bind(this), false);

    var portForwardingFooter = this.element.createChild("div", "port-forwarding-footer");
    portForwardingFooter.createChild("span").textContent = WebInspector.UIString("Define the listening port on your device that maps to a port accessible from your development machine. ");
    portForwardingFooter.appendChild(WebInspector.linkifyURLAsNode("https://developer.chrome.com/devtools/docs/remote-debugging#port-forwarding", WebInspector.UIString("Learn more"), undefined, true));

    this._list = new WebInspector.ListWidget(this);
    this._list.registerRequiredCSS("devices/devicesView.css");
    this._list.element.classList.add("port-forwarding-list");
    var placeholder = createElementWithClass("div", "port-forwarding-list-empty");
    placeholder.textContent = WebInspector.UIString("No rules");
    this._list.setEmptyPlaceholder(placeholder);
    this._list.show(this.element);

    this.element.appendChild(createTextButton(WebInspector.UIString("Add rule"), this._addRuleButtonClicked.bind(this), "add-rule-button"));

    /** @type {!Array<!Adb.PortForwardingRule>} */
    this._portForwardingConfig = [];
}

WebInspector.DevicesView.DiscoveryView.prototype = {
    _addRuleButtonClicked: function()
    {
        this._list.addNewItem(this._portForwardingConfig.length, {port: "", address: ""});
    },

    /**
     * @param {boolean} discoverUsbDevices
     * @param {boolean} portForwardingEnabled
     * @param {!Adb.PortForwardingConfig} portForwardingConfig
     */
    discoveryConfigChanged: function(discoverUsbDevices, portForwardingEnabled, portForwardingConfig)
    {
        this._discoverUsbDevicesCheckbox.checked = discoverUsbDevices;
        this._portForwardingEnabledCheckbox.checked = portForwardingEnabled;

        this._portForwardingConfig = [];
        this._list.clear();
        for (var key of Object.keys(portForwardingConfig)) {
            var rule = /** @type {!Adb.PortForwardingRule} */ ({port: key, address: portForwardingConfig[key]});
            this._portForwardingConfig.push(rule);
            this._list.appendItem(rule, true);
        }
    },

    /**
     * @override
     * @param {*} item
     * @param {boolean} editable
     * @return {!Element}
     */
    renderItem: function(item, editable)
    {
        var rule = /** @type {!Adb.PortForwardingRule} */ (item);
        var element = createElementWithClass("div", "port-forwarding-list-item");
        var port = element.createChild("div", "port-forwarding-value port-forwarding-port");
        port.createChild("span", "port-localhost").textContent = WebInspector.UIString("localhost:");
        port.createTextChild(rule.port);
        element.createChild("div", "port-forwarding-separator");
        element.createChild("div", "port-forwarding-value").textContent = rule.address;
        return element;
    },

    /**
     * @override
     * @param {*} item
     * @param {number} index
     */
    removeItemRequested: function(item, index)
    {
        this._portForwardingConfig.splice(index, 1);
        this._list.removeItem(index);
        this._updateDiscoveryConfig();
    },

    /**
     * @override
     * @param {*} item
     * @param {!WebInspector.ListWidget.Editor} editor
     * @param {boolean} isNew
     */
    commitEdit: function(item, editor, isNew)
    {
        var rule = /** @type {!Adb.PortForwardingRule} */ (item);
        rule.port = editor.control("port").value.trim();
        rule.address = editor.control("address").value.trim();
        if (isNew)
            this._portForwardingConfig.push(rule);
        this._updateDiscoveryConfig();
    },

    /**
     * @override
     * @param {*} item
     * @return {!WebInspector.ListWidget.Editor}
     */
    beginEdit: function(item)
    {
        var rule = /** @type {!Adb.PortForwardingRule} */ (item);
        var editor = this._createEditor();
        editor.control("port").value = rule.port;
        editor.control("address").value = rule.address;
        return editor;
    },

    /**
     * @return {!WebInspector.ListWidget.Editor}
     */
    _createEditor: function()
    {
        if (this._editor)
            return this._editor;

        var editor = new WebInspector.ListWidget.Editor();
        this._editor = editor;
        var content = editor.contentElement();
        var fields = content.createChild("div", "port-forwarding-edit-row");
        fields.createChild("div", "port-forwarding-value port-forwarding-port").appendChild(editor.createInput("port", "text", "Device port (3333)", portValidator.bind(this)));
        fields.createChild("div", "port-forwarding-separator port-forwarding-separator-invisible");
        fields.createChild("div", "port-forwarding-value").appendChild(editor.createInput("address", "text", "Local address (dev.example.corp:3333)", addressValidator));
        return editor;

        /**
         * @param {*} item
         * @param {number} index
         * @param {!HTMLInputElement|!HTMLSelectElement} input
         * @this {WebInspector.DevicesView.DiscoveryView}
         * @return {boolean}
         */
        function portValidator(item, index, input)
        {
            var value = input.value.trim();
            var match = value.match(/^(\d+)$/);
            if (!match)
                return false;
            var port = parseInt(match[1], 10);
            if (port < 1024 || port > 65535)
                return false;
            for (var i = 0; i < this._portForwardingConfig.length; ++i) {
                if (i !== index && this._portForwardingConfig[i].port === value)
                    return false;
            }
            return true;
        }

        /**
         * @param {*} item
         * @param {number} index
         * @param {!HTMLInputElement|!HTMLSelectElement} input
         * @return {boolean}
         */
        function addressValidator(item, index, input)
        {
            var match = input.value.trim().match(/^([a-zA-Z0-9\.\-_]+):(\d+)$/);
            if (!match)
                return false;
            var port = parseInt(match[2], 10);
            return port <= 65535;
        }
    },

    _updateDiscoveryConfig: function()
    {
        var configMap = /** @type {!Adb.PortForwardingConfig} */ ({});
        for (var rule of this._portForwardingConfig)
            configMap[rule.port] = rule.address;
        InspectorFrontendHost.setDevicesDiscoveryConfig(this._discoverUsbDevicesCheckbox.checked, this._portForwardingEnabledCheckbox.checked, configMap);
    },

    __proto__: WebInspector.VBox.prototype
}

/**
 * @constructor
 * @extends {WebInspector.VBox}
 */
WebInspector.DevicesView.DeviceView = function()
{
    WebInspector.VBox.call(this);
    this.setMinimumSize(100, 100);
    this.contentElement.classList.add("device-view");

    var topRow = this.contentElement.createChild("div", "hbox device-text-row");
    this._deviceTitle = topRow.createChild("div", "view-title");
    this._deviceSerial = topRow.createChild("div", "device-serial");
    this._portStatus = this.contentElement.createChild("div", "device-port-status hidden");

    this._deviceOffline = this.contentElement.createChild("div");
    this._deviceOffline.textContent = WebInspector.UIString("Pending authentication: please accept debugging session on the device.");

    this._noBrowsers = this.contentElement.createChild("div");
    this._noBrowsers.textContent = WebInspector.UIString("No browsers detected.");

    this._browsers = this.contentElement.createChild("div", "device-browser-list vbox");

    /** @type {!Map<string, !WebInspector.DevicesView.BrowserSection>} */
    this._browserById = new Map();

    this._device = null;
}

/** @typedef {!{browser: ?Adb.Browser, element: !Element, title: !Element, pages: !Element, viewMore: !Element, newTab: !Element, pageSections: !Map<string, !WebInspector.DevicesView.PageSection>}} */
WebInspector.DevicesView.BrowserSection;

/** @typedef {!{page: ?Adb.Page, element: !Element, title: !Element, url: !Element, inspect: !Element}} */
WebInspector.DevicesView.PageSection;

WebInspector.DevicesView.DeviceView.prototype = {
    /**
     * @param {!Adb.Device} device
     */
    update: function(device)
    {
        if (!this._device || this._device.adbModel !== device.adbModel)
            this._deviceTitle.textContent = device.adbModel;

        if (!this._device || this._device.adbSerial !== device.adbSerial)
            this._deviceSerial.textContent = "#" + device.adbSerial;

        this._deviceOffline.classList.toggle("hidden", device.adbConnected);
        this._noBrowsers.classList.toggle("hidden", !device.adbConnected || !!device.browsers.length);
        this._browsers.classList.toggle("hidden", !device.adbConnected || !device.browsers.length);

        var browserIds = new Set();
        for (var browser of device.browsers)
            browserIds.add(browser.id);

        for (var browserId of this._browserById.keys()) {
            if (!browserIds.has(browserId)) {
                this._browserById.get(browserId).element.remove();
                this._browserById.remove(browserId);
            }
        }

        for (var browser of device.browsers) {
            var section = this._browserById.get(browser.id);
            if (!section) {
                section = this._createBrowserSection();
                this._browserById.set(browser.id, section);
                this._browsers.appendChild(section.element);
            }
            this._updateBrowserSection(section, browser);
        }

        this._device = device;
    },

    /**
     * @return {!WebInspector.DevicesView.BrowserSection}
     */
    _createBrowserSection: function()
    {
        var element = createElementWithClass("div", "vbox flex-none");
        var topRow = element.createChild("div", "");
        var title = topRow.createChild("div", "device-browser-title");

        var newTabRow = element.createChild("div", "device-browser-new-tab");
        newTabRow.createChild("div", "").textContent = WebInspector.UIString("New tab:");
        var newTabInput = newTabRow.createChild("input", "");
        newTabInput.type = "text";
        newTabInput.placeholder = WebInspector.UIString("Enter URL");
        newTabInput.addEventListener("keydown", newTabKeyDown, false);
        var newTabButton = createTextButton(WebInspector.UIString("Open"), openNewTab);
        newTabRow.appendChild(newTabButton);

        var pages = element.createChild("div", "device-page-list vbox");

        var viewMore = element.createChild("div", "device-view-more");
        viewMore.addEventListener("click", viewMoreClick, false);
        updateViewMoreTitle();

        var section = {browser: null, element: element, title: title, pages: pages, viewMore: viewMore, newTab: newTabRow, pageSections: new Map()};
        return section;

        function viewMoreClick()
        {
            pages.classList.toggle("device-view-more-toggled");
            updateViewMoreTitle();
        }

        function updateViewMoreTitle()
        {
            viewMore.textContent = pages.classList.contains("device-view-more-toggled") ? WebInspector.UIString("View less tabs\u2026") : WebInspector.UIString("View more tabs\u2026");
        }

        /**
         * @param {!Event} event
         */
        function newTabKeyDown(event)
        {
            if (event.key === "Enter") {
                event.consume(true);
                openNewTab();
            }
        }

        function openNewTab()
        {
            if (section.browser) {
                InspectorFrontendHost.openRemotePage(section.browser.id, newTabInput.value.trim() || "about:blank");
                newTabInput.value = "";
            }
        }
    },

    /**
     * @param {!WebInspector.DevicesView.BrowserSection} section
     * @param {!Adb.Browser} browser
     */
    _updateBrowserSection: function(section, browser)
    {
        if (!section.browser || section.browser.adbBrowserName !== browser.adbBrowserName || section.browser.adbBrowserVersion !== browser.adbBrowserVersion) {
            if (browser.adbBrowserVersion)
                section.title.textContent = String.sprintf("%s (%s)", browser.adbBrowserName, browser.adbBrowserVersion);
            else
                section.title.textContent = browser.adbBrowserName;
        }

        var pageIds = new Set();
        for (var page of browser.pages)
            pageIds.add(page.id);

        for (var pageId of section.pageSections.keys()) {
            if (!pageIds.has(pageId)) {
                section.pageSections.get(pageId).element.remove();
                section.pageSections.remove(pageId);
            }
        }

        for (var index = 0; index < browser.pages.length; ++index) {
            var page = browser.pages[index];
            var pageSection = section.pageSections.get(page.id);
            if (!pageSection) {
                pageSection = this._createPageSection();
                section.pageSections.set(page.id, pageSection);
                section.pages.appendChild(pageSection.element);
            }
            this._updatePageSection(pageSection, page);
            if (!index && section.pages.firstChild !== pageSection.element)
                section.pages.insertBefore(pageSection.element, section.pages.firstChild);
        }

        var kViewMoreCount = 3;
        for (var index = 0, element = section.pages.firstChild; element; element = element.nextSibling, ++index)
            element.classList.toggle("device-view-more-page", index >= kViewMoreCount);
        section.viewMore.classList.toggle("device-needs-view-more", browser.pages.length > kViewMoreCount);
        section.newTab.classList.toggle("hidden", !browser.adbBrowserChromeVersion);
        section.browser = browser;
    },

    /**
     * @return {!WebInspector.DevicesView.PageSection}
     */
    _createPageSection: function()
    {
        var element = createElementWithClass("div", "vbox");

        var titleRow = element.createChild("div", "device-page-title-row");
        var title = titleRow.createChild("div", "device-page-title");
        var inspect = createTextButton(WebInspector.UIString("Inspect"), doAction.bind(null, "inspect"), "device-inspect-button");
        titleRow.appendChild(inspect);

        var toolbar = new WebInspector.Toolbar("");
        toolbar.appendToolbarItem(new WebInspector.ToolbarMenuButton(appendActions));
        titleRow.appendChild(toolbar.element);

        var url = element.createChild("div", "device-page-url");
        var section = {page: null, element: element, title: title, url: url, inspect: inspect};
        return section;

        /**
         * @param {!WebInspector.ContextMenu} contextMenu
         */
        function appendActions(contextMenu)
        {
            contextMenu.appendItem(WebInspector.UIString("Reload"), doAction.bind(null, "reload"));
            contextMenu.appendItem(WebInspector.UIString("Focus"), doAction.bind(null, "activate"));
            contextMenu.appendItem(WebInspector.UIString("Close"), doAction.bind(null, "close"));
        }

        /**
         * @param {string} action
         */
        function doAction(action)
        {
            if (section.page)
                InspectorFrontendHost.performActionOnRemotePage(section.page.id, action);
        }
    },

    /**
     * @param {!WebInspector.DevicesView.PageSection} section
     * @param {!Adb.Page} page
     */
    _updatePageSection: function(section, page)
    {
        if (!section.page || section.page.name !== page.name) {
            section.title.textContent = page.name;
            section.title.title = page.name;
        }
        if (!section.page || section.page.url !== page.url) {
            section.url.textContent = "";
            section.url.appendChild(WebInspector.linkifyURLAsNode(page.url, undefined, undefined, true));
        }
        section.inspect.disabled = page.adbAttachedForeign;

        section.page = page;
    },

    /**
     * @param {!Adb.DevicePortForwardingStatus} status
     */
    portForwardingStatusChanged: function(status)
    {
        var json = JSON.stringify(status);
        if (json === this._cachedPortStatus)
            return;
        this._cachedPortStatus = json;

        this._portStatus.removeChildren();
        this._portStatus.createChild("div", "device-port-status-text").textContent = WebInspector.UIString("Port Forwarding:");
        var connected = [];
        var transient = [];
        var error = [];
        var empty = true;
        for (var port in status.ports) {
            if (!status.ports.hasOwnProperty(port))
                continue;

            empty = false;
            var portStatus = status.ports[port];
            var portNumber = createElementWithClass("div", "device-view-port-number monospace");
            portNumber.textContent = ":" + port;
            if (portStatus >= 0)
                this._portStatus.appendChild(portNumber);
            else
                this._portStatus.insertBefore(portNumber, this._portStatus.firstChild);

            var portIcon = createElementWithClass("div", "device-view-port-icon");
            if (portStatus >= 0) {
                connected.push(port);
            } else if (portStatus === -1 || portStatus === -2) {
                portIcon.classList.add("device-view-port-icon-transient");
                transient.push(port);
            } else if (portStatus < 0) {
                portIcon.classList.add("device-view-port-icon-error");
                error.push(port);
            }
            this._portStatus.insertBefore(portIcon, portNumber);
        }

        var title = [];
        if (connected.length)
            title.push(WebInspector.UIString("Connected: %s", connected.join(", ")));
        if (transient.length)
            title.push(WebInspector.UIString("Transient: %s", transient.join(", ")));
        if (error.length)
            title.push(WebInspector.UIString("Error: %s", error.join(", ")));
        this._portStatus.title = title.join("; ");
        this._portStatus.classList.toggle("hidden", empty);
    },

    __proto__: WebInspector.VBox.prototype
}


text:
<?php
declare(strict_types=1);

namespace MeetupOrganizing\Entity;

final class User
{
    private int $userId;

    private string $name;

    private string $emailAddress;

    private function __construct()
    {
    }

    public static function fromDatabaseRecord(array $record): User
    {
        $user = new self();

        $user->userId = (int)$record['userId'];
        $user->name = $record['name'];
        $user->emailAddress = $record['emailAddress'];

        return $user;
    }

    public function userId(): UserId
    {
        return UserId::fromInt($this->userId);
    }

    public function name(): string
    {
        return $this->name;
    }

    public function emailAddress(): string
    {
        return $this->emailAddress;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Kbrw\RiakBundle\Service\WebserviceClient\Riak;

use Guzzle\Http\Exception\CurlException;
use Kbrw\RiakBundle\Exception\RiakUnavailableException;
use Kbrw\RiakBundle\Service\WebserviceClient\BaseServiceClient;

class RiakBucketServiceClient extends BaseServiceClient
{
    /**
     * @param  \Kbrw\RiakBundle\Model\Cluster\Cluster $cluster
     * @param  \Kbrw\RiakBundle\Model\Bucket\Bucket   $bucket
     * @return array<string>
     */
    public function keys($cluster, $bucket)
    {
        $keys = array();
        $request = $this->getClient($cluster->getGuzzleClientProviderService(), $this->getConfig($cluster, $bucket->getName(), "stream"))->get();
        $request->getCurlOptions()->set(CURLOPT_WRITEFUNCTION, function($ch, $data) use (&$keys) {
            $content = json_decode($data, true);
            if (is_array($content) && array_key_exists("keys", $content)) {
                foreach ($content["keys"] as $key) {
                    $keys[] = $key;
                }
            }

            return strlen($data);
        });
        try {
            $response = $request->send();
            $this->logResponse($response, array("method" => "GET"));
        } catch (CurlException $e) {
            $this->logger->err("Riak is unavailable" . $e->getMessage());
            throw new RiakUnavailableException();
        } catch (\Exception $e) {
            $this->logger->err("Error while getting keys" . $e->getMessage());
        }

        return $keys;
    }

    /**
     * @param  \Kbrw\RiakBundle\Model\Cluster\Cluster $cluster
     * @param  \Kbrw\RiakBundle\Model\Bucket\Bucket   $bucket
     * @return integer
     */
    public function count($cluster, $bucket)
    {
        $keys = 0;
        $request = $this->getClient($cluster->getGuzzleClientProviderService(), $this->getConfig($cluster, $bucket->getName(), "stream"))->get();
        $request->getCurlOptions()->set(CURLOPT_WRITEFUNCTION, function($ch, $data) use (&$keys) {
            $content = json_decode($data, true);
            if (is_array($content) && array_key_exists("keys", $content)) {
                $keys += count($content["keys"]);
            }

            return strlen($data);
        });
        try {
            $response = $request->send();
            $this->logResponse($response, array("method" => "GET"));
        } catch (CurlException $e) {
            $this->logger->err("Riak is unavailable" . $e->getMessage());
            throw new RiakUnavailableException();
        } catch (\Exception $e) {
            $this->logger->err("Error while getting keys" . $e->getMessage());
        }

        return $keys;
    }

    /**
     * @param  \Kbrw\RiakBundle\Model\Cluster\Cluster $cluster
     * @param  string                                 $bucketName
     * @return \Kbrw\RiakBundle\Model\Bucket\Bucket
     */
    public function properties($cluster, $bucketName)
    {
        $bucket = null;
        $request = $this->getClient($cluster->getGuzzleClientProviderService(), $this->getConfig($cluster, $bucketName, null, true))->get();
        try {
            $response = $request->send();
            $extra = array("method" => "GET");
            if ($response->getStatusCode() == "200") {
                $ts = microtime(true);
                $bucket = $this->serializer->deserialize($response->getBody(true), "Kbrw\RiakBundle\Model\Bucket\Bucket", "json");
                $extra["deserialization_time"] = microtime(true) - $ts;
            }
            $this->logResponse($response, $extra);
        } catch (CurlException $e) {
            $this->logger->err("Riak is unavailable" . $e->getMessage());
            throw new RiakUnavailableException();
        } catch (\Exception $e) {
            $this->logger->err("Error while getting properties on bucket '" . $bucketName . "'. Full message is : " . $e->getMessage());
        }

        return $bucket;
    }

    /**
     * @param  \Kbrw\RiakBundle\Model\Cluster\Cluster $cluster
     * @param  \Kbrw\RiakBundle\Model\Bucket\Bucket   $bucket
     * @return boolean
     */
    public function save($cluster, $bucket)
    {
        $request = $this->getClient($cluster->getGuzzleClientProviderService(), $this->getConfig($cluster, $bucket->getName(), null))->put();
        try {
            $extra = array("method"=> "PUT");
            $ts = microtime(true);
            $request->setBody($this->serializer->serialize($bucket, "json"));
            $extra["serialization_time"] = microtime(true); - $ts;
            $request->setHeader("Content-Type", "application/json");
            $response = $request->send();
            $this->logResponse($response, $extra);
            return ($response->getStatusCode() == "204");
        } catch (CurlException $e) {
            $this->logger->err("Riak is unavailable" . $e->getMessage());
            throw new RiakUnavailableException();
        } catch (\Exception $e) {
            $this->logger->err("Error while setting properties on bucket '" . $bucket->getName() . "'. Full message is : " . $e->getMessage());
        }

        return false;
    }

    /**
     * @param  \Kbrw\RiakBundle\Model\Cluster\Cluster $cluster
     * @param  \Kbrw\RiakBundle\Model\Bucket\Bucket   $bucket
     * @return array<string,string>
     */
    public function getConfig($cluster, $bucketName, $keys = "stream", $props = false)
    {
        $config = array();
        $config["protocol"] = $cluster->getProtocol();
        $config["domain"]   = $cluster->getDomain();
        $config["port"]     = $cluster->getPort();
        $config["bucket"]   = $bucketName;
        $config["keys"]     = $keys;
        $config["props"]    = $props ? "true" : null;

        return $config;
    }

    public function getSerializer()
    {
        return $this->serializer;
    }

    public function setSerializer($serializer)
    {
        $this->serializer = $serializer;
    }

    /**
     * @var \JMS\Serializer\Serializer
     */
    public $serializer;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>ItsAboutTime</groupId>
    <artifactId>ItsAboutTime</artifactId>
    <version>1.0-SNAPSHOT</version>

    <name>com.kaltiz.ItsAboutTime.ItsAboutTime</name>
    <url>https://github.com/Kaltiz/ItsAboutTime</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <repositories>
        <repository>
            <id>sk89q-repo</id>
            <url>http://maven.sk89q.com/repo/</url>
        </repository>

        <repository>
            <id>vault-repo</id>
            <url>http://nexus.theyeticave.net/content/repositories/pub_releases</url>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>org.bukkit</groupId>
            <artifactId>bukkit</artifactId>
            <version>1.7.10-R0.1-SNAPSHOT</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <finalName>${project.artifactId}-${project.version}</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.4</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
const Value SplashTime = Value(1.5);//In seconds

Scene* Splash::createScene()
{
    auto *scene = Scene::create();

    auto *layer = Splash::create();
    layer->setTag(2334);

    scene->addChild(layer);

    return scene;
}

bool Splash::init()
{
    if ( !CCLayer::init() )
    {
        return false;
    }

    Rect visibleRect = ScreenSizeManager::getVisibleRect();

    auto background = Sprite::create(ImageManager::getImage("splash"), visibleRect);
    background->setPosition(ScreenSizeManager::getScreenPositionFromPercentage(50, 50));
    background->setAnchorPoint(Point::ANCHOR_MIDDLE);
    this->addChild(background);

    DelayTime *delayAction = DelayTime::create(SplashTime.asFloat());
    CallFunc *mySelector = CallFunc::create(CC_CALLBACK_0(Splash::launchMainScene, this));
    this->runAction(Sequence::create(delayAction, mySelector, nullptr));

    return true;
}

void Splash::launchMainScene()
{
    SceneManager::getInstance()->runSceneWithType(SceneType::MAIN);
}


text:
package net

import (
	"io"
	"os"
	"syscall"
	"time"
)

// TCPConn is an implementation of the Conn interface for TCP network
// connections.
type TCPConn struct {
	conn
}

func newTCPConn(fd *netFD) *TCPConn {
	return &TCPConn{conn{fd}}
}

// ReadFrom implements the io.ReaderFrom ReadFrom method.
func (c *TCPConn) ReadFrom(r io.Reader) (int64, error) {
	return genericReadFrom(c, r)
}

// CloseRead shuts down the reading side of the TCP connection.
// Most callers should just use Close.
func (c *TCPConn) CloseRead() error {
	if !c.ok() {
		return syscall.EINVAL
	}
	return c.fd.CloseRead()
}

// CloseWrite shuts down the writing side of the TCP connection.
// Most callers should just use Close.
func (c *TCPConn) CloseWrite() error {
	if !c.ok() {
		return syscall.EINVAL
	}
	return c.fd.CloseWrite()
}

// SetLinger sets the behavior of Close() on a connection which still
// has data waiting to be sent or to be acknowledged.
//
// If sec < 0 (the default), Close returns immediately and the
// operating system finishes sending the data in the background.
//
// If sec == 0, Close returns immediately and the operating system
// discards any unsent or unacknowledged data.
//
// If sec > 0, Close blocks for at most sec seconds waiting for data
// to be sent and acknowledged.
func (c *TCPConn) SetLinger(sec int) error {
	return syscall.EPLAN9
}

// SetKeepAlive sets whether the operating system should send
// keepalive messages on the connection.
func (c *TCPConn) SetKeepAlive(keepalive bool) error {
	if !c.ok() {
		return syscall.EPLAN9
	}
	return setKeepAlive(c.fd, keepalive)
}

// SetKeepAlivePeriod sets period between keep alives.
func (c *TCPConn) SetKeepAlivePeriod(d time.Duration) error {
	if !c.ok() {
		return syscall.EPLAN9
	}
	return setKeepAlivePeriod(c.fd, d)
}

// SetNoDelay controls whether the operating system should delay
// packet transmission in hopes of sending fewer packets (Nagle's
// algorithm).  The default is true (no delay), meaning that data is
// sent as soon as possible after a Write.
func (c *TCPConn) SetNoDelay(noDelay bool) error {
	return syscall.EPLAN9
}

// DialTCP connects to the remote address raddr on the network net,
// which must be "tcp", "tcp4", or "tcp6".  If laddr is not nil, it is
// used as the local address for the connection.
func DialTCP(net string, laddr, raddr *TCPAddr) (*TCPConn, error) {
	return dialTCP(net, laddr, raddr, noDeadline)
}

func dialTCP(net string, laddr, raddr *TCPAddr, deadline time.Time) (*TCPConn, error) {
	if !deadline.IsZero() {
		panic("net.dialTCP: deadline not implemented on Plan 9")
	}
	switch net {
	case "tcp", "tcp4", "tcp6":
	default:
		return nil, &OpError{"dial", net, raddr, UnknownNetworkError(net)}
	}
	if raddr == nil {
		return nil, &OpError{"dial", net, nil, errMissingAddress}
	}
	fd, err := dialPlan9(net, laddr, raddr)
	if err != nil {
		return nil, err
	}
	return newTCPConn(fd), nil
}

// TCPListener is a TCP network listener.  Clients should typically
// use variables of type Listener instead of assuming TCP.
type TCPListener struct {
	fd *netFD
}

// AcceptTCP accepts the next incoming call and returns the new
// connection.
func (l *TCPListener) AcceptTCP() (*TCPConn, error) {
	if l == nil || l.fd == nil || l.fd.ctl == nil {
		return nil, syscall.EINVAL
	}
	fd, err := l.fd.acceptPlan9()
	if err != nil {
		return nil, err
	}
	return newTCPConn(fd), nil
}

// Accept implements the Accept method in the Listener interface; it
// waits for the next call and returns a generic Conn.
func (l *TCPListener) Accept() (Conn, error) {
	if l == nil || l.fd == nil || l.fd.ctl == nil {
		return nil, syscall.EINVAL
	}
	c, err := l.AcceptTCP()
	if err != nil {
		return nil, err
	}
	return c, nil
}

// Close stops listening on the TCP address.
// Already Accepted connections are not closed.
func (l *TCPListener) Close() error {
	if l == nil || l.fd == nil || l.fd.ctl == nil {
		return syscall.EINVAL
	}
	if _, err := l.fd.ctl.WriteString("hangup"); err != nil {
		l.fd.ctl.Close()
		return &OpError{"close", l.fd.ctl.Name(), l.fd.laddr, err}
	}
	return l.fd.ctl.Close()
}

// Addr returns the listener's network address, a *TCPAddr.
func (l *TCPListener) Addr() Addr { return l.fd.laddr }

// SetDeadline sets the deadline associated with the listener.
// A zero time value disables the deadline.
func (l *TCPListener) SetDeadline(t time.Time) error {
	if l == nil || l.fd == nil || l.fd.ctl == nil {
		return syscall.EINVAL
	}
	return l.fd.setDeadline(t)
}

// File returns a copy of the underlying os.File, set to blocking
// mode.  It is the caller's responsibility to close f when finished.
// Closing l does not affect f, and closing f does not affect l.
//
// The returned os.File's file descriptor is different from the
// connection's.  Attempting to change properties of the original
// using this duplicate may or may not have the desired effect.
func (l *TCPListener) File() (f *os.File, err error) { return l.dup() }

// ListenTCP announces on the TCP address laddr and returns a TCP
// listener.  Net must be "tcp", "tcp4", or "tcp6".  If laddr has a
// port of 0, ListenTCP will choose an available port.  The caller can
// use the Addr method of TCPListener to retrieve the chosen address.
func ListenTCP(net string, laddr *TCPAddr) (*TCPListener, error) {
	switch net {
	case "tcp", "tcp4", "tcp6":
	default:
		return nil, &OpError{"listen", net, laddr, UnknownNetworkError(net)}
	}
	if laddr == nil {
		laddr = &TCPAddr{}
	}
	fd, err := listenPlan9(net, laddr)
	if err != nil {
		return nil, err
	}
	return &TCPListener{fd}, nil
}


text:
<!-- Copyright (C) 2012-2014 the original author or authors. Licensed under
	the Apache License, Version 2.0 (the "License"); you may not use this file
	except in compliance with the License. You may obtain a copy of the License
	at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable
	law or agreed to in writing, software distributed under the License is distributed
	on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
	express or implied. See the License for the specific language governing permissions
	and limitations under the License. -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.gitblit.fathom</groupId>
    <artifactId>fathom-parent</artifactId>
    <packaging>pom</packaging>
    <version>1.2.0-SNAPSHOT</version>
    <name>Fathom Parent</name>
    <description>Microservice Foundation</description>
    <url>http://fathom.gitblit.com</url>

    <scm>
        <url>https://github.com/gitblit/fathom</url>
        <connection>scm:git:https://github.com/gitblit/fathom.git</connection>
        <developerConnection>scm:git:git@github.com:gitblit/fathom.git</developerConnection>
        <tag>HEAD</tag>
    </scm>

    <issueManagement>
        <system>GitHub</system>
        <url>https://github.com/gitblit/fathom/issues/</url>
    </issueManagement>

    <licenses>
        <license>
            <name>The Apache Software License, Version 2.0</name>
            <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
            <distribution>repo</distribution>
        </license>
    </licenses>

    <developers>
        <developer>
            <name>James Moger</name>
            <email>james.moger@gmail.com</email>
            <organization>gitblit.com</organization>
            <organizationUrl>https://github.com/gitblit</organizationUrl>
        </developer>
    </developers>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <pippo.version>1.2.0</pippo.version>
        <h2.version>1.4.186</h2.version>
        <mockito.version>1.9.5</mockito.version>
        <junit.version>4.13.1</junit.version>
        <slf4j.version>1.7.21</slf4j.version>
    </properties>

    <distributionManagement>
        <snapshotRepository>
            <id>ossrh</id>
            <url>https://oss.sonatype.org/content/repositories/snapshots</url>
        </snapshotRepository>
        <repository>
            <id>ossrh</id>
            <url>https://oss.sonatype.org/service/local/staging/deploy/maven2</url>
        </repository>
    </distributionManagement>

    <build>
        <plugins>
            <!-- Java Compiler plugin -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>

            <!-- Release plugin -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-release-plugin</artifactId>
                <version>2.5</version>
                <configuration>
                    <!-- install next final version in local repo, so that tests on archetypes work -->
                    <preparationGoals>clean install</preparationGoals>
                    <autoVersionSubmodules>true</autoVersionSubmodules>
                    <goals>deploy</goals>
                    <tagNameFormat>release-@{project.version}</tagNameFormat>
                    <useReleaseProfile>false</useReleaseProfile>
                    <releaseProfiles>release</releaseProfiles>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <profiles>
        <profile>
            <id>release</id>
            <build>
                <plugins>
                    <!-- Java Source plugin -->
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-source-plugin</artifactId>
                        <executions>
                            <execution>
                                <id>attach-sources</id>
                                <goals>
                                    <goal>jar</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>

                    <!-- JavaDoc plugin -->
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-javadoc-plugin</artifactId>
                        <executions>
                            <execution>
                                <id>attach-javadocs</id>
                                <goals>
                                    <goal>jar</goal>
                                </goals>
                                <configuration>
                                    <additionalparam>-Xdoclint:none</additionalparam>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>

                    <!-- GPG plugin to sign the artifacts -->
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-gpg-plugin</artifactId>
                        <version>1.5</version>
                        <executions>
                            <execution>
                                <id>sign-artifacts</id>
                                <phase>verify</phase>
                                <goals>
                                    <goal>sign</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.h2database</groupId>
                <artifactId>h2</artifactId>
                <version>${h2.version}</version>
            </dependency>

            <dependency>
                <groupId>org.mockito</groupId>
                <artifactId>mockito-core</artifactId>
                <version>${mockito.version}</version>
            </dependency>

            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>${junit.version}</version>
            </dependency>

            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
                <version>${slf4j.version}</version>
            </dependency>

            <dependency>
                <groupId>org.kohsuke.metainf-services</groupId>
                <artifactId>metainf-services</artifactId>
                <version>1.7</version>
            </dependency>

        </dependencies>
    </dependencyManagement>

    <modules>
        <module>fathom-core</module>
        <module>fathom-x509</module>
        <module>fathom-eventbus</module>
        <module>fathom-jcache</module>
        <module>fathom-jmx</module>
        <module>fathom-metrics</module>
        <module>fathom-metrics-librato</module>
        <module>fathom-metrics-influxdb</module>
        <module>fathom-metrics-graphite</module>
        <module>fathom-metrics-ganglia</module>
        <module>fathom-mailer</module>
        <module>fathom-quartz</module>
        <module>fathom-rest</module>
        <module>fathom-rest-security</module>
        <module>fathom-rest-swagger</module>
        <module>fathom-rest-test</module>
        <module>fathom-test-tools</module>
        <module>fathom-security</module>
        <module>fathom-security-htpasswd</module>
        <module>fathom-security-pam</module>
        <module>fathom-security-windows</module>
        <module>fathom-security-ldap</module>
        <module>fathom-security-jdbc</module>
        <module>fathom-security-redis</module>
        <module>fathom-security-keycloak</module>
        <module>fathom-rest-shiro</module>
        <module>fathom-xmlrpc</module>
        <module>fathom-xmlrpc-test</module>
        <module>fathom-integration-test</module>
        <module>fathom-archetype-standard</module>
    </modules>

</project>


text:
module Rails::Command::CredentialsCommand::Diffing # :nodoc:
  GITATTRIBUTES_ENTRY = <<~END
    config/credentials/*.yml.enc diff=rails_credentials
    config/credentials.yml.enc diff=rails_credentials
  END

  def enroll_project_in_credentials_diffing
    if enrolled_in_credentials_diffing?
      say "Project is already enrolled in credentials file diffing."
    else
      gitattributes.write(GITATTRIBUTES_ENTRY, mode: "a")

      say "Enrolled project in credentials file diffing!"
      say "Rails ensures the rails_credentials diff driver is set when running `credentials:edit`. See `credentials:help` for more."
    end
  end

  def disenroll_project_from_credentials_diffing
    if enrolled_in_credentials_diffing?
      gitattributes.write(gitattributes.read.gsub(GITATTRIBUTES_ENTRY, ""))
      gitattributes.delete if gitattributes.empty?

      say "Disenrolled project from credentials file diffing!"
    else
      say "Project is not enrolled in credentials file diffing."
    end
  end

  def ensure_diffing_driver_is_configured
    configure_diffing_driver if enrolled_in_credentials_diffing? && !diffing_driver_configured?
  end

  private
    def enrolled_in_credentials_diffing?
      gitattributes.file? && gitattributes.read.include?(GITATTRIBUTES_ENTRY)
    end

    def diffing_driver_configured?
      system "git config --get diff.rails_credentials.textconv", out: File::NULL
    end

    def configure_diffing_driver
      system "git config diff.rails_credentials.textconv 'bin/rails credentials:diff'"
    end

    def gitattributes
      Rails.root.join(".gitattributes")
    end
end


text:
namespace crypto {
namespace tink {
namespace internal {

crypto::tink::util::Status ValidateParams(
    const google::crypto::tink::HpkeParams& params);

crypto::tink::util::Status ValidateKeyAndVersion(
    const google::crypto::tink::HpkePublicKey& key, uint32_t max_key_version);

}  // namespace internal
}  // namespace tink
}  // namespace crypto

#endif  // TINK_HYBRID_INTERNAL_HPKE_KEY_MANAGER_UTIL_H_


text:
This is an example using the AWS SDK for Go to concatenate two objects together.
We use `UploadPartCopy` which uses an object for a part. Here in this example we have two parts, or in other words
two objects that we want to concatenate together.

# Usage

The example uses the bucket name provided, two keys for each object, and lastly the output key.

```sh
AWS_REGION=<region> go run -tags example concatenateObjects.go <bucket> <key for object 1> <key for object 2> <key for output>
```


text:
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator

    Friend NotInheritable Class MayHaveSideEffectsVisitor
        Inherits BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator

        Private _mayHaveSideEffects As Boolean

        Private Sub New()
        End Sub

        Friend Shared Function MayHaveSideEffects(node As BoundNode) As Boolean
            Dim visitor = New MayHaveSideEffectsVisitor()
            visitor.Visit(node)
            Return visitor._mayHaveSideEffects
        End Function

        Public Overrides Function Visit(node As BoundNode) As BoundNode
            If _mayHaveSideEffects Then
                Return Nothing
            End If

            Return MyBase.Visit(node)
        End Function

        Public Overrides Function VisitAssignmentOperator(node As BoundAssignmentOperator) As BoundNode
            Return SetMayHaveSideEffects()
        End Function

        ' Calls are treated as having side effects, but properties are
        ' not. (Since this visitor is run on the bound tree before
        ' lowering, properties are not represented as calls.)
        Public Overrides Function VisitCall(node As BoundCall) As BoundNode
            Return SetMayHaveSideEffects()
        End Function

        ' In Visual Basic, a parameterless method can be called without specifying an argument list,
        ' so we will treat every method group as a potential Call.  This is not strictly true (in the
        ' case where the parent is an AddressOf), but it doesn't seem worth any extra effort to handle
        ' that case differently (the consequence of saying that something may have side effects is
        ' simply that you may have to re-evaluate the expression manually).  The far more common case
        ' is encountered when getting the DataTip for a method invocation (the argument list is not
        ' included in the expression text).  We want to prevent automatic evaluation in that case.
        Public Overrides Function VisitMethodGroup(node As BoundMethodGroup) As BoundNode
            Return SetMayHaveSideEffects()
        End Function

        Public Overrides Function VisitObjectInitializerExpression(node As BoundObjectInitializerExpression) As BoundNode
            For Each initializer In node.Initializers
                ' Do not treat initializer assignment as a side effect since it is
                ' part of an object creation. In short, visit the RHS only.
                Dim expr = If(initializer.Kind = BoundKind.AssignmentOperator,
                    DirectCast(initializer, BoundAssignmentOperator).Right,
                    initializer)
                Visit(expr)
            Next
            Return Nothing
        End Function

        Private Function SetMayHaveSideEffects() As BoundNode
            _mayHaveSideEffects = True
            Return Nothing
        End Function

    End Class

End Namespace


text:
<?php require('../includes/header.inc.php'); ?>
<?php $this->renderBegin(); ?>

Hello World, Revisited

This example revisits our original Hello World example to show how you can easily
	change a postback-based form and interactions into AJAX-postback based ones.

Whereas before, we executed a Server on the button's click, we have now changed
	that to a Ajax.  Everything else remains the same.

The result is the exact same interaction, but now performed Asynchronously via Ajax.  Note
	that after clicking the button, the entire page doesn't "refresh" -- but the label's content
	changes as defined in the PHP method btnButton_Click.

<?php $this->lblMessage->render(); ?>

<?php $this->btnButton->render(); ?>

<?php $this->renderEnd(); ?>
<?php require('../includes/footer.inc.php'); ?>


text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

namespace core\plugininfo;

use moodle_url, core_plugin_manager;

defined('MOODLE_INTERNAL') || die();

/**
 * Class for question behaviours.
 */
class qbehaviour extends base {
    /**
     * Finds all enabled plugins, the result may include missing plugins.
     * @return array|null of enabled plugins $pluginname=>$pluginname, null means unknown
     */
    public static function get_enabled_plugins() {
        $plugins = core_plugin_manager::instance()->get_installed_plugins('qbehaviour');
        if (!$plugins) {
            return array();
        }
        if ($disabled = get_config('question', 'disabledbehaviours')) {
            $disabled = explode(',', $disabled);
        } else {
            $disabled = array();
        }

        $enabled = array();
        foreach ($plugins as $plugin => $version) {
            if (in_array($plugin, $disabled)) {
                continue;
            }
            $enabled[$plugin] = $plugin;
        }

        return $enabled;
    }

    public function is_uninstall_allowed() {
        global $DB;

        if ($this->name === 'missing') {
            // qbehaviour_missing is used by the system. It cannot be uninstalled.
            return false;
        }

        return !$DB->record_exists('question_attempts', array('behaviour' => $this->name));
    }

    /**
     * Pre-uninstall hook.
     *
     * This is intended for disabling of plugin, some DB table purging, etc.
     *
     * NOTE: to be called from uninstall_plugin() only.
     * @private
     */
    public function uninstall_cleanup() {
        if ($disabledbehaviours = get_config('question', 'disabledbehaviours')) {
            $disabledbehaviours = explode(',', $disabledbehaviours);
            $disabledbehaviours = array_unique($disabledbehaviours);
        } else {
            $disabledbehaviours = array();
        }
        if (($key = array_search($this->name, $disabledbehaviours)) !== false) {
            unset($disabledbehaviours[$key]);
            set_config('disabledbehaviours', implode(',', $disabledbehaviours), 'question');
        }

        if ($behaviourorder = get_config('question', 'behavioursortorder')) {
            $behaviourorder = explode(',', $behaviourorder);
            $behaviourorder = array_unique($behaviourorder);
        } else {
            $behaviourorder = array();
        }
        if (($key = array_search($this->name, $behaviourorder)) !== false) {
            unset($behaviourorder[$key]);
            set_config('behavioursortorder', implode(',', $behaviourorder), 'question');
        }

        parent::uninstall_cleanup();
    }

    /**
     * Return URL used for management of plugins of this type.
     * @return moodle_url
     */
    public static function get_manage_url() {
        return new moodle_url('/admin/qbehaviours.php');
    }
}


text:
package com.example.mprice.mpcolumn.models;

/**
 * Created by mprice on 2/7/16.
 */
public class ArticleHeadline {
    public String main;
}


text:
var express       = require('express');
var falcorExpress = require('falcor-express');
var Router        = require('falcor-router');
var jwt           = require('express-jwt');
var dotenv        = require('dotenv');
var bodyParser    = require('body-parser');

var app = express();

dotenv.load();

app.use(express.static('.'));

var authenticate = jwt({
  secret: new Buffer(process.env.AUTH0_CLIENT_SECRET, 'base64'),
  audience: process.env.AUTH0_CLIENT_ID
});

var data = [
  {
    "name": "AngularJS",
    "language": "JavaScript"
  },
  {
    "name": "NodeJS",
    "language": "JavaScript"
  },
  {
    "name": "Laravel",
    "language": "PHP"
  }
];

app.use('/api/model.json', authenticate, falcorExpress.dataSourceRoute(function(req, res) {
  return new Router([
    {
      route: "frameworks[{integers:frameworkIds}]['name', 'language']",
      get: function(pathSet) {
        var results = [];

        pathSet.frameworkIds.forEach(function(frameworkId) {

          // An array of key names that map is held at pathSet[2]
          pathSet[2].map(function(key) {

            // Find the framework that corresponds to the current frameworkId
            var frameworkRecord = data[frameworkId];

            // Finally we push a path/value object onto
            // the results array
            results.push({
              path: ['frameworks', frameworkId, key],
              value: frameworkRecord[key]
            });
          });
        });

        return results;
      }
    }
  ]);
}));

app.listen(3000);
console.log("Listening on http://localhost:3000");


text:
<!--
 Licensed to the Apache Software Foundation (ASF) under one or more
 contributor license agreements.  See the NOTICE file distributed with
 this work for additional information regarding copyright ownership.
 The ASF licenses this file to You under the Apache License, Version 2.0
 (the "License"); you may not use this file except in compliance with
 the License.  You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->

<project name="dropbox" default="all">

    <import file="../connector-build.xml"/>

    <path id="connector-classpath">
        <path refid="mcf-connector-build.connector-classpath"/>
        <fileset dir="../../lib">
            <include name="dropbox-client*.jar"/>
            <include name="json-simple*.jar"/>
        </fileset>
    </path>

    <target name="lib" depends="mcf-connector-build.lib,precompile-check" if="canBuild">
        <mkdir dir="dist/lib"/>
        <copy todir="dist/lib">
            <fileset dir="../../lib">
                <include name="dropbox*.jar"/>
                <include name="json-simple*.jar"/>
            </fileset>
        </copy>
    </target>

</project>


text:
classdef WordStatsCounter < handle
    %WORDSTATSCOUNTER Summary of this class goes here
    %   Detailed explanation goes here

    properties
        dictionary % the dictionary to use for testing
        xlWriter;
        articleWords = 0; % total words seen so far for the article
        articleCounts; % array of counts of matching words, for each entry in the dictionary, for the article
        allWords = 0; % total words seen so far for all articles
        allCounts; % counts (as articleCounts) but for all articles
    end

    methods
        function obj = WordStatsCounter(dictionary, xlWriter)
            % WordStatsCounter constructor for class
            obj.dictionary = dictionary;
            obj.xlWriter = xlWriter;
            obj.articleCounts = zeros(1, length(obj.dictionary));
            obj.allCounts = zeros(1, length(obj.dictionary));
        end

        function addWords(obj, words)
            % addWords add the words supplied to the counter
            %    words is a cell array of words to be added

            %obj - the current object
            %words - words to be added
            %word - current word
            %i - loop counter
            %j - loop counter

            obj.articleWords = obj.articleWords + length(words);
            obj.allWords = obj.allWords  + length(words);

            % iterate over all words added
            for i = 1:length(words)
                word = words{i};
                % iterate over the dictionary entries
                for j = 1:length(obj.dictionary);

                    %if the word matches the dictionary entry add one to
                    %the counter for this entry
                    if(obj.dictionary(j).matches(word))
                        obj.articleCounts(j) =  obj.articleCounts(j) + 1;
                        obj.allCounts(j) =  obj.allCounts(j) + 1;
                    end
                end
            end
        end

        function writeArticleResultsToExcel(obj, filename, sheet, row, column)
            % writeResultsToExcel writes the current stored counts to Excel
            %    writes to the row, starting from the specified column
            %    first column is the total number of words
            %    subsequent columns are the number of words for each
            %    dictionary entry, in order.

            %obj - the current object
            %filename - path to file
            %sheet - sheet in Excel
            %row - index for row in Excel
            %column - index for column in Excel
            %range - range in excel to write to

            % write the total words added
            range = xlRange(column,row,column,row);
            obj.xlWriter.xlswrite(filename, obj.articleWords, sheet, range);

            % write the count of matched words for each dictionary entry.
            range = xlRange(column+1,row,column+length(obj.articleCounts),row);
            obj.xlWriter.xlswrite(filename, obj.articleCounts, sheet, range);
        end

        function writeSummaryResultsToExcel(obj, filename, sheet, row, column)
            % writeResultsToExcel writes the current stored counts to Excel
            %    writes to the row, starting from the specified column
            %    first column is the total number of words
            %    subsequent columns are the number of words for each
            %    dictionary entry, in order.

            %range - range in excel to write to

            % write the total words added
            range = xlRange(column,row,column,row);
            obj.xlWriter.xlswrite(filename, obj.allWords, sheet, range);

            % write the count of matched words for each dictionary entry.
            range = xlRange(column+1,row,column+length(obj.allCounts),row);
            obj.xlWriter.xlswrite(filename, obj.allCounts, sheet, range);
        end

        function nextArticle(obj)
            % reset resets the counter to the initial (0) state
            obj.articleWords = 0;
            obj.articleCounts = zeros(1, length(obj.dictionary));
        end
    end

end


text:
// Wee (weepower.com)
// Licensed under Apache 2 (http://www.apache.org/licenses/LICENSE-2.0)
// DO NOT MODIFY

/* global __dirname, global, module, project, require */

(function() {
	'use strict';

	module.exports = function(grunt) {
		global.rootPath = __dirname;
		global.configPath = './' + (grunt.option('config') || 'project.json');

		global.project = grunt.file.readJSON(global.configPath);

		var assetPath = (project.paths.root !== '') ?
				project.paths.root + '/' + project.paths.assets :
				project.assets,
			buildPath = assetPath + '/wee/build/';

		require('./' + buildPath + 'config.js')(grunt);
		grunt.loadTasks(buildPath + 'tasks');
	};
})();


text:
using System;
using cAlgo.API;
using cAlgo.API.Indicators;

namespace cAlgo.Indicators
{
    [Indicator(IsOverlay = true, AccessRights = AccessRights.None)]
    public class IchimokuCloud : Indicator
    {
        [Parameter(DefaultValue = 9)]
        public int periodFast { get; set; }

        [Parameter(DefaultValue = 26)]
        public int periodMedium { get; set; }

        [Parameter(DefaultValue = 52)]
        public int periodSlow { get; set; }

        [Parameter(DefaultValue = 26)]
        public int DisplacementCloud { get; set; }

        [Output("SenkouSpanB", Color = Colors.Red, LineStyle = LineStyle.Lines)]
        public IndicatorDataSeries SenkouSpanB { get; set; }
        [Output("SenkouSpanA", Color = Colors.Green, LineStyle = LineStyle.Lines)]
        public IndicatorDataSeries SenkouSpanA { get; set; }

        double maxfast, minfast, maxmedium, minmedium, maxslow, minslow;

        public IndicatorDataSeries TenkanSen;
        public IndicatorDataSeries KijunSen;
        protected override void Initialize()
        {
            TenkanSen = CreateDataSeries();
            KijunSen = CreateDataSeries();
        }

        public override void Calculate(int index)
        {
            if ((index < periodFast) || (index < periodSlow))
            {
                return;
            }

            maxfast = MarketSeries.High[index];
            minfast = MarketSeries.Low[index];
            maxmedium = MarketSeries.High[index];
            minmedium = MarketSeries.Low[index];
            maxslow = MarketSeries.High[index];
            minslow = MarketSeries.Low[index];

            for (int i = 0; i < periodFast; i++)
            {
                if (maxfast < MarketSeries.High[index - i])
                {
                    maxfast = MarketSeries.High[index - i];
                }
                if (minfast > MarketSeries.Low[index - i])
                {
                    minfast = MarketSeries.Low[index - i];
                }
            }
            for (int i = 0; i < periodMedium; i++)
            {
                if (maxmedium < MarketSeries.High[index - i])
                {
                    maxmedium = MarketSeries.High[index - i];
                }
                if (minmedium > MarketSeries.Low[index - i])
                {
                    minmedium = MarketSeries.Low[index - i];
                }
            }
            for (int i = 0; i < periodSlow; i++)
            {
                if (maxslow < MarketSeries.High[index - i])
                {
                    maxslow = MarketSeries.High[index - i];
                }
                if (minslow > MarketSeries.Low[index - i])
                {
                    minslow = MarketSeries.Low[index - i];
                }
            }
            TenkanSen[index] = (maxfast + minfast) / 2;
            KijunSen[index] = (maxmedium + minmedium) / 2;

            SenkouSpanA[index + DisplacementCloud] = (TenkanSen[index] + KijunSen[index]) / 2;
            SenkouSpanB[index + DisplacementCloud] = (maxslow + minslow) / 2;
        }
    }
}


text:
from .cat import cat

def test_cat(fs):
    filename = 'foo.txt'
    contents = 'insert a story here'
    fs.create_file(filename, contents=contents)

    result = cat(filename)
    assert result[0] == 'success'
    assert result[1] == contents

def test_cat_missing(fs):
    result = cat('file.txt')
    assert result[0] == 'failure'
    assert result[1] is None


text:
import os
import socket

# automatically determine debug status
if 'cai' in socket.getfqdn():
    DEBUG = False
else:
    DEBUG = True

TEMPLATE_DEBUG = DEBUG

ADMINS = (
    ('Ye Tian', 'yxt157@ist.psu.edu'),
)

MANAGERS = ADMINS

server_ip = socket.gethostbyname(socket.gethostname())

GEOS_LIBRARY_PATH = 'C:/OSGeo4W64/bin/geos_c.dll'

# determine if the IST DB can be connected. if not, use local db.
if '130.203' in server_ip:
    SERVER_HOST = '130.203.136.141'
    DATABASES = {
        'default': {
            'ENGINE': 'django.contrib.gis.db.backends.postgis',
            'NAME': 'cir_backup_20161125',  # Or path to database file if using sqlite3.
            'USER': 'postgres',
            'PASSWORD': 'asdf1234',
            'HOST': SERVER_HOST,
            'PORT': '',  # Set to empty string for default.
        },
        'dev': {
            'ENGINE': 'django.contrib.gis.db.backends.postgis',
            'NAME': 'cir_backup_20161125',  # Or path to database file if using sqlite3.
            'USER': 'postgres',
            'PASSWORD': 'asdf1234',
            'HOST': SERVER_HOST,
            'PORT': '',  # Set to empty string for default.
        }
    }
else:
    # on local dev -- use different DB setups
    SERVER_HOST = '127.0.0.1'
    DATABASES = {
        'default': {
            'ENGINE': 'django.contrib.gis.db.backends.postgis',
            'NAME': 'cir_backup_20161125',  # Or path to database file if using sqlite3.
            'USER': 'homestead',
            'PASSWORD': 'secret',
            'HOST': SERVER_HOST,
            'PORT': '',  # Set to empty string for default.
        },
        'dev': {
            'ENGINE': 'django.contrib.gis.db.backends.postgis',
            'NAME': 'cir_backup_20161125',  # Or path to database file if using sqlite3.
            'USER': 'homestead',
            'PASSWORD': 'secret',
            'HOST': SERVER_HOST,
            'PORT': '',  # Set to empty string for default.
        }
    }

# dispatcher url
if DEBUG:
    DISPATCHER_URL = '127.0.0.1:443'
else:
    DISPATCHER_URL = '130.203.136.141:443'

PROJECT_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))
POSTGIS_VERSION = (2, 0, 3)
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = [
    '127.0.0.1',
    'localhost',
    '.ist.psu.edu',
]

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'America/New_York'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True

# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = os.path.join(PROJECT_PATH, 'media/')

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = '/media/'

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"

if DEBUG:
    STATIC_ROOT = os.path.join(PROJECT_PATH, '../cir-static/')
else:
    STATIC_ROOT = os.path.join(PROJECT_PATH, '../static/geolab/')

# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'

# Additional locations of static files
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    os.path.join(PROJECT_PATH, 'static'),
)

STATICFILES_STORAGE = 'pipeline.storage.PipelineStorage'
PIPELINE_EMBED_MAX_IMAGE_SIZE = 120000
PIPELINE_EMBED_PATH = r'[/]?static/embed/'
PIPELINE_CSS = {
    'cir_global': {
        'source_filenames': (
            'css/container.css',
            'css/page_body.css',
        ),
        'output_filename': 'css/cir_global.css',
    },
    'cir_forum': {
        'source_filenames': (
            'css/document.css',
            'css/claim.css',
            'css/chatter.css',
            'css/vis.css'
            ),
        'output_filename': 'css/cir_forum.css',
    },
    'cir_dashboard': {
        'source_filenames': (
            'css/dashboard.css',
        ),
        'output_filename': 'css/cir_dashboard.css',
    }
}

PIPELINE_JS = {
    'cir_global': {
        'source_filenames': (
            'js/header.js',
            'js/utils.js',
        ),
        'output_filename': 'js/cir_global.js',
    },
    'cir_forum': {
        'source_filenames': (
            'js/layout.js',
            'js/document.js',
            'js/claim.js',
            'js/activity-feed.js',
            'js/utils.js',
            'js/workbench2.js',
        ),
        'output_filename': 'js/cir_forum.js',
    },
    'cir_dashboard': {
        'source_filenames': (
            'js/dashboard.js',
        ),
        'output_filename': 'js/cir_dashboard.js',
    }
}

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    'pipeline.finders.PipelineFinder',
    # 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# Make this unique, and don't share it with anybody.
SECRET_KEY = 'cj6k998fi&=fesrf39*2g07jcuf!%)=xfnvji8z2f==d7yb_-d'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
    # 'django.template.loaders.eggs.Loader',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
        # 'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.transaction.TransactionMiddleware',
    # Uncomment the next line for simple clickjacking protection:
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

DATABASE_ROUTERS = ['cir.user_db_router.UserForumRoleRouter']
ROOT_URLCONF = 'cir.urls'

# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'cir.wsgi.application'

BASE_DIR = os.path.dirname(os.path.dirname(__file__))

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    os.path.join(BASE_DIR, 'templates'),
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.admin',
    'django.contrib.admindocs',
    'cir',
    'password_reset',
    'pipeline',
    'mptt',
    'south',
)

SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer'
SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies'
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        },
    },
    'loggers': {
        'django.request': {
            'handlers': ['console'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'community.forum.cir@gmail.com'
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
EMAIL_HOST_PASSWORD = 'geodeliberation'
EMAIL_PORT = 587

# CIR app settings


text:
require 'spec_helper'
require 'input_sanitizer/extended_converters/comma_joined_strings_converter'

describe InputSanitizer::CommaJoinedStringsConverter do
  let(:converter) { described_class.new }

  it "parses to array of ids" do
    converter.call("input,Sanitizer,ROCKS").should eq(["input", "Sanitizer", "ROCKS"])
  end

  it "allows underscores" do
    converter.call("input_sanitizer,rocks").should eq(["input_sanitizer", "rocks"])
  end

  it "raises on invalid character" do
    lambda { converter.call(":") }.should raise_error(InputSanitizer::ConversionError)
  end
end


text:
package org.assertj.core.api.booleanarray;

import static org.assertj.core.api.Assertions.assertThatExceptionOfType;

import java.util.Comparator;

import org.assertj.core.api.BooleanArrayAssert;
import org.assertj.core.api.BooleanArrayAssertBaseTest;
import org.junit.jupiter.api.Test;

/**
 * Tests for <code>{@link BooleanArrayAssert#usingElementComparator(Comparator)}</code>.
 *
 * @author Joel Costigliola
 * @author Mikhail Mazursky
 */
public class BooleanArrayAssert_usingDefaultElementComparator_Test extends BooleanArrayAssertBaseTest {

  @Override
  @Test
  @SuppressWarnings("deprecation")
  public void should_have_internal_effects() {
    assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> assertions.usingDefaultElementComparator());
  }

  @Override
  @Test
  public void should_return_this() {
    // Disabled since this method throws an exception
  }

  @Override
  protected BooleanArrayAssert invoke_api_method() {
    // Not used in this test
    return null;
  }

  @Override
  protected void verify_internal_effects() {
    // Not used in this test
  }

}


text:
if (typeof module !== 'undefined' && module.exports) {
    var assert = require( "assert" );
    var W = require( "../build/W.node.js" );
}

describe( 'promiseWrap', function () {

    it( 'should be a function', function () {
        assert.equal( typeof W.promiseWrap, 'function' );
    });

    it( 'should not throw', function () {
        assert.doesNotThrow( function () {
            var promise = W.promiseWrap( function () {}  )();
        });
    });

    describe( 'success', function () {
        it( 'should get called', function ( done )  {
            var p = W.promiseWrap( function () {} )();
            p.success( function () {
                assert( true );
                done();
            });
        });

        it( 'should send returned values as success arguments', function ( done ) {
            var p = W.promiseWrap( function () { return 10; } )();
            p.success( function ( v ) {
                assert.equal( v, 10 );
                done();
            });
        });
    });

    describe( 'error', function () {
        var error = new Error( 'Deliberate error' );

        it( 'should get called', function ( done )  {
            var p = W.promiseWrap( function () {
                throw error;
            })();
            p.error( function ( err ) {
                assert.equal( err, error );
                done();
            });
        });

    });

});


text:
package com.autumncode.sandbox.executablejar;

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello, world");
    }
}


text:
'use strict'

const _ = require('lodash')
const async = require('async')
const crate = require('mongoose-crate')
const MonError = require('mongoose-crud').MonError
const utils = require('./utils')

module.exports = function(schema, options) {

	const field = options.field
	const fields = {}
	fields[field] = {
		array: options.array || false
	}

	schema.plugin(crate, {
		storage: options.storage,
		fields: fields
	})

	/**
	 * Finds a matching document and attaches a field to it.
	 * Use mongoose-crate plugin for this method to work.
	 *
	 * @method addAttachment
	 *
	 * @example updates a document using key
	 *
	 * Model.addAttachment('john', { path: '/path/to/the/file.png' }, function(error, attachments) { })
	 *
	 * @example updates a document using search conditions
	 *
	 * Model.addAttachment({ name: 'john' }, { path: '/path/to/the/file.png' }, function(error, attachments) { })
	 *
	 * The callback will receive two parameters, `error` if an error occurred,
	 * and `attachments` that contains data from attachment field if the document was updated in the database and null otherwise.
	 *
	 * @param {String|Object}
	 *            key - The document key or search conditions.
	 * @param {Object}
	 *            attachment - The attachment. See mongoose-crate for more information.
	 * @param {Function}
	 *            callback - The callback that handles the response.
	 * @public
	 */

	schema.statics.addAttachment = function(key, attachment, callback) {

		// validate that a callback was provided
		if (!_.isFunction(callback)) throw new MonError('callback must be provided.')

		const self = this

		// find document
		// we have to find document first to enable middleware
		self.getDocument(key, '_id ' + field, {
			lean: false
		}, function(error, document) {
			if (error) return callback(error)
			if (!document) return callback(null, null)

			if (options.array) {

				const oldvalue = _.cloneDeep(document[field])

				const tasks = []
				if (_.isArray(attachment)) {
					attachment.forEach(function(item) {
						tasks.push(function(cb) {
							document.attach(field, item, cb)
						})
					})
				} else {
					tasks.push(function(cb) {
						document.attach(field, attachment, cb)
					})
				}

				async.series(tasks, function(error) {
					/* istanbul ignore next */
					if (error) return callback(new MonError(error))

					// update document
					document.save(function(error) {
						/* istanbul ignore next */
						if (error) return callback(new MonError(error))

						// return the updated property that holds the attachments
						// use id instead of _id for  comparison (_id is the mongo object, while id is a string))
						callback(null, _.differenceBy(document[field], oldvalue, 'id'))
					})
				})

			} else {
				document.attach(field, attachment, function(error) {
					/* istanbul ignore next */
					if (error) return callback(new MonError(error))

					document.save(function(error) {
						/* istanbul ignore next */
						if (error) return callback(new MonError(error))

						// return the updated property that holds the attachments
						callback(null, document[field])
					})
				})
			}
		})
	}

	/**
	 * Finds a matching document and returns an attachment field from it.
	 * Use mongoose-crate plugin for this method to work.
	 *
	 * @method getAttachments
	 *
	 * @example finds all attachments using document key
	 *
	 * Model.getAttachments('john', function(error, attachments) { })
	 *
	 * @example finds all attachments using search conditions
	 *
	 * Model.getAttachments({ name: 'john' }, function(error, attachments) { })
	 *
	 * The callback will receive two parameters, `error` if an error occurred,
	 * and `attachments` that contains data from attachment field if the document was found in the database and null otherwise.
	 *
	 * @param {String|Object}
	 *            key - The document key or search conditions.
	 * @param {Function}
	 *            callback - The callback that handles the response.
	 * @public
	 */

	schema.statics.getAttachments = function(key, callback) {

		// validate that a callback was provided
		if (!_.isFunction(callback)) throw new MonError('callback must be provided.')

		const self = this

		self.getDocument(key, field, function(error, document) {
			/* istanbul ignore next */
			if (error) return callback(error)
			if (!document) return callback(null, null)

			callback(null, document[field] || (options.array ? /* istanbul ignore next */ [] : {}))
		})
	}

	/**
	 * Finds a matching document and returns a matching attachment field from it.
	 * Use mongoose-crate plugin for this method to work.
	 *
	 * @method getAttachment
	 *
	 * @example finds an attachment using document and attachment keys
	 *
	 * Model.getAttachments('john', '123', function(error, updated) { })
	 *
	 * The callback will receive two parameters, `error` if an error occurred,
	 * and `attachment` that contains data from attachment field if the document was found in the database and null otherwise.
	 *
	 * @param {String|Object}
	 *            key - The document key or search conditions.
	 * @param {ObjectId}
	 *            [id] - The id of the attachment to get.
	 * @param {Function}
	 *            callback - The callback that handles the response.
	 * @public
	 */

	schema.statics.getAttachment = function(key, id, callback) {

		// validate that a callback was provided
		if (!_.isFunction(callback)) throw new MonError('callback must be provided.')
		if (!options.array) throw new MonError('This method works with arrays only.')

		const self = this

		utils.createFilter(self.$$crudKey, key, function(error, filter) {
			if (error) return callback(error)
			if (_.isUndefined(id) || _.isNull(id)) return callback(new MonError(MonError.messages.required, 'id'))

			filter[field + '._id'] = id

			self.getDocument(filter, field, function(error, document) {
				/* istanbul ignore next */
				if (error) return callback(error)
				if (!document) return callback(null, null)

				const attachment = _.find(document[field], function(item) {
					return item._id.equals(id)
				})

				callback(null, attachment)
			})
		})
	}

	/**
	 * Finds a matching document and deletes the specified attachment from attached field.
	 * Use mongoose-crate plugin for this method to work.
	 *
	 * @method deleteAttachment
	 *
	 * @example updates a document using key
	 *
	 * Model.deleteAttachment('john', '55551399b467590175f569d8', function(error, updated) { })
	 *
	 * @example updates a document using search conditions
	 *
	 * Model.deleteAttachment({ name: 'john' }, '55551399b467590175f569d8', function(error, updated) { })
	 *
	 * The callback will receive two parameters, `error` if an error occurred,
	 * and `updated` which is true if the document was updated in the database and false otherwise.
	 *
	 * @param {String|Object}
	 *            key - The document key or search conditions.
	 * @param {ObjectId}
	 *            [id] - The id of the attachment to delete. If not specified, the method deletes all attachments.
	 * @param {Function}
	 *            callback - The callback that handles the response.
	 * @public
	 */

	schema.statics.deleteAttachment = function(key, id, callback) {

		// process optional arguments
		if (_.isFunction(id)) {
			callback = id
			id = undefined
		}

		// validate that a callback was provided
		if (!_.isFunction(callback)) throw new MonError('callback must be provided.')

		const self = this

		// find document
		// we have to find document first to enable middleware
		self.getDocument(key, '_id ' + field, {
			lean: false
		}, function(error, document) {
			if (error) return callback(error)
			if (!document) return callback(null, false)

			// find and delete attachment
			if (options.array) {
				if (_.isUndefined(id)) {
					document[field] = []
				} else {
					const index = _.findIndex(document[field], function(item) {
						return item._id.equals(id)
					})
					if (index === -1) return callback(null, false)
					document[field].splice(index, 1)
				}
			} else {
				document[field] = null
			}

			// update document
			document.save(function(error) {
				/* istanbul ignore next */
				if (error) return callback(new MonError(error))

				// return true if the document was updated; otherwise, false
				callback(null, true)
			})
		})
	}
}


text:
package com.tmg.uifwk.orm;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(schema = "DM", name = "ObjectTree")
public class ObjectTree {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "TREEID")
	private Long treeID;

	@ManyToOne
	@JoinColumn(name = "ParentOID")
	private ObjectDefinition parentObject;

	@ManyToOne
	@JoinColumn(name = "RootOID")
	private ObjectDefinition rootObject;

	@ManyToOne
	@JoinColumn(name = "VersionID")
	private ObjectVersion objectVersion;

	@ManyToOne
	@JoinColumn(name = "RelationID")
	private ObjectRelation relation;

	public Long getTreeID() {
		return treeID;
	}

	public void setTreeID(Long treeID) {
		this.treeID = treeID;
	}

	public ObjectDefinition getParentObject() {
		return parentObject;
	}

	public void setParentObject(ObjectDefinition parentObject) {
		this.parentObject = parentObject;
	}

	public ObjectDefinition getRootObject() {
		return rootObject;
	}

	public void setRootObject(ObjectDefinition rootObject) {
		this.rootObject = rootObject;
	}

	public ObjectVersion getObjectVersion() {
		return objectVersion;
	}

	public void setObjectVersion(ObjectVersion objectVersion) {
		this.objectVersion = objectVersion;
	}

	public ObjectRelation getRelation() {
		return relation;
	}

	public void setRelation(ObjectRelation relation) {
		this.relation = relation;
	}

}


text:
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace CodeCracker.CSharp.Refactoring
{

    [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(MergeNestedIfCodeFixProvider)), Shared]
    public class MergeNestedIfCodeFixProvider : CodeFixProvider
    {
        public sealed override ImmutableArray<string> FixableDiagnosticIds =>
            ImmutableArray.Create(DiagnosticId.MergeNestedIf.ToDiagnosticId());

        public sealed override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer;

        public sealed override Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var diagnostic = context.Diagnostics.First();
            context.RegisterCodeFix(CodeAction.Create("Merge nested if statements", c => MergeIfsAsync(context.Document, diagnostic.Location, c), nameof(MergeNestedIfCodeFixProvider)), diagnostic);
            return Task.FromResult(0);
        }

        private async static Task<Document> MergeIfsAsync(Document document, Location diagnosticLocation, CancellationToken cancellationToken)
        {
            var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
            var ifStatement = (IfStatementSyntax)root.FindNode(diagnosticLocation.SourceSpan);
            var newRoot = MergeIfs(ifStatement, root);
            var newDocument = document.WithSyntaxRoot(newRoot);
            return newDocument;
        }

        private static SyntaxNode MergeIfs(IfStatementSyntax ifStatement, SyntaxNode root)
        {
            var nestedIf = (IfStatementSyntax)ifStatement.Statement.GetSingleStatementFromPossibleBlock();
            var newIf = ifStatement
                .WithCondition(SyntaxFactory.BinaryExpression(SyntaxKind.LogicalAndExpression, ifStatement.Condition, nestedIf.Condition))
                .WithStatement(nestedIf.Statement)
                .WithLeadingTrivia(ifStatement.GetLeadingTrivia().AddRange(nestedIf.GetLeadingTrivia()))
                .WithAdditionalAnnotations(Formatter.Annotation);
            if (ifStatement.HasTrailingTrivia && nestedIf.HasTrailingTrivia && !ifStatement.GetTrailingTrivia().Equals(nestedIf.GetTrailingTrivia()))
                newIf = newIf.WithTrailingTrivia(ifStatement.GetTrailingTrivia().AddRange(nestedIf.GetTrailingTrivia()));
            var newRoot = root.ReplaceNode(ifStatement, newIf);
            return newRoot;
        }
    }
}