text:
/**
 * @constructor
 */
WebInspector.Settings = function()
{
    this._eventSupport = new WebInspector.Object();
    this._registry = /** @type {!Object.<string, !WebInspector.Setting>} */ ({});

    this.colorFormat = this.createSetting("colorFormat", "original");
    this.consoleHistory = this.createSetting("consoleHistory", []);
    this.domWordWrap = this.createSetting("domWordWrap", true);
    this.eventListenersFilter = this.createSetting("eventListenersFilter", "all");
    this.lastViewedScriptFile = this.createSetting("lastViewedScriptFile", "application");
    this.monitoringXHREnabled = this.createSetting("monitoringXHREnabled", false);
    this.preserveConsoleLog = this.createSetting("preserveConsoleLog", false);
    this.consoleTimestampsEnabled = this.createSetting("consoleTimestampsEnabled", false);
    this.resourcesLargeRows = this.createSetting("resourcesLargeRows", true);
    this.resourcesSortOptions = this.createSetting("resourcesSortOptions", {timeOption: "responseTime", sizeOption: "transferSize"});
    this.resourceViewTab = this.createSetting("resourceViewTab", "preview");
    this.showInheritedComputedStyleProperties = this.createSetting("showInheritedComputedStyleProperties", false);
    this.showUserAgentStyles = this.createSetting("showUserAgentStyles", true);
    this.watchExpressions = this.createSetting("watchExpressions", []);
    this.breakpoints = this.createSetting("breakpoints", []);
    this.eventListenerBreakpoints = this.createSetting("eventListenerBreakpoints", []);
    this.domBreakpoints = this.createSetting("domBreakpoints", []);
    this.xhrBreakpoints = this.createSetting("xhrBreakpoints", []);
    this.jsSourceMapsEnabled = this.createSetting("sourceMapsEnabled", true);
    this.cssSourceMapsEnabled = this.createSetting("cssSourceMapsEnabled", true);
    this.cacheDisabled = this.createSetting("cacheDisabled", false);
    this.showUAShadowDOM = this.createSetting("showUAShadowDOM", false);
    this.savedURLs = this.createSetting("savedURLs", {});
    this.javaScriptDisabled = this.createSetting("javaScriptDisabled", false);
    this.showAdvancedHeapSnapshotProperties = this.createSetting("showAdvancedHeapSnapshotProperties", false);
    this.recordAllocationStacks = this.createSetting("recordAllocationStacks", false);
    this.highResolutionCpuProfiling = this.createSetting("highResolutionCpuProfiling", false);
    this.searchInContentScripts = this.createSetting("searchInContentScripts", false);
    this.textEditorIndent = this.createSetting("textEditorIndent", "    ");
    this.textEditorAutoDetectIndent = this.createSetting("textEditorAutoIndentIndent", true);
    this.textEditorAutocompletion = this.createSetting("textEditorAutocompletion", true);
    this.textEditorBracketMatching = this.createSetting("textEditorBracketMatching", true);
    this.cssReloadEnabled = this.createSetting("cssReloadEnabled", false);
    this.timelineLiveUpdate = this.createSetting("timelineLiveUpdate", true);
    this.showMetricsRulers = this.createSetting("showMetricsRulers", false);
    this.workerInspectorWidth = this.createSetting("workerInspectorWidth", 600);
    this.workerInspectorHeight = this.createSetting("workerInspectorHeight", 600);
    this.messageURLFilters = this.createSetting("messageURLFilters", {});
    this.networkHideDataURL = this.createSetting("networkHideDataURL", false);
    this.networkResourceTypeFilters = this.createSetting("networkResourceTypeFilters", {});
    this.messageLevelFilters = this.createSetting("messageLevelFilters", {});
    this.splitVerticallyWhenDockedToRight = this.createSetting("splitVerticallyWhenDockedToRight", true);
    this.visiblePanels = this.createSetting("visiblePanels", {});
    this.shortcutPanelSwitch = this.createSetting("shortcutPanelSwitch", false);
    this.showWhitespacesInEditor = this.createSetting("showWhitespacesInEditor", false);
    this.skipStackFramesPattern = this.createRegExpSetting("skipStackFramesPattern", "");
    this.skipContentScripts = this.createSetting("skipContentScripts", false);
    this.pauseOnExceptionEnabled = this.createSetting("pauseOnExceptionEnabled", false);
    this.pauseOnCaughtException = this.createSetting("pauseOnCaughtException", false);
    this.enableAsyncStackTraces = this.createSetting("enableAsyncStackTraces", false);
    this.showMediaQueryInspector = this.createSetting("showMediaQueryInspector", false);
    this.disableOverridesWarning = this.createSetting("disableOverridesWarning", false);

    // Rendering options
    this.showPaintRects = this.createSetting("showPaintRects", false);
    this.showDebugBorders = this.createSetting("showDebugBorders", false);
    this.showFPSCounter = this.createSetting("showFPSCounter", false);
    this.continuousPainting = this.createSetting("continuousPainting", false);
    this.showScrollBottleneckRects = this.createSetting("showScrollBottleneckRects", false);
}

WebInspector.Settings.prototype = {
    /**
     * @param {string} key
     * @param {*} defaultValue
     * @return {!WebInspector.Setting}
     */
    createSetting: function(key, defaultValue)
    {
        if (!this._registry[key])
            this._registry[key] = new WebInspector.Setting(key, defaultValue, this._eventSupport, window.localStorage);
        return this._registry[key];
    },

    /**
     * @param {string} key
     * @param {string} defaultValue
     * @param {string=} regexFlags
     * @return {!WebInspector.Setting}
     */
    createRegExpSetting: function(key, defaultValue, regexFlags)
    {
        if (!this._registry[key])
            this._registry[key] = new WebInspector.RegExpSetting(key, defaultValue, this._eventSupport, window.localStorage, regexFlags);
        return this._registry[key];
    }
}

/**
 * @constructor
 * @param {string} name
 * @param {V} defaultValue
 * @param {!WebInspector.Object} eventSupport
 * @param {?Storage} storage
 * @template V
 */
WebInspector.Setting = function(name, defaultValue, eventSupport, storage)
{
    this._name = name;
    this._defaultValue = defaultValue;
    this._eventSupport = eventSupport;
    this._storage = storage;
}

WebInspector.Setting.prototype = {
    /**
     * @param {function(!WebInspector.Event)} listener
     * @param {!Object=} thisObject
     */
    addChangeListener: function(listener, thisObject)
    {
        this._eventSupport.addEventListener(this._name, listener, thisObject);
    },

    /**
     * @param {function(!WebInspector.Event)} listener
     * @param {!Object=} thisObject
     */
    removeChangeListener: function(listener, thisObject)
    {
        this._eventSupport.removeEventListener(this._name, listener, thisObject);
    },

    get name()
    {
        return this._name;
    },

    /**
     * @return {V}
     */
    get: function()
    {
        if (typeof this._value !== "undefined")
            return this._value;

        this._value = this._defaultValue;
        if (this._storage && this._name in this._storage) {
            try {
                this._value = JSON.parse(this._storage[this._name]);
            } catch(e) {
                delete this._storage[this._name];
            }
        }
        return this._value;
    },

    /**
     * @param {V} value
     */
    set: function(value)
    {
        this._value = value;
        if (this._storage) {
            try {
                var settingString = JSON.stringify(value);
                try {
                    this._storage[this._name] = settingString;
                } catch(e) {
                    this._printSettingsSavingError(e.message, this._name, settingString);
                }
            } catch(e) {
                WebInspector.console.error("Cannot stringify setting with name: " + this._name + ", error: " + e.message);
            }
        }
        this._eventSupport.dispatchEventToListeners(this._name, value);
    },

    /**
     * @param {string} message
     * @param {string} name
     * @param {string} value
     */
    _printSettingsSavingError: function(message, name, value)
    {
        var errorMessage = "Error saving setting with name: " + this._name + ", value length: " + value.length + ". Error: " + message;
        console.error(errorMessage);
        WebInspector.console.error(errorMessage);
        WebInspector.console.log("Ten largest settings: ");

        var sizes = { __proto__: null };
        for (var key in this._storage)
            sizes[key] = this._storage.getItem(key).length;
        var keys = Object.keys(sizes);

        function comparator(key1, key2)
        {
            return sizes[key2] - sizes[key1];
        }

        keys.sort(comparator);

        for (var i = 0; i < 10 && i < keys.length; ++i)
            WebInspector.console.log("Setting: '" + keys[i] + "', size: " + sizes[keys[i]]);
    },
}

/**
 * @constructor
 * @extends {WebInspector.Setting}
 * @param {string} name
 * @param {string} defaultValue
 * @param {!WebInspector.Object} eventSupport
 * @param {?Storage} storage
 * @param {string=} regexFlags
 */
WebInspector.RegExpSetting = function(name, defaultValue, eventSupport, storage, regexFlags)
{
    WebInspector.Setting.call(this, name, defaultValue ? [{ pattern: defaultValue }] : [], eventSupport, storage);
    this._regexFlags = regexFlags;
}

WebInspector.RegExpSetting.prototype = {
    /**
     * @override
     * @return {string}
     */
    get: function()
    {
        var result = [];
        var items = this.getAsArray();
        for (var i = 0; i < items.length; ++i) {
            var item = items[i];
            if (item.pattern && !item.disabled)
                result.push(item.pattern);
        }
        return result.join("|");
    },

    /**
     * @return {!Array.<{pattern: string, disabled: (boolean|undefined)}>}
     */
    getAsArray: function()
    {
        return WebInspector.Setting.prototype.get.call(this);
    },

    /**
     * @override
     * @param {string} value
     */
    set: function(value)
    {
        this.setAsArray([{ pattern: value }]);
    },

    /**
     * @param {!Array.<{pattern: string, disabled: (boolean|undefined)}>} value
     */
    setAsArray: function(value)
    {
        delete this._regex;
        WebInspector.Setting.prototype.set.call(this, value);
    },

    /**
     * @return {?RegExp}
     */
    asRegExp: function()
    {
        if (typeof this._regex !== "undefined")
            return this._regex;
        this._regex = null;
        try {
            var pattern = this.get();
            if (pattern)
                this._regex = new RegExp(pattern, this._regexFlags || "");
        } catch (e) {
        }
        return this._regex;
    },

    __proto__: WebInspector.Setting.prototype
}

/**
 * @constructor
 * @param {boolean} experimentsEnabled
 */
WebInspector.ExperimentsSettings = function(experimentsEnabled)
{
    this._experimentsEnabled = experimentsEnabled;
    this._setting = WebInspector.settings.createSetting("experiments", {});
    this._experiments = [];
    this._enabledForTest = {};

    // Add currently running experiments here.
    this.applyCustomStylesheet = this._createExperiment("applyCustomStylesheet", "Allow custom UI themes");
    this.canvasInspection = this._createExperiment("canvasInspection ", "Canvas inspection");
    this.devicesPanel = this._createExperiment("devicesPanel", "Devices panel");
    this.disableAgentsWhenProfile = this._createExperiment("disableAgentsWhenProfile", "Disable other agents and UI when profiler is active", true);
    this.dockToLeft = this._createExperiment("dockToLeft", "Dock to left", true);
    this.documentation = this._createExperiment("documentation", "JavaScript documentation", true);
    this.fileSystemInspection = this._createExperiment("fileSystemInspection", "FileSystem inspection");
    this.gpuTimeline = this._createExperiment("gpuTimeline", "GPU data on timeline", true);
    this.layersPanel = this._createExperiment("layersPanel", "Layers panel");
    this.paintProfiler = this._createExperiment("paintProfiler", "Paint profiler");
    this.timelineOnTraceEvents = this._createExperiment("timelineOnTraceEvents", "Timeline on trace events");
    this.timelinePowerProfiler = this._createExperiment("timelinePowerProfiler", "Timeline power profiler");
    this.timelineJSCPUProfile = this._createExperiment("timelineJSCPUProfile", "Timeline with JS sampling");

    this._cleanUpSetting();
}

WebInspector.ExperimentsSettings.prototype = {
    /**
     * @return {!Array.<!WebInspector.Experiment>}
     */
    get experiments()
    {
        return this._experiments.slice();
    },

    /**
     * @return {boolean}
     */
    get experimentsEnabled()
    {
        return this._experimentsEnabled;
    },

    /**
     * @param {string} experimentName
     * @param {string} experimentTitle
     * @param {boolean=} hidden
     * @return {!WebInspector.Experiment}
     */
    _createExperiment: function(experimentName, experimentTitle, hidden)
    {
        var experiment = new WebInspector.Experiment(this, experimentName, experimentTitle, !!hidden);
        this._experiments.push(experiment);
        return experiment;
    },

    /**
     * @param {string} experimentName
     * @return {boolean}
     */
    isEnabled: function(experimentName)
    {
        if (this._enabledForTest[experimentName])
            return true;

        if (!this.experimentsEnabled)
            return false;

        var experimentsSetting = this._setting.get();
        return experimentsSetting[experimentName];
    },

    /**
     * @param {string} experimentName
     * @param {boolean} enabled
     */
    setEnabled: function(experimentName, enabled)
    {
        var experimentsSetting = this._setting.get();
        experimentsSetting[experimentName] = enabled;
        this._setting.set(experimentsSetting);
    },

    /**
     * @param {string} experimentName
     */
    _enableForTest: function(experimentName)
    {
        this._enabledForTest[experimentName] = true;
    },

    _cleanUpSetting: function()
    {
        var experimentsSetting = this._setting.get();
        var cleanedUpExperimentSetting = {};
        for (var i = 0; i < this._experiments.length; ++i) {
            var experimentName = this._experiments[i].name;
            if (experimentsSetting[experimentName])
                cleanedUpExperimentSetting[experimentName] = true;
        }
        this._setting.set(cleanedUpExperimentSetting);
    }
}

/**
 * @constructor
 * @param {!WebInspector.ExperimentsSettings} experimentsSettings
 * @param {string} name
 * @param {string} title
 * @param {boolean} hidden
 */
WebInspector.Experiment = function(experimentsSettings, name, title, hidden)
{
    this._name = name;
    this._title = title;
    this._hidden = hidden;
    this._experimentsSettings = experimentsSettings;
}

WebInspector.Experiment.prototype = {
    /**
     * @return {string}
     */
    get name()
    {
        return this._name;
    },

    /**
     * @return {string}
     */
    get title()
    {
        return this._title;
    },

    /**
     * @return {boolean}
     */
    get hidden()
    {
        return this._hidden;
    },

    /**
     * @return {boolean}
     */
    isEnabled: function()
    {
        return this._experimentsSettings.isEnabled(this._name);
    },

    /**
     * @param {boolean} enabled
     */
    setEnabled: function(enabled)
    {
        this._experimentsSettings.setEnabled(this._name, enabled);
    },

    enableForTest: function()
    {
        this._experimentsSettings._enableForTest(this._name);
    }
}

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

WebInspector.VersionController.currentVersion = 10;

WebInspector.VersionController.prototype = {
    updateVersion: function()
    {
        var versionSetting = WebInspector.settings.createSetting("inspectorVersion", 0);
        var currentVersion = WebInspector.VersionController.currentVersion;
        var oldVersion = versionSetting.get();
        var methodsToRun = this._methodsToRunToUpdateVersion(oldVersion, currentVersion);
        for (var i = 0; i < methodsToRun.length; ++i)
            this[methodsToRun[i]].call(this);
        versionSetting.set(currentVersion);
    },

    /**
     * @param {number} oldVersion
     * @param {number} currentVersion
     */
    _methodsToRunToUpdateVersion: function(oldVersion, currentVersion)
    {
        var result = [];
        for (var i = oldVersion; i < currentVersion; ++i)
            result.push("_updateVersionFrom" + i + "To" + (i + 1));
        return result;
    },

    _updateVersionFrom0To1: function()
    {
        this._clearBreakpointsWhenTooMany(WebInspector.settings.breakpoints, 500000);
    },

    _updateVersionFrom1To2: function()
    {
        var versionSetting = WebInspector.settings.createSetting("previouslyViewedFiles", []);
        versionSetting.set([]);
    },

    _updateVersionFrom2To3: function()
    {
        var fileSystemMappingSetting = WebInspector.settings.createSetting("fileSystemMapping", {});
        fileSystemMappingSetting.set({});
        if (window.localStorage)
            delete window.localStorage["fileMappingEntries"];
    },

    _updateVersionFrom3To4: function()
    {
        var advancedMode = WebInspector.settings.createSetting("showHeaSnapshotObjectsHiddenProperties", false).get();
        WebInspector.settings.showAdvancedHeapSnapshotProperties.set(advancedMode);
    },

    _updateVersionFrom4To5: function()
    {
        if (!window.localStorage)
            return;
        var settingNames = {
            "FileSystemViewSidebarWidth": "fileSystemViewSplitViewState",
            "canvasProfileViewReplaySplitLocation": "canvasProfileViewReplaySplitViewState",
            "canvasProfileViewSplitLocation": "canvasProfileViewSplitViewState",
            "elementsSidebarWidth": "elementsPanelSplitViewState",
            "StylesPaneSplitRatio": "stylesPaneSplitViewState",
            "heapSnapshotRetainersViewSize": "heapSnapshotSplitViewState",
            "InspectorView.splitView": "InspectorView.splitViewState",
            "InspectorView.screencastSplitView": "InspectorView.screencastSplitViewState",
            "Inspector.drawerSplitView": "Inspector.drawerSplitViewState",
            "layerDetailsSplitView": "layerDetailsSplitViewState",
            "networkSidebarWidth": "networkPanelSplitViewState",
            "sourcesSidebarWidth": "sourcesPanelSplitViewState",
            "scriptsPanelNavigatorSidebarWidth": "sourcesPanelNavigatorSplitViewState",
            "sourcesPanelSplitSidebarRatio": "sourcesPanelDebuggerSidebarSplitViewState",
            "timeline-details": "timelinePanelDetailsSplitViewState",
            "timeline-split": "timelinePanelRecorsSplitViewState",
            "timeline-view": "timelinePanelTimelineStackSplitViewState",
            "auditsSidebarWidth": "auditsPanelSplitViewState",
            "layersSidebarWidth": "layersPanelSplitViewState",
            "profilesSidebarWidth": "profilesPanelSplitViewState",
            "resourcesSidebarWidth": "resourcesPanelSplitViewState"
        };
        for (var oldName in settingNames) {
            var newName = settingNames[oldName];
            var oldNameH = oldName + "H";

            var newValue = null;
            var oldSetting = WebInspector.settings.createSetting(oldName, undefined).get();
            if (oldSetting) {
                newValue = newValue || {};
                newValue.vertical = {};
                newValue.vertical.size = oldSetting;
                delete window.localStorage[oldName];
            }
            var oldSettingH = WebInspector.settings.createSetting(oldNameH, undefined).get();
            if (oldSettingH) {
                newValue = newValue || {};
                newValue.horizontal = {};
                newValue.horizontal.size = oldSettingH;
                delete window.localStorage[oldNameH];
            }
            var newSetting = WebInspector.settings.createSetting(newName, {});
            if (newValue)
                newSetting.set(newValue);
        }
    },

    _updateVersionFrom5To6: function()
    {
        if (!window.localStorage)
            return;

        var settingNames = {
            "debuggerSidebarHidden": "sourcesPanelSplitViewState",
            "navigatorHidden": "sourcesPanelNavigatorSplitViewState",
            "WebInspector.Drawer.showOnLoad": "Inspector.drawerSplitViewState"
        };

        for (var oldName in settingNames) {
            var newName = settingNames[oldName];

            var oldSetting = WebInspector.settings.createSetting(oldName, undefined).get();
            var invert = "WebInspector.Drawer.showOnLoad" === oldName;
            var hidden = !!oldSetting !== invert;
            delete window.localStorage[oldName];
            var showMode = hidden ? "OnlyMain" : "Both";

            var newSetting = WebInspector.settings.createSetting(newName, null);
            var newValue = newSetting.get() || {};
            newValue.vertical = newValue.vertical || {};
            newValue.vertical.showMode = showMode;
            newValue.horizontal = newValue.horizontal || {};
            newValue.horizontal.showMode = showMode;
            newSetting.set(newValue);
        }
    },

    _updateVersionFrom6To7: function()
    {
        if (!window.localStorage)
            return;

        var settingNames = {
            "sourcesPanelNavigatorSplitViewState": "sourcesPanelNavigatorSplitViewState",
            "elementsPanelSplitViewState": "elementsPanelSplitViewState",
            "canvasProfileViewReplaySplitViewState": "canvasProfileViewReplaySplitViewState",
            "stylesPaneSplitViewState": "stylesPaneSplitViewState",
            "sourcesPanelDebuggerSidebarSplitViewState": "sourcesPanelDebuggerSidebarSplitViewState"
        };

        for (var name in settingNames) {
            if (!(name in window.localStorage))
                continue;
            var setting = WebInspector.settings.createSetting(name, undefined);
            var value = setting.get();
            if (!value)
                continue;
            // Zero out saved percentage sizes, and they will be restored to defaults.
            if (value.vertical && value.vertical.size && value.vertical.size < 1)
                value.vertical.size = 0;
            if (value.horizontal && value.horizontal.size && value.horizontal.size < 1)
                value.horizontal.size = 0;
            setting.set(value);
        }
    },

    _updateVersionFrom7To8: function()
    {
        var settingName = "deviceMetrics";
        if (!window.localStorage || !(settingName in window.localStorage))
            return;
        var setting = WebInspector.settings.createSetting(settingName, undefined);
        var value = setting.get();
        if (!value)
            return;

        var components = value.split("x");
        if (components.length >= 3) {
            var width = parseInt(components[0], 10);
            var height = parseInt(components[1], 10);
            var deviceScaleFactor = parseFloat(components[2]);
            if (deviceScaleFactor) {
                components[0] = "" + Math.round(width / deviceScaleFactor);
                components[1] = "" + Math.round(height / deviceScaleFactor);
            }
        }
        value = components.join("x");
        setting.set(value);
    },

    _updateVersionFrom8To9: function()
    {
        if (!window.localStorage)
            return;

        var settingNames = [
            "skipStackFramesPattern",
            "workspaceFolderExcludePattern"
        ];

        for (var i = 0; i < settingNames.length; ++i) {
            var settingName = settingNames[i];
            if (!(settingName in window.localStorage))
                continue;
            try {
                var value = JSON.parse(window.localStorage[settingName]);
                if (!value)
                    continue;
                if (typeof value === "string")
                    value = [value];
                for (var j = 0; j < value.length; ++j) {
                    if (typeof value[j] === "string")
                        value[j] = { pattern: value[j] };
                }
                window.localStorage[settingName] = JSON.stringify(value);
            } catch(e) {
            }
        }
    },

    _updateVersionFrom9To10: function()
    {
        if (!window.localStorage)
            return;

        for (var key in window.localStorage) {
            if (key.startsWith("revision-history"))
                window.localStorage.removeItem(key);
        }
    },

    /**
     * @param {!WebInspector.Setting} breakpointsSetting
     * @param {number} maxBreakpointsCount
     */
    _clearBreakpointsWhenTooMany: function(breakpointsSetting, maxBreakpointsCount)
    {
        // If there are too many breakpoints in a storage, it is likely due to a recent bug that caused
        // periodical breakpoints duplication leading to inspector slowness.
        if (breakpointsSetting.get().length > maxBreakpointsCount)
            breakpointsSetting.set([]);
    }
}

/**
 * @type {!WebInspector.Settings}
 */
WebInspector.settings;

/**
 * @type {!WebInspector.ExperimentsSettings}
 */
WebInspector.experimentsSettings;

// These methods are added for backwards compatibility with Devtools CodeSchool extension.
// DO NOT REMOVE

/**
 * @constructor
 */
WebInspector.PauseOnExceptionStateSetting = function()
{
    WebInspector.settings.pauseOnExceptionEnabled.addChangeListener(this._enabledChanged, this);
    WebInspector.settings.pauseOnCaughtException.addChangeListener(this._pauseOnCaughtChanged, this);
    this._name = "pauseOnExceptionStateString";
    this._eventSupport = new WebInspector.Object();
    this._value = this._calculateValue();
}

WebInspector.PauseOnExceptionStateSetting.prototype = {
    /**
     * @param {function(!WebInspector.Event)} listener
     * @param {!Object=} thisObject
     */
    addChangeListener: function(listener, thisObject)
    {
        this._eventSupport.addEventListener(this._name, listener, thisObject);
    },

    /**
     * @param {function(!WebInspector.Event)} listener
     * @param {!Object=} thisObject
     */
    removeChangeListener: function(listener, thisObject)
    {
        this._eventSupport.removeEventListener(this._name, listener, thisObject);
    },

    /**
     * @return {string}
     */
    get: function()
    {
        return this._value;
    },

    /**
     * @return {string}
     */
    _calculateValue: function()
    {
        if (!WebInspector.settings.pauseOnExceptionEnabled.get())
            return "none";
        // The correct code here would be
        //     return WebInspector.settings.pauseOnCaughtException.get() ? "all" : "uncaught";
        // But the CodeSchool DevTools relies on the fact that we used to enable pausing on ALL extensions by default, so we trick it here.
        return "all";
    },

    _enabledChanged: function(event)
    {
        this._fireChangedIfNeeded();
    },

    _pauseOnCaughtChanged: function(event)
    {
        this._fireChangedIfNeeded();
    },

    _fireChangedIfNeeded: function()
    {
        var newValue = this._calculateValue();
        if (newValue === this._value)
            return;
        this._value = newValue;
        this._eventSupport.dispatchEventToListeners(this._name, this._value);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ShowReminder.Web.Models;
using ShowReminder.TMDBFetcher.Model.TV;

namespace ShowReminder.Web.Mapper
{
    public static class ShowMapper
    {
        public static Show ToModel(this TVShow show)
        {
            var model = new Show()
            {
                Id = show.Id,
                Name = show.Name,
                Overview = show.Overview,
                Status = show.Status,
                FirstAired = show.FirstAirDate
            };

            var airDate = show.LastAirDate ?? show.FirstAirDate;

            if (null != airDate)
            {
                model.AirsDayOfWeek = airDate.Value.ToString("dddd");
            }

            return model;
        }

        public static IEnumerable<Show> ToModel(this IEnumerable<TVShow> shows)
        {
            return shows.Select(x => x.ToModel());
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
001
016
017    package com.google.common.collect;
018
019    import com.google.common.collect.MapConstraints.ConstrainedMap;
020    import com.google.common.primitives.Primitives;
021
022    import java.util.HashMap;
023    import java.util.Map;
024
025    /**
026     * A mutable class-to-instance map backed by an arbitrary user-provided map.
027     * See also {@link ImmutableClassToInstanceMap}.
028     *
029     * @author Kevin Bourrillion
030     * @since 2 (imported from Google Collections Library)
031     */
032    public final class MutableClassToInstanceMap<B>
033        extends ConstrainedMap<Class<? extends B>, B>
034        implements ClassToInstanceMap<B> {
035
036      /**
037       * Returns a new {@code MutableClassToInstanceMap} instance backed by a {@link
038       * HashMap} using the default initial capacity and load factor.
039       */
040      public static <B> MutableClassToInstanceMap<B> create() {
041        return new MutableClassToInstanceMap<B>(
042            new HashMap<Class<? extends B>, B>());
043      }
044
045      /**
046       * Returns a new {@code MutableClassToInstanceMap} instance backed by a given
047       * empty {@code backingMap}. The caller surrenders control of the backing map,
048       * and thus should not allow any direct references to it to remain accessible.
049       */
050      public static <B> MutableClassToInstanceMap<B> create(
051          Map<Class<? extends B>, B> backingMap) {
052        return new MutableClassToInstanceMap<B>(backingMap);
053      }
054
055      private MutableClassToInstanceMap(Map<Class<? extends B>, B> delegate) {
056        super(delegate, VALUE_CAN_BE_CAST_TO_KEY);
057      }
058
059      private static final MapConstraint<Class<?>, Object> VALUE_CAN_BE_CAST_TO_KEY
060          = new MapConstraint<Class<?>, Object>() {
061        public void checkKeyValue(Class<?> key, Object value) {
062          cast(key, value);
063        }
064      };
065
066      public <T extends B> T putInstance(Class<T> type, T value) {
067        return cast(type, put(type, value));
068      }
069
070      public <T extends B> T getInstance(Class<T> type) {
071        return cast(type, get(type));
072      }
073
074      private static <B, T extends B> T cast(Class<T> type, B value) {
075        return Primitives.wrap(type).cast(value);
076      }
077
078      private static final long serialVersionUID = 0;
079    }


text:
package org.wso2.siddhi.core.query.ratelimit;

import junit.framework.Assert;
import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import org.wso2.siddhi.core.ExecutionPlanRuntime;
import org.wso2.siddhi.core.SiddhiManager;
import org.wso2.siddhi.core.event.Event;
import org.wso2.siddhi.core.query.output.callback.QueryCallback;
import org.wso2.siddhi.core.stream.input.InputHandler;
import org.wso2.siddhi.core.util.EventPrinter;

public class EventOutputRateLimitTestCase {
    static final Logger log = Logger.getLogger(EventOutputRateLimitTestCase.class);
    private volatile int count;
    private volatile boolean eventArrived;

    @Before
    public void init() {
        count = 0;
        eventArrived = false;
    }

    @Test
    public void testEventOutputRateLimitQuery1() throws InterruptedException {
        log.info("EventOutputRateLimit test1");

        SiddhiManager siddhiManager = new SiddhiManager();

        String executionPlan = "" +
                "@Plan:name('EventOutputRateLimitTest1') " +
                "" +
                "define stream LoginEvents (timeStamp long, ip string);" +
                "" +
                "@info(name = 'query1') " +
                "from LoginEvents " +
                "select ip " +
                "output all every 2 events " +
                "insert into uniqueIps ;";

        ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(executionPlan);

        log.info("Running : " + executionPlanRuntime.getName());

        executionPlanRuntime.addCallback("query1", new QueryCallback() {
            @Override
            public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
                EventPrinter.print(timeStamp, inEvents, removeEvents);
                if (inEvents != null) {
                    count += inEvents.length;
                } else {
                    Assert.fail("Remove events emitted");
                }
                eventArrived = true;
            }

        });

        InputHandler inputHandler = executionPlanRuntime.getInputHandler("LoginEvents");

        executionPlanRuntime.start();

        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.3"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.3"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.4"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.3"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.5"});

        Thread.sleep(1000);
        Assert.assertEquals("Event arrived", true, eventArrived);
        Assert.assertEquals("Number of output event value", 4, count);

        executionPlanRuntime.shutdown();

    }

    @Test
    public void testEventOutputRateLimitQuery2() throws InterruptedException {
        log.info("EventOutputRateLimit test2");

        SiddhiManager siddhiManager = new SiddhiManager();

        String executionPlan = "" +
                "@Plan:name('EventOutputRateLimitTest2') " +
                "" +
                "define stream LoginEvents (timeStamp long, ip string);" +
                "" +
                "@info(name = 'query1') " +
                "from LoginEvents " +
                "select ip " +
                "output every 2 events " +
                "insert into uniqueIps ;";

        ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(executionPlan);

        log.info("Running : " + executionPlanRuntime.getName());

        executionPlanRuntime.addCallback("query1", new QueryCallback() {
            @Override
            public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
                EventPrinter.print(timeStamp, inEvents, removeEvents);
                if (inEvents != null) {
                    count += inEvents.length;
                } else {
                    Assert.fail("Remove events emitted");
                }
                eventArrived = true;
            }

        });

        InputHandler inputHandler = executionPlanRuntime.getInputHandler("LoginEvents");

        executionPlanRuntime.start();

        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.3"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.3"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.4"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.3"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.5"});

        Thread.sleep(1000);

        Assert.assertEquals("Event arrived", true, eventArrived);
        Assert.assertEquals("Number of output event value", 4, count);
        executionPlanRuntime.shutdown();
    }

    @Test
    public void testEventOutputRateLimitQuery3() throws InterruptedException {
        log.info("EventOutputRateLimit test3");

        SiddhiManager siddhiManager = new SiddhiManager();

        String executionPlan = "" +
                "@Plan:name('EventOutputRateLimitTest3') " +
                "" +
                "define stream LoginEvents (timeStamp long, ip string);" +
                "" +
                "@info(name = 'query1') " +
                "from LoginEvents " +
                "select ip " +
                "output every 5 events " +
                "insert into uniqueIps ;";

        ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(executionPlan);

        log.info("Running : " + executionPlanRuntime.getName());

        executionPlanRuntime.addCallback("query1", new QueryCallback() {
            @Override
            public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
                EventPrinter.print(timeStamp, inEvents, removeEvents);
                if (inEvents != null) {
                    count += inEvents.length;
                } else {
                    Assert.fail("Remove events emitted");
                }
                eventArrived = true;
            }

        });

        InputHandler inputHandler = executionPlanRuntime.getInputHandler("LoginEvents");

        executionPlanRuntime.start();

        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.5"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.5"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.3"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.9"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.4"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.4"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.4"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.30"});

        Thread.sleep(1000);

        Assert.assertEquals("Event arrived", true, eventArrived);
        Assert.assertEquals("Number of output event value", 5, count);
        executionPlanRuntime.shutdown();

    }

    @Test
    public void testEventOutputRateLimitQuery4() throws InterruptedException {
        log.info("EventOutputRateLimit test4");

        SiddhiManager siddhiManager = new SiddhiManager();

        String executionPlan = "" +
                "@Plan:name('EventOutputRateLimitTest4') " +
                "" +
                "define stream LoginEvents (timeStamp long, ip string);" +
                "" +
                "@info(name = 'query1') " +
                "from LoginEvents " +
                "select ip " +
                "output first every 2 events " +
                "insert into uniqueIps ;";

        ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(executionPlan);

        log.info("Running : " + executionPlanRuntime.getName());

        executionPlanRuntime.addCallback("query1", new QueryCallback() {
            @Override
            public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
                EventPrinter.print(timeStamp, inEvents, removeEvents);
                if (inEvents != null) {
                    count += inEvents.length;
                    Assert.assertTrue("192.10.1.5".equals(inEvents[0].getData(0)) || "192.10.1.9".equals(inEvents[0].getData(0)) || "192.10.1.3".equals(inEvents[0].getData(0)));
                } else {
                    Assert.fail("Remove events emitted");
                }
                eventArrived = true;
            }

        });

        InputHandler inputHandler = executionPlanRuntime.getInputHandler("LoginEvents");

        executionPlanRuntime.start();

        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.5"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.3"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.9"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.4"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.3"});

        Thread.sleep(1000);

        Assert.assertEquals("Event arrived", true, eventArrived);
        Assert.assertEquals("Number of output event value", 3, count);
        executionPlanRuntime.shutdown();
    }

    @Test
    public void testEventOutputRateLimitQuery5() throws InterruptedException {
        log.info("EventOutputRateLimit test5");

        SiddhiManager siddhiManager = new SiddhiManager();

        String executionPlan = "" +
                "@Plan:name('EventOutputRateLimitTest5') " +
                "" +
                "define stream LoginEvents (timeStamp long, ip string);" +
                "" +
                "@info(name = 'query1') " +
                "from LoginEvents " +
                "select ip " +
                "output first every 3 events " +
                "insert into uniqueIps ;";

        ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(executionPlan);

        log.info("Running : " + executionPlanRuntime.getName());

        executionPlanRuntime.addCallback("query1", new QueryCallback() {
            @Override
            public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
                EventPrinter.print(timeStamp, inEvents, removeEvents);
                if (inEvents != null) {
                    count += inEvents.length;
                    Assert.assertTrue("192.10.1.5".equals(inEvents[0].getData(0)) || "192.10.1.4".equals(inEvents[0].getData(0)));
                } else {
                    Assert.fail("Remove events emitted");
                }
                eventArrived = true;
            }

        });

        InputHandler inputHandler = executionPlanRuntime.getInputHandler("LoginEvents");

        executionPlanRuntime.start();

        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.5"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.3"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.9"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.4"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.3"});

        Thread.sleep(1000);

        Assert.assertEquals("Event arrived", true, eventArrived);
        Assert.assertEquals("Number of output event value", 2, count);
        executionPlanRuntime.shutdown();
    }

    @Test
    public void testEventOutputRateLimitQuery6() throws InterruptedException {
        log.info("EventOutputRateLimit test6");

        SiddhiManager siddhiManager = new SiddhiManager();

        String executionPlan = "" +
                "@Plan:name('EventOutputRateLimitTest6') " +
                "" +
                "define stream LoginEvents (timeStamp long, ip string);" +
                "" +
                "@info(name = 'query1') " +
                "from LoginEvents " +
                "select ip " +
                "output last every 2 events " +
                "insert into uniqueIps ;";

        ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(executionPlan);

        log.info("Running : " + executionPlanRuntime.getName());

        executionPlanRuntime.addCallback("query1", new QueryCallback() {
            @Override
            public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
                EventPrinter.print(timeStamp, inEvents, removeEvents);
                if (inEvents != null) {
                    count += inEvents.length;
                    Assert.assertTrue("192.10.1.5".equals(inEvents[0].getData(0)) || "192.10.1.4".equals(inEvents[0].getData(0)));
                } else {
                    Assert.fail("Remove events emitted");
                }
                eventArrived = true;
            }

        });

        InputHandler inputHandler = executionPlanRuntime.getInputHandler("LoginEvents");

        executionPlanRuntime.start();

        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.3"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.5"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.3"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.4"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.3"});

        Thread.sleep(1000);

        Assert.assertEquals("Event arrived", true, eventArrived);
        Assert.assertEquals("Number of output event value", 2, count);
        executionPlanRuntime.shutdown();
    }

    @Test
    public void testEventOutputRateLimitQuery7() throws InterruptedException {
        log.info("EventOutputRateLimit test7");

        SiddhiManager siddhiManager = new SiddhiManager();

        String executionPlan = "" +
                "@Plan:name('EventOutputRateLimitTest7') " +
                "" +
                "define stream LoginEvents (timeStamp long, ip string);" +
                "" +
                "@info(name = 'query1') " +
                "from LoginEvents " +
                "select ip " +
                "output last every 4 events " +
                "insert into uniqueIps ;";

        ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(executionPlan);

        log.info("Running : " + executionPlanRuntime.getName());

        executionPlanRuntime.addCallback("query1", new QueryCallback() {
            @Override
            public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
                EventPrinter.print(timeStamp, inEvents, removeEvents);
                if (inEvents != null) {
                    count += inEvents.length;
                    Assert.assertTrue("192.10.1.4".equals(inEvents[0].getData(0)));
                } else {
                    Assert.fail("Remove events emitted");
                }
                eventArrived = true;
            }

        });

        InputHandler inputHandler = executionPlanRuntime.getInputHandler("LoginEvents");

        executionPlanRuntime.start();

        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.3"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.5"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.3"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.4"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.3"});

        Thread.sleep(1000);

        Assert.assertEquals("Event arrived", true, eventArrived);
        Assert.assertEquals("Number of output event value", 1, count);
        executionPlanRuntime.shutdown();
    }

    @Test
    public void testEventOutputRateLimitQuery8() throws InterruptedException {
        log.info("EventOutputRateLimit test8");

        SiddhiManager siddhiManager = new SiddhiManager();

        String executionPlan = "" +
                "@Plan:name('EventOutputRateLimitTest8') " +
                "" +
                "define stream LoginEvents (timeStamp long, ip string);" +
                "" +
                "@info(name = 'query1') " +
                "from LoginEvents " +
                "select ip " +
                "group by ip " +
                "output first every 5 events " +
                "insert into uniqueIps ;";

        ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(executionPlan);

        log.info("Running : " + executionPlanRuntime.getName());

        executionPlanRuntime.addCallback("query1", new QueryCallback() {
            @Override
            public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
                EventPrinter.print(timeStamp, inEvents, removeEvents);
                if (inEvents != null) {
                    count += inEvents.length;
                } else {
                    Assert.fail("Remove events emitted");
                }
                eventArrived = true;
            }

        });

        InputHandler inputHandler = executionPlanRuntime.getInputHandler("LoginEvents");

        executionPlanRuntime.start();

        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.5"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.5"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.3"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.9"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.4"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.4"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.4"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.30"});
        Thread.sleep(1000);

        Assert.assertEquals("Event arrived", true, eventArrived);
        Assert.assertEquals("Number of output event value", 6, count);
        executionPlanRuntime.shutdown();
    }

    @Test
    public void testEventOutputRateLimitQuery9() throws InterruptedException {
        log.info("EventOutputRateLimit test9");

        SiddhiManager siddhiManager = new SiddhiManager();

        String executionPlan = "" +
                "@Plan:name('EventOutputRateLimitTest9') " +
                "" +
                "define stream LoginEvents (timeStamp long, ip string);" +
                "" +
                "@info(name = 'query1') " +
                "from LoginEvents " +
                "select  ip " +
                "group by  ip " +
                "output last every 5 events " +
                "insert into uniqueIps ;";

        ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(executionPlan);

        log.info("Running : " + executionPlanRuntime.getName());

        executionPlanRuntime.addCallback("query1", new QueryCallback() {
            @Override
            public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
                EventPrinter.print(timeStamp, inEvents, removeEvents);
                if (inEvents != null) {
                    count += inEvents.length;
                } else {
                    Assert.fail("Remove events emitted");
                }
                eventArrived = true;
            }

        });

        InputHandler inputHandler = executionPlanRuntime.getInputHandler("LoginEvents");

        executionPlanRuntime.start();

        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.5"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.5"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.3"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.9"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.4"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.4"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.4"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.30"});
        Thread.sleep(1000);

        Assert.assertEquals("Event arrived", true, eventArrived);
        Assert.assertEquals("Number of output event value", 4, count);

        executionPlanRuntime.shutdown();
    }

}


text:
using System;
using System.Linq;
using System.Runtime.InteropServices;
using Torque6.Engine.SimObjects;
using Torque6.Engine.SimObjects.Scene;
using Torque6.Engine.Namespaces;
using Torque6.Utility;

namespace Torque6.Engine.SimObjects.Scene
{
   public unsafe class RootNode : BaseNode
   {

      public RootNode()
      {
         ObjectPtr = Sim.WrapObject(InternalUnsafeMethods.RootNodeCreateInstance());
      }

      public RootNode(uint pId) : base(pId)
      {
      }

      public RootNode(string pName) : base(pName)
      {
      }

      public RootNode(IntPtr pObjPtr) : base(pObjPtr)
      {
      }

      public RootNode(Sim.SimObjectPtr* pObjPtr) : base(pObjPtr)
      {
      }

      public RootNode(SimObject pObj) : base(pObj)
      {
      }

      #region UnsafeNativeMethods

      new internal struct InternalUnsafeMethods
      {
         [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
         private delegate IntPtr _RootNodeCreateInstance();
         private static _RootNodeCreateInstance _RootNodeCreateInstanceFunc;
         internal static IntPtr RootNodeCreateInstance()
         {
            if (_RootNodeCreateInstanceFunc == null)
            {
               _RootNodeCreateInstanceFunc =
                  (_RootNodeCreateInstance)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
                     "RootNodeCreateInstance"), typeof(_RootNodeCreateInstance));
            }

            return _RootNodeCreateInstanceFunc();
         }
      }

      #endregion

      #region Properties

      #endregion

      #region Methods

      #endregion

   }
}


text:
module TestTypes (
  IncPK(..)
, CompoundPK(..)
-- , incFromList
-- , compoundFromList
) where

import qualified Data.Aeson as JSON
import Data.Aeson ((.:))
-- import Data.Maybe (fromJust)
import Control.Applicative
import Control.Monad (mzero)

import Prelude

data IncPK = IncPK {
  incId :: Int
, incNullableStr :: Maybe String
, incStr :: String
, incInsert :: String
} deriving (Eq, Show)

instance JSON.FromJSON IncPK where
  parseJSON (JSON.Object r) = IncPK <$>
    r .: "id" <*>
    r .: "nullable_string" <*>
    r .: "non_nullable_string" <*>
    r .: "inserted_at"
  parseJSON _ = mzero

-- incFromList :: [(String, SqlValue)] -> IncPK
-- incFromList row = IncPK
--   (fromSql . fromJust $ lookup "id" row)
--   (fromSql . fromJust $ lookup "nullable_string" row)
--   (fromSql . fromJust $ lookup "non_nullable_string" row)
--   (fromSql . fromJust $ lookup "inserted_at" row)

data CompoundPK = CompoundPK {
  compoundK1 :: Int
, compoundK2 :: String
, compoundExtra :: Maybe Int
} deriving (Eq, Show)

instance JSON.FromJSON CompoundPK where
  parseJSON (JSON.Object r) = CompoundPK <$>
    r .: "k1" <*>
    r .: "k2" <*>
    r .: "extra"
  parseJSON _ = mzero

-- compoundFromList :: [(String, SqlValue)] -> CompoundPK
-- compoundFromList row = CompoundPK
--   (fromSql . fromJust $ lookup "k1" row)
--   (fromSql . fromJust $ lookup "k2" row)
--   (fromSql . fromJust $ lookup "extra" row)


text:
using System;
using System.Xml.Serialization;

namespace Aop.Api.Response
{
    /// <summary>
    /// AlipaySecurityProdFacerepoAddResponse.
    /// </summary>
    public class AlipaySecurityProdFacerepoAddResponse : AopResponse
    {
        /// <summary>
        /// 扩展信息
        /// </summary>
        [XmlElement("ext_info")]
        public string ExtInfo { get; set; }

        /// <summary>
        /// 对此次插入人脸库分组的人脸id标识
        /// </summary>
        [XmlElement("face_id")]
        public string FaceId { get; set; }
    }
}


text:
package org.apache.phoenix.execute;

import static org.apache.phoenix.query.QueryConstants.BASE_TABLE_BASE_COLUMN_COUNT;
import static org.apache.phoenix.query.QueryConstants.VALUE_COLUMN_FAMILY;
import static org.apache.phoenix.util.PhoenixRuntime.CONNECTIONLESS;
import static org.apache.phoenix.util.PhoenixRuntime.JDBC_PROTOCOL;
import static org.apache.phoenix.util.PhoenixRuntime.JDBC_PROTOCOL_SEPARATOR;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;

import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;

import org.apache.phoenix.thirdparty.com.google.common.collect.ImmutableList;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.phoenix.compile.ColumnResolver;
import org.apache.phoenix.compile.FromCompiler;
import org.apache.phoenix.compile.OrderByCompiler.OrderBy;
import org.apache.phoenix.compile.QueryPlan;
import org.apache.phoenix.compile.RowProjector;
import org.apache.phoenix.compile.SequenceManager;
import org.apache.phoenix.compile.StatementContext;
import org.apache.phoenix.compile.TupleProjectionCompiler;
import org.apache.phoenix.coprocessor.MetaDataProtocol;
import org.apache.phoenix.expression.Expression;
import org.apache.phoenix.expression.LiteralExpression;
import org.apache.phoenix.expression.ProjectedColumnExpression;
import org.apache.phoenix.iterate.ResultIterator;
import org.apache.phoenix.jdbc.PhoenixConnection;
import org.apache.phoenix.jdbc.PhoenixStatement;
import org.apache.phoenix.parse.ParseNodeFactory;
import org.apache.phoenix.parse.SelectStatement;
import org.apache.phoenix.schema.ColumnRef;
import org.apache.phoenix.schema.PColumn;
import org.apache.phoenix.schema.PColumnImpl;
import org.apache.phoenix.schema.PName;
import org.apache.phoenix.schema.PNameFactory;
import org.apache.phoenix.schema.PTable;
import org.apache.phoenix.schema.PTable.EncodedCQCounter;
import org.apache.phoenix.schema.PTable.ImmutableStorageScheme;
import org.apache.phoenix.schema.PTable.QualifierEncodingScheme;
import org.apache.phoenix.schema.PTableImpl;
import org.apache.phoenix.schema.PTableType;
import org.apache.phoenix.schema.TableRef;
import org.apache.phoenix.schema.tuple.SingleKeyValueTuple;
import org.apache.phoenix.schema.tuple.Tuple;
import org.junit.Test;

import org.apache.phoenix.thirdparty.com.google.common.collect.Lists;

public class LiteralResultIteratorPlanTest {

    private static final StatementContext CONTEXT;

    static {
        try {
            PhoenixConnection connection = DriverManager
                    .getConnection(JDBC_PROTOCOL + JDBC_PROTOCOL_SEPARATOR + CONNECTIONLESS)
                    .unwrap(PhoenixConnection.class);
            PhoenixStatement stmt = new PhoenixStatement(connection);
            ColumnResolver resolver = FromCompiler.getResolverForQuery(SelectStatement.SELECT_ONE, connection);
            CONTEXT = new StatementContext(stmt, resolver, new Scan(), new SequenceManager(stmt));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    private static final Object[][] RELATION = new Object[][] {
        {"2", 20},
        {"2", 40},
        {"5", 50},
        {"6", 60},
        {"5", 100},
        {"1", 10},
        {"3", 30},
 };
    PTable table = createProjectedTableFromLiterals(RELATION[0]).getTable();

    @Test
    public void testLiteralResultIteratorPlanWithOffset() throws SQLException {
        Object[][] expected = new Object[][] {
            {"2", 40},
            {"5", 50},
            {"6", 60},
            {"5", 100},
            {"1", 10},
            {"3", 30},
        };
        testLiteralResultIteratorPlan(expected, 1, null);
    }

    @Test
    public void testLiteralResultIteratorPlanWithLimit() throws SQLException {
        Object[][] expected = new Object[][] {
            {"2", 20},
            {"2", 40},
            {"5", 50},
            {"6", 60},
        };
        testLiteralResultIteratorPlan(expected, null, 4);
    }

    @Test
    public void testLiteralResultIteratorPlanWithLimitAndOffset() throws SQLException {
        Object[][] expected = new Object[][] {
            {"5", 50},
            {"6", 60},
            {"5", 100},
            {"1", 10},
            };
        testLiteralResultIteratorPlan(expected, 2, 4);
    }

    private void testLiteralResultIteratorPlan(Object[][] expectedResult, Integer offset, Integer limit)
            throws SQLException {

        QueryPlan plan = newLiteralResultIterationPlan(offset, limit);
        ResultIterator iter = plan.iterator();
        ImmutableBytesWritable ptr = new ImmutableBytesWritable();
        for (Object[] row : expectedResult) {
            Tuple next = iter.next();
            assertNotNull(next);
            for (int i = 0; i < row.length; i++) {
                PColumn column = table.getColumns().get(i);
                boolean eval = new ProjectedColumnExpression(column, table, column.getName().getString()).evaluate(next,
                        ptr);
                Object o = eval ? column.getDataType().toObject(ptr) : null;
                assertEquals(row[i], o);
            }
        }
        assertNull(iter.next());
    }

    private QueryPlan newLiteralResultIterationPlan(Integer offset, Integer limit) throws SQLException {
        List<Tuple> tuples = Lists.newArrayList();

        Tuple baseTuple = new SingleKeyValueTuple(KeyValue.LOWESTKEY);
        for (Object[] row : RELATION) {
            Expression[] exprs = new Expression[row.length];
            for (int i = 0; i < row.length; i++) {
                exprs[i] = LiteralExpression.newConstant(row[i]);
            }
            TupleProjector projector = new TupleProjector(exprs);
            tuples.add(projector.projectResults(baseTuple));
        }

        return new LiteralResultIterationPlan(tuples, CONTEXT, SelectStatement.SELECT_ONE, TableRef.EMPTY_TABLE_REF,
                RowProjector.EMPTY_PROJECTOR, limit, offset, OrderBy.EMPTY_ORDER_BY, null);
    }

    private TableRef createProjectedTableFromLiterals(Object[] row) {
        List<PColumn> columns = Lists.<PColumn> newArrayList();
        for (int i = 0; i < row.length; i++) {
            String name = ParseNodeFactory.createTempAlias();
            Expression expr = LiteralExpression.newConstant(row[i]);
            PName colName = PNameFactory.newName(name);
            columns.add(new PColumnImpl(PNameFactory.newName(name),
                    PNameFactory.newName(VALUE_COLUMN_FAMILY), expr.getDataType(), expr.getMaxLength(),
                    expr.getScale(), expr.isNullable(), i, expr.getSortOrder(), null, null, false, name, false, false, colName.getBytes(),
                HConstants.LATEST_TIMESTAMP));
        }
        try {
            PTable pTable = new PTableImpl.Builder()
                    .setType(PTableType.SUBQUERY)
                    .setTimeStamp(MetaDataProtocol.MIN_TABLE_TIMESTAMP)
                    .setIndexDisableTimestamp(0L)
                    .setSequenceNumber(PTable.INITIAL_SEQ_NUM)
                    .setImmutableRows(false)
                    .setDisableWAL(false)
                    .setMultiTenant(false)
                    .setStoreNulls(false)
                    .setUpdateCacheFrequency(0)
                    .setNamespaceMapped(false)
                    .setAppendOnlySchema(false)
                    .setImmutableStorageScheme(ImmutableStorageScheme.ONE_CELL_PER_COLUMN)
                    .setQualifierEncodingScheme(QualifierEncodingScheme.NON_ENCODED_QUALIFIERS)
                    .setBaseColumnCount(BASE_TABLE_BASE_COLUMN_COUNT)
                    .setEncodedCQCounter(EncodedCQCounter.NULL_COUNTER)
                    .setUseStatsForParallelization(true)
                    .setExcludedColumns(ImmutableList.of())
                    .setSchemaName(PName.EMPTY_NAME)
                    .setTableName(PName.EMPTY_NAME)
                    .setRowKeyOrderOptimizable(true)
                    .setIndexes(Collections.emptyList())
                    .setPhysicalNames(ImmutableList.of())
                    .setColumns(columns)
                    .build();
            TableRef sourceTable = new TableRef(pTable);
            List<ColumnRef> sourceColumnRefs = Lists.newArrayList();
            for (PColumn column : sourceTable.getTable().getColumns()) {
                sourceColumnRefs.add(new ColumnRef(sourceTable, column.getPosition()));
            }

            return new TableRef(TupleProjectionCompiler.createProjectedTable(sourceTable, sourceColumnRefs, false));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}


text:
package com.secucard.connect.client;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Arrays;

/**
 * Writes objects and streams to disk.
 */
public class OfflineCache extends DataStorage {
  private File directory;

  public OfflineCache(String path) {
    try {
      init(path);
    } catch (Exception e) {
      throw new ClientError("Error initializing data storage.", e);
    }
  }

  protected void init(String path) {
    directory = new File(path);
    createDirectoryIfNeeded();
  }

  private void createDirectoryIfNeeded() {
    if (!directory.exists()) {
      directory.mkdirs();
      if (!directory.exists()) {
        throw new DataStorageException("Can't create directory " + directory);
      }
    }
  }

  @Override
  public synchronized void save(String id, Object object, boolean replace) throws DataStorageException {
    if (!(object instanceof Serializable)) {
      throw new DataStorageException("Object to store must implement serializable");
    }

    createDirectoryIfNeeded();

    ObjectOutputStream out = null;
    try {
      File file = new File(directory, id);

      if (file.exists() && !replace) {
        return;
      }

      out = new ObjectOutputStream(new FileOutputStream(file));
      out.writeObject(object);
      out.flush();
    } catch (IOException e) {
      throw new DataStorageException("Error writing object \"" + id + "\" to disk.", e);
    } finally {
      if (out != null) {
        try {
          out.close();
        } catch (IOException e) {
          // ignore
        }
      }
    }
  }

  @Override
  public synchronized void save(String id, InputStream in, boolean replace) throws DataStorageException {
    throw new DataStorageException("This operation is not supported");
  }

  @Override
  public synchronized Object get(String id) {
    try {
      InputStream stream = getStream(id);
      if (stream != null) {
        try {
          return new ObjectInputStream(stream).readObject();
        } finally {
          try {
            stream.close();
          } catch (IOException e) {
            // ignore
          }
        }
      }
    } catch (IOException | ClassNotFoundException e) {
      throw new DataStorageException("Error reading object \"" + id + "\" from disk.", e);
    }
    return null;
  }

  @Override
  public synchronized InputStream getStream(String id) {
    File path = new File(directory, id);
    try {
      if (path.exists() && path.length() > 0) {
        return new FileInputStream(path);
      }
    } catch (IOException e) {
      throw new DataStorageException("Error reading stream \"" + id + "\" from disk.", e);
    }
    return null;
  }

  @Override
  public synchronized void clear(final String pattern, final Long timestampMs) {
    if (!directory.exists()) {
      return;
    }

    File[] paths = directory.listFiles(new FileFilter() {
      @Override
      public boolean accept(File pathname) {
        String fileName = pathname.getName();
        return wildCardMatch(fileName, pattern)
            && (timestampMs == null || pathname.lastModified() < timestampMs);
      }
    });

    for (File path : paths) {
      if (!path.delete()) {
        throw new DataStorageException("Error deleting  file \"" + path.toString() + "\" from disk.");
      }
    }
  }

  public synchronized int size() throws Exception {
    if (!directory.exists()) {
      return 0;
    }

    String[] files = directory.list();
    if (files == null) {
      return 0;
    }

    return files.length;
  }

  public synchronized File[] getFiles() {
    File[] files = directory.listFiles(new FileFilter() {
      @Override
      public boolean accept(File pathname) {
        return pathname.isFile();
      }
    });
    if (files != null) {
      Arrays.sort(files);
    }
    return files;
  }

  public synchronized void destroy() {
    if (!directory.exists()) {
      return;
    }

    File[] files = directory.listFiles();
    for (File file : files) {
      if (!file.delete()) {
        throw new DataStorageException("Error deleting  file \"" + file.getPath() + "\" from disk.");
      }
    }

    deleteDir(directory);
  }

  private void deleteDir(File file) {
    if (file != null && file.isDirectory() && file.list().length == 0) {

      if (!file.delete()) {
        throw new DataStorageException("Error deleting  file \"" + file.getPath() + "\" from disk.");
      }

      deleteDir(file.getParentFile());
    }
  }

  @Override
  public String toString() {
    return "OfflineCache{" +
        "directory=" + directory +
        "} " + super.toString();
  }
}


text:
import React from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import Radium from 'radium'
import { fetchHomeRecommendations, removeHomeRecommendation,
    updateHomeRecommendationUserBackgroundImage, addHomeRecommendation, topHomeRecommendation } from '../actions/homeRecommendations'
import Pagination from '../components/public/Pagination'
import HomeRecommendationsList from '../components/homeRecommendations/HomeRecommendationsList'
import AddHomeRecommendationModal from '../components/homeRecommendations/AddHomeRecommendationModal'

const perPage = 15

@Radium
export default class HomeRecommendationsPage extends React.Component {
    state = {
        modalIsOpen: false
    }

    openModal = () => {
        this.setState({modalIsOpen: true})
    }

    closeModal = () => {
        this.setState({modalIsOpen: false})
    }

    componentDidMount() {
        const { dispatch } = this.props

        dispatch(fetchHomeRecommendations(1, perPage))
    }

    selectImageFile = (homeRecommendation) => {
        this.targetHomeRecommendation = homeRecommendation

        if (this.fileInput !== null) {
            this.fileInput.click();
        }
    }

    handleInputChange = (e) => {
        const { dispatch } = this.props

        dispatch(updateHomeRecommendationUserBackgroundImage(this.targetHomeRecommendation, e.target.files[0]))
    }

    render() {
        const { dispatch, recommendations } = this.props

        return (

首页推荐管理

                    <button type="button" className="btn btn-default" onClick={this.openModal}>
                         添加推荐
                    </button>

                    <HomeRecommendationsList
                        homeRecommendations={recommendations}
                        removeHomeRecommendation={bindActionCreators(removeHomeRecommendation, dispatch)}
                        selectImageFile={this.selectImageFile}
                        topHomeRecommendation={bindActionCreators(topHomeRecommendation, dispatch)}/>

                <input type="file" accept="image/*" style={{display: "none"}} ref={(ref) => this.fileInput = ref}
                       onChange={this.handleInputChange}/>

                <AddHomeRecommendationModal
                    modalIsOpen={this.state.modalIsOpen}
                    closeModal={this.closeModal}
                    addHomeRecommendation={bindActionCreators(addHomeRecommendation, dispatch)}/>

                <Pagination
                    totalCount={this.props.totalCount}
                    currentPage={this.props.currentPage}
                    redirect={bindActionCreators((page) => fetchHomeRecommendations(page, perPage), dispatch)}
                    perPage={perPage}/>

        )
    }
}

const mapStateToProps = (state) => {
    return {
        totalCount: state.homeRecommendations.totalCount,
        currentPage: state.homeRecommendations.currentPage,
        recommendations: state.homeRecommendations.recommendations[state.homeRecommendations.currentPage] || []
    }
}

const styles = {
    homeRecommendationList: {
        marginTop: '10px'
    }
}

export default connect(mapStateToProps)(HomeRecommendationsPage)


text:
@interface ComGoogleCommonPrimitivesParseRequest : NSObject {
 @public
  NSString *rawValue_;
  jint radix_;
}

+ (ComGoogleCommonPrimitivesParseRequest *)fromStringWithNSString:(NSString *)stringValue;

@end

J2OBJC_EMPTY_STATIC_INIT(ComGoogleCommonPrimitivesParseRequest)

J2OBJC_FIELD_SETTER(ComGoogleCommonPrimitivesParseRequest, rawValue_, NSString *)

CF_EXTERN_C_BEGIN

FOUNDATION_EXPORT ComGoogleCommonPrimitivesParseRequest *ComGoogleCommonPrimitivesParseRequest_fromStringWithNSString_(NSString *stringValue);
CF_EXTERN_C_END
#endif

J2OBJC_TYPE_LITERAL_HEADER(ComGoogleCommonPrimitivesParseRequest)


text:
Transport Mapping Nachschlagetabellen

<tt>transport_maps</tt>

Dieser Parameter gibt optionale Tabellen an, die eine Domain für Mapping (transport, nexthop) enthalten. Siehe Transport mapping für Syntax Details.

In Standardeinstellung ist dieses Feature deaktiviert. Bestimmen Sie die verwendeten Datenbank-Typen.

Mögliche sensible Werte:

 <tt>dbm:/etc/postfix/transport</tt>

 <tt>hash:/etc/postfix/transport</tt>

 <tt>hash:/etc/postfix/transport, nis:transport</tt>

 <tt>hash:/etc/postfix/transport, netinfo:/transport</tt>


text:
@implementation UIColor(AFExtension)

+(UIColor *)color24WithR:(float)r G:(float)g  B:(float)b A:(float)a
{
    return[UIColor colorWithRed:(float)r/255.0 green:(float)g/255.0 blue:(float)b/255.0 alpha:a];
}

+ (UIColor *)colorWithHex:(UInt32)hex andAlpha:(CGFloat)alpha
{
    int r = (hex >> 16) & 0xFF;
    int g = (hex >> 8) & 0xFF;
    int b = (hex) & 0xFF;

    return [UIColor colorWithRed:r / 255.0f
                           green:g / 255.0f
                            blue:b / 255.0f
                           alpha:alpha];
}

+ (UIColor *)colorWithHex:(UInt32)hex
{
    return [self colorWithHex:hex andAlpha:1.0];
}

+(UIColor *)hexRGBA:(UInt32)hex
{
    return [UIColor colorWithHex:hex];
}

+(UIColor *)random
{
    return [UIColor color24WithR:(arc4random()%256) G:(arc4random()%256) B:(arc4random()%256) A:1.0];
}

- (UIColor * (^)(CGFloat))withAlpha {
    return ^id(CGFloat a){
        return  [self colorWithAlphaComponent:a];
    };
}

+ (UIColor *)fadeFromColor:(UIColor *)fromColor toColor:(UIColor *)toColor withPercentage:(CGFloat)percentage
{
    // get the RGBA values from the colours
    CGFloat fromRed, fromGreen, fromBlue, fromAlpha;
    [fromColor getRed:&fromRed green:&fromGreen blue:&fromBlue alpha:&fromAlpha];

    CGFloat toRed, toGreen, toBlue, toAlpha;
    [toColor getRed:&toRed green:&toGreen blue:&toBlue alpha:&toAlpha];

    //calculate the actual RGBA values of the fade colour
    CGFloat red = (toRed - fromRed) * percentage + fromRed;
    CGFloat green = (toGreen - fromGreen) * percentage + fromGreen;
    CGFloat blue = (toBlue - fromBlue) * percentage + fromBlue;
    CGFloat alpha = (toAlpha - fromAlpha) * percentage + fromAlpha;

    // return the fade colour
    return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}
@end


text:
jQuery(document).ready(function() {

///////////////////////////////////////////////////////////////////////////
// equal H
///////////////////////////////////////////////////////////////////////////

$(window).load(function() {

	$(function() {
		$('.equal .item').matchHeight();
		// $(".parent-map").swipe( {
  //       //Generic swipe handler for all directions
  //       swipeRight:function(event, direction, distance, duration, fingerCount, fingerData) {
  //       	var xPos = e.originalEvent.touches[0].pageX;
  //       	alert(xPos)
  //       	if(xPos < 170)
  //       	{
  //       		$( "#cd-menu-trigger" ).trigger( "click" );

  //       	}
  //       }

  //   });
	});

})

///////////////////////////////////////////////////////////////////////////
// sticky
///////////////////////////////////////////////////////////////////////////

// $(".sticky").stick_in_parent();

$('.owl-carousel').owlCarousel({
	loop:true,
	margin:0,
	nav:false,
	responsive:{
		0:{
			items:1
		}
	}
})

///////////////////////////////////////////////////////////////////////////
//  scrollTo
///////////////////////////////////////////////////////////////////////////

$('.fixed-nav, .controls,#sideMenu,header').localScroll({
	target:'body',
	duration: 1000,
	easing: 'easeInOutExpo', //(see http://easings.net/)
	offset:-99
});

// $('#mainMenu').onePageNav({
// 	currentClass: 'active',
// 	changeHash: false
// });

///////////////////////////////////////////////////////////////////////////
//  scrollUp
///////////////////////////////////////////////////////////////////////////

$.scrollUp({
    scrollName: 'scrollUp', // Element ID
    topDistance: '600', // Distance from top before showing element (px)
    topSpeed: 400, // Speed back to top (ms)
    animation: 'fade', // Fade, slide, none
    animationInSpeed: 200, // Animation in speed (ms)
    animationOutSpeed: 200, // Animation out speed (ms)
    scrollText: '<i class="fa fa-angle-up"></i>', // Text for element
    activeOverlay: false, // Set CSS color to display scrollUp active point, e.g '#00FFFF'
});

///////////////////////////////////////////////////////////////////////////
//  appear
///////////////////////////////////////////////////////////////////////////

jQuery('.appear').appear();
$(document.body).on('appear', '.appear-fadeIn', function() {
	$(this).each(function(){jQuery(this).addClass('fadeIn') });
});
$(document.body).on('appear', '.appear-bounceInRight', function() {
	$(this).each(function(){jQuery(this).addClass('bounceInRight')});
});
$(document.body).on('appear', '.appear-flip', function() {
	$(this).each(function(){jQuery(this).addClass('flip') });
});
$(document.body).on('appear', '.appear-slide', function() {
	$(this).each(function(){jQuery(this).addClass('slide') });
});
$(document.body).on('appear', '.appear-bounceInDown', function() {
	$(this).each(function(){jQuery(this).addClass('bounceInDown') });
});
$(document.body).on('appear', '.appear-bounceInLeft', function() {
	$(this).each(function(){jQuery(this).addClass('bounceInLeft') });
});
$(document.body).on('appear', '.appear-bounceIn', function() {
	$(this).each(function(){jQuery(this).addClass('bounceIn') });
});
$(document.body).on('appear', '.appear-puffIn', function() {
	$(this).each(function(){jQuery(this).addClass('puffIn') });
});
$(document.body).on('appear', '.appear-holeIn', function() {
	$(this).each(function(){jQuery(this).addClass('holeIn') });
});

$(document.body).on('appear', '.appear-fadeInUp', function() {
	$(this).each(function(){jQuery(this).addClass('fadeInUp') });
});

});	//ready


text:
AngularJS提供了几种方式将应用同来自远程服务器的信息集成在一起。

* $http
* $resource
* Restangular

### $http
$http是angularjs核心服务,用于与远程HTTP服务器通信,通过浏览器的XMLHttpRequest对象或通过jsonp

$http服务是只能接受一个参数的函数,这个参数是一个对象,包含了用来生成HTTP请求的配置内容。

$http方法返回一个promise对象,我们可以在响应返回时用 then 方法来处理回调。或者可以使用 success 和 error 回调代替。

$http 服务提供了一些顺手的快捷方法供我们使用,这些方法简化了复杂设置,只需要提供URL和HTTP方法(或者POST或PUT请求中包含的数据)即可。

快捷方法:
```
$http.get(url, [config]);
$http.head(url, [config]);
$http.post(url, data, [config]);
$http.put(url, data, [config]);
$http.delete(url, [config]);
$http.jsonp(url, [config]);
$http.patch(url, data, [config]);
```
设置对象:
```
$http({
  method : {string} ,
  url : {string} ,
  params : {Object.<string|Object>} ,
  data : {string|Object} ,
  headers : {Object} ,
  xsrfHeaderName : {string} ,
  xsrfCookieName : {string} ,
  transformRequest : {function(data, headersGetter)|Array.<function(data, headersGetter)>} ,
  transformResponse : {function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>} ,
  paramSerializer : {string|function(Object<string,string>):string} ,
  cache : {boolean|Cache} ,
  timeout : {number|Promise} ,
  withCredentials : {boolean} ,
  responseType : {string}
  });
```
响应对象:
```
$http({
  method: 'GET',
  url: '/api/users.json'
}).then (resp) {
  // 读取X-Auth-ID
  resp.headers('X-Auth-ID');
  // data (字符串或对象)
  // status (数值型)
  // headers (函数)
  // config (对象)
  // statusText (字符串)
});
```
拦截器:
拦截器的核心是服务工厂,通过向$httpProvider.interceptors数组中添加服务工厂,在$httpProvider中进行注册。
* request
* response
* requestError
* responseError

例:
```
angular.module('myApp', [])
  .factory('myInterceptor', function($q) {
      var interceptor = {
        'request': function(config) {
          // 成功的请求方法
          return config; // 或者 $q.when(config);
        },
        'response': function(response) {
          // 响应成功
          return response; // 或者 $q.when(config);
        },
        'requestError': function(rejection) {
          // 请求发生了错误,如果能从错误中恢复,可以返回一个新的请求或promise
          return response; // 或新的promise
          // 或者,可以通过返回一个rejection来阻止下一步
          // return $q.reject(rejection);
        },
        'responseError': function(rejection) {
          // 请求发生了错误,如果能从错误中恢复,可以返回一个新的响应或promise
          return rejection; // 或新的promise
          // 或者,可以通过返回一个rejection来阻止下一步
          // return $q.reject(rejection);
        }
      };
    return interceptor;
  })
  .config(function($httpProvider) {
    $httpProvider.interceptors.push('myInterceptor');
  });
```
$httpProvider
用$httpProvider改变$http服务的默认行为。
```
angular.module('myApp', [])
  .config(function($httpProvider) {
    $httpProvider.defaults.headers.common['X-Requested-By'] = 'MyAngularApp';
    // defaults.cache : {Object}
    // defaults.xsrfCookieName : {string}
    // defaults.xsrfHeaderName : {string}
    // defaults.headers : {Object}
    // defaults.headers.common
    // defaults.headers.post
    // defaults.headers.put
    // defaults.headers.patch
    // defaults.paramSerializer : {string|function(Object<string,string>):string}
  });
```


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Empleado</title>
<meta name="date" content="2015-05-12">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Logica

Class Empleado

java.lang.Object

Logica.Persona

Logica.Empleado

public class Empleado
extends Persona

Clase que define el Objeto Empleado

Field Summary

Fields inherited from class Logica.Persona

ID, Nombre

Constructor Summary

Constructors

Constructor and Description

Empleado()

Constructor Básico

Empleado(java.lang.String Codigo,
        java.lang.String Nombre,
        java.lang.String ID)

Constructor Párametrico

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

java.lang.String
getCodigo()

Metodo que obtiene y retorna el contenido del Atributo Codigo

void
setCodigo(java.lang.String Codigo)

Metodo que recibe un párametro y se le Asigna a el atributo Codigo del objeto

java.lang.String
toString()

Metodo que retorna el contenido del objeto Empleado

Methods inherited from class Logica.Persona

getID, getNombre, setID, setNombre

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

Empleado

public Empleado(java.lang.String Codigo,
                java.lang.String Nombre,
                java.lang.String ID)

Constructor Párametrico

Parameters:

Codigo -

Nombre -

ID -

Empleado

public Empleado()

Constructor Básico

Method Detail

getCodigo

public java.lang.String getCodigo()

Metodo que obtiene y retorna el contenido del Atributo Codigo

Returns:

String

setCodigo

public void setCodigo(java.lang.String Codigo)

Metodo que recibe un párametro y se le Asigna a el atributo Codigo del objeto

Parameters:

Codigo -

toString

public java.lang.String toString()

Metodo que retorna el contenido del objeto Empleado

Overrides:

toString in class Persona

Returns:

String

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method