text:
/**
 * @constructor
 * @implements {WebInspector.ViewFactory}
 */
WebInspector.AdvancedSearchController = function()
{
    this._shortcut = WebInspector.AdvancedSearchController.createShortcut();
    this._searchId = 0;

    WebInspector.settings.advancedSearchConfig = WebInspector.settings.createSetting("advancedSearchConfig", new WebInspector.SearchConfig("", true, false));

    WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.FrameNavigated, this._frameNavigated, this);
    WebInspector.inspectorView.registerViewInDrawer("search", WebInspector.UIString("Search"), this);
}

/**
 * @return {!WebInspector.KeyboardShortcut.Descriptor}
 */
WebInspector.AdvancedSearchController.createShortcut = function()
{
    if (WebInspector.isMac())
        return WebInspector.KeyboardShortcut.makeDescriptor("f", WebInspector.KeyboardShortcut.Modifiers.Meta | WebInspector.KeyboardShortcut.Modifiers.Alt);
    else
        return WebInspector.KeyboardShortcut.makeDescriptor("f", WebInspector.KeyboardShortcut.Modifiers.Ctrl | WebInspector.KeyboardShortcut.Modifiers.Shift);
}

WebInspector.AdvancedSearchController.prototype = {
    /**
     * @param {string=} id
     * @return {?WebInspector.View}
     */
    createView: function(id)
    {
        if (!this._searchView)
            this._searchView = new WebInspector.SearchView(this);
        return this._searchView;
    },

    /**
     * @param {!KeyboardEvent} event
     * @return {boolean}
     */
    handleShortcut: function(event)
    {
        if (WebInspector.KeyboardShortcut.makeKeyFromEvent(event) === this._shortcut.key) {
            if (!this._searchView || !this._searchView.isShowing() || this._searchView._search !== document.activeElement) {
                WebInspector.showPanel("sources");
                this.show();
            } else
                WebInspector.inspectorView.closeDrawer();
            event.consume(true);
            return true;
        }
        return false;
    },

    _frameNavigated: function()
    {
        this.resetSearch();
    },

    /**
     * @param {!WebInspector.SearchScope} searchScope
     */
    registerSearchScope: function(searchScope)
    {
        // FIXME: implement multiple search scopes.
        this._searchScope = searchScope;
    },

    show: function()
    {
        var selection = window.getSelection();
        var queryCandidate;
        if (selection.rangeCount)
            queryCandidate = selection.toString().replace(/\r?\n.*/, "");

        if (!this._searchView || !this._searchView.isShowing())
            WebInspector.inspectorView.showViewInDrawer("search");
        if (queryCandidate)
            this._searchView._search.value = queryCandidate;
        this._searchView.focus();

        this.startIndexing();
    },

    /**
     * @param {boolean} finished
     */
    _onIndexingFinished: function(finished)
    {
        delete this._isIndexing;
        this._searchView.indexingFinished(finished);
        if (!finished)
            delete this._pendingSearchConfig;
        if (!this._pendingSearchConfig)
            return;
        var searchConfig = this._pendingSearchConfig
        delete this._pendingSearchConfig;
        this._innerStartSearch(searchConfig);
    },

    startIndexing: function()
    {
        this._isIndexing = true;
        // FIXME: this._currentSearchScope should be initialized based on searchConfig
        this._currentSearchScope = this._searchScope;
        if (this._progressIndicator)
            this._progressIndicator.done();
        this._progressIndicator = new WebInspector.ProgressIndicator();
        this._searchView.indexingStarted(this._progressIndicator);
        this._currentSearchScope.performIndexing(this._progressIndicator, this._onIndexingFinished.bind(this));
    },

    /**
     * @param {number} searchId
     * @param {!WebInspector.FileBasedSearchResultsPane.SearchResult} searchResult
     */
    _onSearchResult: function(searchId, searchResult)
    {
        if (searchId !== this._searchId)
            return;
        this._searchView.addSearchResult(searchResult);
        if (!searchResult.searchMatches.length)
            return;
        if (!this._searchResultsPane)
            this._searchResultsPane = this._currentSearchScope.createSearchResultsPane(this._searchConfig);
        this._searchView.resultsPane = this._searchResultsPane;
        this._searchResultsPane.addSearchResult(searchResult);
    },

    /**
     * @param {number} searchId
     * @param {boolean} finished
     */
    _onSearchFinished: function(searchId, finished)
    {
        if (searchId !== this._searchId)
            return;
        if (!this._searchResultsPane)
            this._searchView.nothingFound();
        this._searchView.searchFinished(finished);
        delete this._searchConfig;
    },

    /**
     * @param {!WebInspector.SearchConfig} searchConfig
     */
    startSearch: function(searchConfig)
    {
        this.resetSearch();
        ++this._searchId;
        if (!this._isIndexing)
            this.startIndexing();
        this._pendingSearchConfig = searchConfig;
    },

    /**
     * @param {!WebInspector.SearchConfig} searchConfig
     */
    _innerStartSearch: function(searchConfig)
    {
        this._searchConfig = searchConfig;
        // FIXME: this._currentSearchScope should be initialized based on searchConfig
        this._currentSearchScope = this._searchScope;

        if (this._progressIndicator)
            this._progressIndicator.done();
        this._progressIndicator = new WebInspector.ProgressIndicator();
        this._searchView.searchStarted(this._progressIndicator);
        this._currentSearchScope.performSearch(searchConfig, this._progressIndicator, this._onSearchResult.bind(this, this._searchId), this._onSearchFinished.bind(this, this._searchId));
    },

    resetSearch: function()
    {
        this.stopSearch();

        if (this._searchResultsPane) {
            this._searchView.resetResults();
            delete this._searchResultsPane;
        }
    },

    stopSearch: function()
    {
        if (this._progressIndicator)
            this._progressIndicator.cancel();
        if (this._currentSearchScope)
            this._currentSearchScope.stopSearch();
        delete this._searchConfig;
    }
}

/**
 * @constructor
 * @extends {WebInspector.View}
 * @param {!WebInspector.AdvancedSearchController} controller
 */
WebInspector.SearchView = function(controller)
{
    WebInspector.View.call(this);

    this._controller = controller;

    this.element.className = "search-view vbox";

    this._searchPanelElement = this.element.createChild("div", "search-drawer-header");
    this._searchPanelElement.addEventListener("keydown", this._onKeyDown.bind(this), false);

    this._searchResultsElement = this.element.createChild("div");
    this._searchResultsElement.className = "search-results";

    this._search = this._searchPanelElement.createChild("input");
    this._search.placeholder = WebInspector.UIString("Search sources");
    this._search.setAttribute("type", "text");
    this._search.classList.add("search-config-search");
    this._search.setAttribute("results", "0");
    this._search.setAttribute("size", 30);

    this._ignoreCaseLabel = this._searchPanelElement.createChild("label");
    this._ignoreCaseLabel.classList.add("search-config-label");
    this._ignoreCaseCheckbox = this._ignoreCaseLabel.createChild("input");
    this._ignoreCaseCheckbox.setAttribute("type", "checkbox");
    this._ignoreCaseCheckbox.classList.add("search-config-checkbox");
    this._ignoreCaseLabel.appendChild(document.createTextNode(WebInspector.UIString("Ignore case")));

    this._regexLabel = this._searchPanelElement.createChild("label");
    this._regexLabel.classList.add("search-config-label");
    this._regexCheckbox = this._regexLabel.createChild("input");
    this._regexCheckbox.setAttribute("type", "checkbox");
    this._regexCheckbox.classList.add("search-config-checkbox");
    this._regexLabel.appendChild(document.createTextNode(WebInspector.UIString("Regular expression")));

    this._searchStatusBarElement = this.element.createChild("div", "search-status-bar-summary");
    this._searchMessageElement = this._searchStatusBarElement.createChild("span");
    this._searchResultsMessageElement = document.createElement("span");

    this._load();
}

// Number of recent search queries to store.
WebInspector.SearchView.maxQueriesCount = 20;

WebInspector.SearchView.prototype = {
    /**
     * @return {!WebInspector.SearchConfig}
     */
    get searchConfig()
    {
        return new WebInspector.SearchConfig(this._search.value, this._ignoreCaseCheckbox.checked, this._regexCheckbox.checked);
    },

    /**
     * @type {!WebInspector.SearchResultsPane}
     */
    set resultsPane(resultsPane)
    {
        this.resetResults();
        this._searchResultsElement.appendChild(resultsPane.element);
    },

    /**
     * @param {!WebInspector.ProgressIndicator} progressIndicator
     */
    searchStarted: function(progressIndicator)
    {
        this.resetResults();
        this._resetCounters();

        this._searchMessageElement.textContent = WebInspector.UIString("Searching...");
        progressIndicator.show(this._searchStatusBarElement);
        this._updateSearchResultsMessage();

        if (!this._searchingView)
            this._searchingView = new WebInspector.EmptyView(WebInspector.UIString("Searching..."));
        this._searchingView.show(this._searchResultsElement);
    },

    /**
     * @param {!WebInspector.ProgressIndicator} progressIndicator
     */
    indexingStarted: function(progressIndicator)
    {
        this._searchMessageElement.textContent = WebInspector.UIString("Indexing...");
        progressIndicator.show(this._searchStatusBarElement);
    },

    /**
     * @param {boolean} finished
     */
    indexingFinished: function(finished)
    {
        this._searchMessageElement.textContent = finished ? "" : WebInspector.UIString("Indexing interrupted.");
    },

    _updateSearchResultsMessage: function()
    {
        if (this._searchMatchesCount && this._searchResultsCount)
            this._searchResultsMessageElement.textContent = WebInspector.UIString("Found %d matches in %d files.", this._searchMatchesCount, this._nonEmptySearchResultsCount);
        else
            this._searchResultsMessageElement.textContent = "";
    },

    resetResults: function()
    {
        if (this._searchingView)
            this._searchingView.detach();
        if (this._notFoundView)
            this._notFoundView.detach();
        this._searchResultsElement.removeChildren();
    },

    _resetCounters: function()
    {
        this._searchMatchesCount = 0;
        this._searchResultsCount = 0;
        this._nonEmptySearchResultsCount = 0;
    },

    nothingFound: function()
    {
        this.resetResults();

        if (!this._notFoundView)
            this._notFoundView = new WebInspector.EmptyView(WebInspector.UIString("No matches found."));
        this._notFoundView.show(this._searchResultsElement);
        this._searchResultsMessageElement.textContent = WebInspector.UIString("No matches found.");
    },

    /**
     * @param {!WebInspector.FileBasedSearchResultsPane.SearchResult} searchResult
     */
    addSearchResult: function(searchResult)
    {
        this._searchMatchesCount += searchResult.searchMatches.length;
        this._searchResultsCount++;
        if (searchResult.searchMatches.length)
            this._nonEmptySearchResultsCount++;
        this._updateSearchResultsMessage();
    },

    /**
     * @param {boolean} finished
     */
    searchFinished: function(finished)
    {
        this._searchMessageElement.textContent = finished ? WebInspector.UIString("Search finished.") : WebInspector.UIString("Search interrupted.");
    },

    focus: function()
    {
        WebInspector.setCurrentFocusElement(this._search);
        this._search.select();
    },

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

    willHide: function()
    {
        this._controller.stopSearch();
    },

    /**
     * @param {?Event} event
     */
    _onKeyDown: function(event)
    {
        switch (event.keyCode) {
        case WebInspector.KeyboardShortcut.Keys.Enter.code:
            this._onAction();
            break;
        }
    },

    _save: function()
    {
        WebInspector.settings.advancedSearchConfig.set(this.searchConfig);
    },

    _load: function()
    {
        var searchConfig = WebInspector.settings.advancedSearchConfig.get();
        this._search.value = searchConfig.query;
        this._ignoreCaseCheckbox.checked = searchConfig.ignoreCase;
        this._regexCheckbox.checked = searchConfig.isRegex;
    },

    _onAction: function()
    {
        var searchConfig = this.searchConfig;
        if (!searchConfig.query || !searchConfig.query.length)
            return;

        this._save();
        this._controller.startSearch(searchConfig);
    },

    __proto__: WebInspector.View.prototype
}

/**
 * @constructor
 * @param {string} query
 * @param {boolean} ignoreCase
 * @param {boolean} isRegex
 */
WebInspector.SearchConfig = function(query, ignoreCase, isRegex)
{
    this.query = query;
    this.ignoreCase = ignoreCase;
    this.isRegex = isRegex;
    this._parse();
}

WebInspector.SearchConfig.prototype = {
    _parse: function()
    {
        var filePattern = "file:(([^\\\\ ]|\\\\.)+)"; // After file: prefix: any symbol except space and backslash or any symbol escaped with a backslash.
        var quotedPattern = "\"(([^\\\\\"]|\\\\.)+)\""; // Inside double quotes: any symbol except double quote and backslash or any symbol escaped with a backslash.
        var unquotedPattern = "(([^\\\\ ]|\\\\.)+)"; // any symbol except space and backslash or any symbol escaped with a backslash.

        var pattern = "(" + filePattern + ")|(" + quotedPattern + ")|(" + unquotedPattern + ")";
        var regexp = new RegExp(pattern, "g");
        var queryParts = this.query.match(regexp) || [];

        this._fileQueries = [];
        this._queries = [];

        for (var i = 0; i < queryParts.length; ++i) {
            var queryPart = queryParts[i];
            if (!queryPart)
                continue;
            if (queryPart.startsWith("file:")) {
                this._fileQueries.push(this._parseFileQuery(queryPart));
                continue;
            }
            if (queryPart.startsWith("\"")) {
                if (!queryPart.endsWith("\""))
                    continue;
                this._queries.push(this._parseQuotedQuery(queryPart));
                continue;
            }
            this._queries.push(this._parseUnquotedQuery(queryPart));
        }
    },

    fileQueries: function()
    {
        return this._fileQueries;
    },

    queries: function()
    {
        return this._queries;
    },

    _parseUnquotedQuery: function(query)
    {
        return query.replace(/\\(.)/g, "$1");
    },

    _parseQuotedQuery: function(query)
    {
        return query.substring(1, query.length - 1).replace(/\\(.)/g, "$1");
    },

    _parseFileQuery: function(query)
    {
        query = query.substr("file:".length);
        var result = "";
        for (var i = 0; i < query.length; ++i) {
            var char = query[i];
            if (char === "*") {
                result += ".*";
            } else if (char === "\\") {
                ++i;
                var nextChar = query[i];
                if (nextChar === " ")
                    result += " ";
            } else {
                if (String.regexSpecialCharacters().indexOf(query.charAt(i)) !== -1)
                    result += "\\";
                result += query.charAt(i);
            }
        }
        return result;
    }
}

/**
 * @interface
 */
WebInspector.SearchScope = function()
{
}

WebInspector.SearchScope.prototype = {
    /**
     * @param {!WebInspector.SearchConfig} searchConfig
     * @param {!WebInspector.Progress} progress
     * @param {function(!WebInspector.FileBasedSearchResultsPane.SearchResult)} searchResultCallback
     * @param {function(boolean)} searchFinishedCallback
     */
    performSearch: function(searchConfig, progress, searchResultCallback, searchFinishedCallback) { },

    stopSearch: function() { },

    /**
     * @param {!WebInspector.SearchConfig} searchConfig
     * @return {!WebInspector.SearchResultsPane}
     */
    createSearchResultsPane: function(searchConfig) { }
}

/**
 * @constructor
 * @param {!WebInspector.SearchConfig} searchConfig
 */
WebInspector.SearchResultsPane = function(searchConfig)
{
    this._searchConfig = searchConfig;
    this.element = document.createElement("div");
}

WebInspector.SearchResultsPane.prototype = {
    /**
     * @return {!WebInspector.SearchConfig}
     */
    get searchConfig()
    {
        return this._searchConfig;
    },

    /**
     * @param {!WebInspector.FileBasedSearchResultsPane.SearchResult} searchResult
     */
    addSearchResult: function(searchResult) { }
}

/**
 * @constructor
 * @extends {WebInspector.SearchResultsPane}
 * @param {!WebInspector.SearchConfig} searchConfig
 */
WebInspector.FileBasedSearchResultsPane = function(searchConfig)
{
    WebInspector.SearchResultsPane.call(this, searchConfig);

    this._searchResults = [];

    this.element.id = "search-results-pane-file-based";

    this._treeOutlineElement = document.createElement("ol");
    this._treeOutlineElement.className = "search-results-outline-disclosure";
    this.element.appendChild(this._treeOutlineElement);
    this._treeOutline = new TreeOutline(this._treeOutlineElement);

    this._matchesExpandedCount = 0;
}

WebInspector.FileBasedSearchResultsPane.matchesExpandedByDefaultCount = 20;
WebInspector.FileBasedSearchResultsPane.fileMatchesShownAtOnce = 20;

WebInspector.FileBasedSearchResultsPane.prototype = {
    /**
     * @param {!WebInspector.UISourceCode} uiSourceCode
     * @param {number} lineNumber
     * @param {number} columnNumber
     * @return {!Element}
     */
    _createAnchor: function(uiSourceCode, lineNumber, columnNumber)
    {
        var anchor = document.createElement("a");
        anchor.preferredPanel = "sources";
        anchor.href = sanitizeHref(uiSourceCode.originURL());
        anchor.uiSourceCode = uiSourceCode;
        anchor.lineNumber = lineNumber;
        return anchor;
    },

    /**
     * @param {!WebInspector.FileBasedSearchResultsPane.SearchResult} searchResult
     */
    addSearchResult: function(searchResult)
    {
        this._searchResults.push(searchResult);
        var uiSourceCode = searchResult.uiSourceCode;
        if (!uiSourceCode)
            return;
        var searchMatches = searchResult.searchMatches;

        var fileTreeElement = this._addFileTreeElement(uiSourceCode.fullDisplayName(), searchMatches.length, this._searchResults.length - 1);
    },

    /**
     * @param {!WebInspector.FileBasedSearchResultsPane.SearchResult} searchResult
     * @param {!TreeElement} fileTreeElement
     */
    _fileTreeElementExpanded: function(searchResult, fileTreeElement)
    {
        if (fileTreeElement._initialized)
            return;

        var toIndex = Math.min(searchResult.searchMatches.length, WebInspector.FileBasedSearchResultsPane.fileMatchesShownAtOnce);
        if (toIndex < searchResult.searchMatches.length) {
            this._appendSearchMatches(fileTreeElement, searchResult, 0, toIndex - 1);
            this._appendShowMoreMatchesElement(fileTreeElement, searchResult, toIndex - 1);
        } else
            this._appendSearchMatches(fileTreeElement, searchResult, 0, toIndex);

        fileTreeElement._initialized = true;
    },

    /**
     * @param {!TreeElement} fileTreeElement
     * @param {!WebInspector.FileBasedSearchResultsPane.SearchResult} searchResult
     * @param {number} fromIndex
     * @param {number} toIndex
     */
    _appendSearchMatches: function(fileTreeElement, searchResult, fromIndex, toIndex)
    {
        var uiSourceCode = searchResult.uiSourceCode;
        var searchMatches = searchResult.searchMatches;

        var queries = this._searchConfig.queries();
        var regexes = [];
        for (var i = 0; i < queries.length; ++i)
            regexes.push(createSearchRegex(queries[i], !this._searchConfig.ignoreCase, this._searchConfig.isRegex));

        for (var i = fromIndex; i < toIndex; ++i) {
            var lineNumber = searchMatches[i].lineNumber;
            var lineContent = searchMatches[i].lineContent;
            var matchRanges = [];
            for (var j = 0; j < regexes.length; ++j)
                matchRanges = matchRanges.concat(this._regexMatchRanges(lineContent, regexes[j]));

            var anchor = this._createAnchor(uiSourceCode, lineNumber, matchRanges[0].offset);

            var numberString = numberToStringWithSpacesPadding(lineNumber + 1, 4);
            var lineNumberSpan = document.createElement("span");
            lineNumberSpan.classList.add("search-match-line-number");
            lineNumberSpan.textContent = numberString;
            anchor.appendChild(lineNumberSpan);

            var contentSpan = this._createContentSpan(lineContent, matchRanges);
            anchor.appendChild(contentSpan);

            var searchMatchElement = new TreeElement("");
            searchMatchElement.selectable = false;
            fileTreeElement.appendChild(searchMatchElement);
            searchMatchElement.listItemElement.className = "search-match source-code";
            searchMatchElement.listItemElement.appendChild(anchor);
        }
    },

    /**
     * @param {!TreeElement} fileTreeElement
     * @param {!WebInspector.FileBasedSearchResultsPane.SearchResult} searchResult
     * @param {number} startMatchIndex
     */
    _appendShowMoreMatchesElement: function(fileTreeElement, searchResult, startMatchIndex)
    {
        var matchesLeftCount = searchResult.searchMatches.length - startMatchIndex;
        var showMoreMatchesText = WebInspector.UIString("Show all matches (%d more).", matchesLeftCount);
        var showMoreMatchesElement = new TreeElement(showMoreMatchesText);
        fileTreeElement.appendChild(showMoreMatchesElement);
        showMoreMatchesElement.listItemElement.classList.add("show-more-matches");
        showMoreMatchesElement.onselect = this._showMoreMatchesElementSelected.bind(this, searchResult, startMatchIndex, showMoreMatchesElement);
    },

    /**
     * @param {!WebInspector.FileBasedSearchResultsPane.SearchResult} searchResult
     * @param {number} startMatchIndex
     * @param {!TreeElement} showMoreMatchesElement
     * @return {boolean}
     */
    _showMoreMatchesElementSelected: function(searchResult, startMatchIndex, showMoreMatchesElement)
    {
        var fileTreeElement = showMoreMatchesElement.parent;
        fileTreeElement.removeChild(showMoreMatchesElement);
        this._appendSearchMatches(fileTreeElement, searchResult, startMatchIndex, searchResult.searchMatches.length);
        return false;
    },

    /**
     * @param {string} fileName
     * @param {number} searchMatchesCount
     * @param {number} searchResultIndex
     */
    _addFileTreeElement: function(fileName, searchMatchesCount, searchResultIndex)
    {
        var fileTreeElement = new TreeElement("", null, true);
        fileTreeElement.toggleOnClick = true;
        fileTreeElement.selectable = false;

        this._treeOutline.appendChild(fileTreeElement);
        fileTreeElement.listItemElement.classList.add("search-result");

        var fileNameSpan = document.createElement("span");
        fileNameSpan.className = "search-result-file-name";
        fileNameSpan.textContent = fileName;
        fileTreeElement.listItemElement.appendChild(fileNameSpan);

        var matchesCountSpan = document.createElement("span");
        matchesCountSpan.className = "search-result-matches-count";
        if (searchMatchesCount === 1)
            matchesCountSpan.textContent = WebInspector.UIString("(%d match)", searchMatchesCount);
        else
            matchesCountSpan.textContent = WebInspector.UIString("(%d matches)", searchMatchesCount);

        fileTreeElement.listItemElement.appendChild(matchesCountSpan);

        var searchResult = this._searchResults[searchResultIndex];
        fileTreeElement.onexpand = this._fileTreeElementExpanded.bind(this, searchResult, fileTreeElement);

        // Expand until at least certain amount of matches is expanded.
        if (this._matchesExpandedCount < WebInspector.FileBasedSearchResultsPane.matchesExpandedByDefaultCount)
            fileTreeElement.expand();
        this._matchesExpandedCount += searchResult.searchMatches.length;

        return fileTreeElement;
    },

    /**
     * @param {string} lineContent
     * @param {!RegExp} regex
     * @return {!Array.<!WebInspector.SourceRange>}
     */
    _regexMatchRanges: function(lineContent, regex)
    {
        regex.lastIndex = 0;
        var match;
        var offset = 0;
        var matchRanges = [];
        while ((regex.lastIndex < lineContent.length) && (match = regex.exec(lineContent)))
            matchRanges.push(new WebInspector.SourceRange(match.index, match[0].length));

        return matchRanges;
    },

    /**
     * @param {string} lineContent
     * @param {!Array.<!WebInspector.SourceRange>} matchRanges
     */
    _createContentSpan: function(lineContent, matchRanges)
    {
        var contentSpan = document.createElement("span");
        contentSpan.className = "search-match-content";
        contentSpan.textContent = lineContent;
        WebInspector.highlightRangesWithStyleClass(contentSpan, matchRanges, "highlighted-match");
        return contentSpan;
    },

    __proto__: WebInspector.SearchResultsPane.prototype
}

/**
 * @constructor
 * @param {!WebInspector.UISourceCode} uiSourceCode
 * @param {!Array.<!Object>} searchMatches
 */
WebInspector.FileBasedSearchResultsPane.SearchResult = function(uiSourceCode, searchMatches) {
    this.uiSourceCode = uiSourceCode;
    this.searchMatches = searchMatches;
}

/**
 * @type {!WebInspector.AdvancedSearchController}
 */
WebInspector.advancedSearchController;


text:
import controllers.mediator.Representations
import core.HubModule
import java.io.File
import models.OrganizationConfiguration
import org.apache.commons.io.FileUtils
import play.api.test._
import play.api.test.Helpers._
import plugins.MediatorPlugin
import test.Specs2TestContext
import util.OrganizationConfigurationHandler

/**
 *
 * @author Manuel Bernhardt <bernhardt.manuel@gmail.com>
 */
class RepresentationSpec extends Specs2TestContext {

  "The representation controller" should {

    val representationController = new Representations()(HubModule)

    "find a resource on disk" in new WithApplication {

      implicit val configuration = OrganizationConfigurationHandler.getByOrgId("delving")

      val p = new File(MediatorPlugin.pluginConfiguration.archiveDirectory, "delving/testCollection")
      p.mkdirs()
      val f = new File(p, "testIdentifier.jpg")
      f.createNewFile()

      representationController.findResourceFile("delving", "testCollection", "testIdentifier") should equalTo(Some(f))

      FileUtils.deleteQuietly(p)
    }

    "render a resource" in {
      val here = new File("modules/mediator/test/resources")
      withTestConfig(Map("configurations.delving.plugin.mediator.archiveDirectory" -> here.getAbsolutePath)) { implicit configuration: OrganizationConfiguration =>

        val request = representationController.representation("image", "delving", "testSpec", "logo")(FakeRequest())

        status(request) must equalTo(OK)
      }
    }

    val here = new File("modules/mediator/test/resources")
    val accessKeyConfig = Map(
      "configurations.delving.plugin.mediator.archiveDirectory" -> here.getAbsolutePath,
      "configurations.delving.plugin.mediator.sourceImageRepresentationAccessKey" -> "foobar"
    )

    "refuse to render a protected resources without accessKey" in {
      withTestConfig(accessKeyConfig) { implicit configuration: OrganizationConfiguration =>
        val request = representationController.representation("image", "delving", "testSpec", "logo")(FakeRequest())
        status(request) must equalTo(UNAUTHORIZED)
      }
    }

    "refuse to render a protected resources given a wrong accessKey" in {
      withTestConfig(accessKeyConfig) { implicit configuration: OrganizationConfiguration =>
        val request = representationController.representation("image", "delving", "testSpec", "logo", Some("barfoo"))(FakeRequest())
        status(request) must equalTo(UNAUTHORIZED)
      }
    }

    "render a protected resource given the correct accessKey" in {
      withTestConfig(accessKeyConfig) { implicit configuration: OrganizationConfiguration =>
        val request = representationController.representation("image", "delving", "testSpec", "logo", Some("foobar"))(FakeRequest())
        status(request) must equalTo(OK)
      }
    }
  }

}

redpajama_set_name: RedPajamaGithub


text:
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import Event from "../Core/Event.js";
import CompositeProperty from "./CompositeProperty.js";
import Property from "./Property.js";

/**
 * A {@link CompositeProperty} which is also a {@link MaterialProperty}.
 *
 * @alias CompositeMaterialProperty
 * @constructor
 */
function CompositeMaterialProperty() {
  this._definitionChanged = new Event();
  this._composite = new CompositeProperty();
  this._composite.definitionChanged.addEventListener(
    CompositeMaterialProperty.prototype._raiseDefinitionChanged,
    this
  );
}

Object.defineProperties(CompositeMaterialProperty.prototype, {
  /**
   * Gets a value indicating if this property is constant.  A property is considered
   * constant if getValue always returns the same result for the current definition.
   * @memberof CompositeMaterialProperty.prototype
   *
   * @type {Boolean}
   * @readonly
   */
  isConstant: {
    get: function () {
      return this._composite.isConstant;
    },
  },
  /**
   * Gets the event that is raised whenever the definition of this property changes.
   * The definition is changed whenever setValue is called with data different
   * than the current value.
   * @memberof CompositeMaterialProperty.prototype
   *
   * @type {Event}
   * @readonly
   */
  definitionChanged: {
    get: function () {
      return this._definitionChanged;
    },
  },
  /**
   * Gets the interval collection.
   * @memberof CompositeMaterialProperty.prototype
   *
   * @type {TimeIntervalCollection}
   */
  intervals: {
    get: function () {
      return this._composite._intervals;
    },
  },
});

/**
 * Gets the {@link Material} type at the provided time.
 *
 * @param {JulianDate} time The time for which to retrieve the type.
 * @returns {String} The type of material.
 */
CompositeMaterialProperty.prototype.getType = function (time) {
  //>>includeStart('debug', pragmas.debug);
  if (!defined(time)) {
    throw new DeveloperError("time is required");
  }
  //>>includeEnd('debug');

  const innerProperty = this._composite._intervals.findDataForIntervalContainingDate(
    time
  );
  if (defined(innerProperty)) {
    return innerProperty.getType(time);
  }
  return undefined;
};

/**
 * Gets the value of the property at the provided time.
 *
 * @param {JulianDate} time The time for which to retrieve the value.
 * @param {Object} [result] The object to store the value into, if omitted, a new instance is created and returned.
 * @returns {Object} The modified result parameter or a new instance if the result parameter was not supplied.
 */
CompositeMaterialProperty.prototype.getValue = function (time, result) {
  //>>includeStart('debug', pragmas.debug);
  if (!defined(time)) {
    throw new DeveloperError("time is required");
  }
  //>>includeEnd('debug');

  const innerProperty = this._composite._intervals.findDataForIntervalContainingDate(
    time
  );
  if (defined(innerProperty)) {
    return innerProperty.getValue(time, result);
  }
  return undefined;
};

/**
 * Compares this property to the provided property and returns
 * true if they are equal, false otherwise.
 *
 * @param {Property} [other] The other property.
 * @returns {Boolean} true if left and right are equal, false otherwise.
 */
CompositeMaterialProperty.prototype.equals = function (other) {
  return (
    this === other || //
    (other instanceof CompositeMaterialProperty && //
      this._composite.equals(other._composite, Property.equals))
  );
};

/**
 * @private
 */
CompositeMaterialProperty.prototype._raiseDefinitionChanged = function () {
  this._definitionChanged.raiseEvent(this);
};
export default CompositeMaterialProperty;


text:
package org.ebayopensource.turmeric.runtime.tests.common.cachepolicy;

import static org.junit.Assert.*;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.ebayopensource.turmeric.runtime.binding.schema.DataElementSchema;
import org.ebayopensource.turmeric.runtime.common.cachepolicy.CacheContext;
import org.ebayopensource.turmeric.runtime.common.cachepolicy.CacheKey;
import org.ebayopensource.turmeric.runtime.common.cachepolicy.CachePolicyDesc;
import org.ebayopensource.turmeric.runtime.common.cachepolicy.CachePolicyHolder;
import org.ebayopensource.turmeric.runtime.common.cachepolicy.OperationCachePolicy;
import org.ebayopensource.turmeric.runtime.common.exceptions.ServiceCreationException;
import org.ebayopensource.turmeric.runtime.common.impl.internal.service.ServiceOperationParamDescImpl;
import org.ebayopensource.turmeric.runtime.common.impl.utils.ParseUtils;
import org.ebayopensource.turmeric.runtime.common.service.ServiceOperationParamDesc;
import org.ebayopensource.turmeric.runtime.common.types.SOAConstants;
import org.ebayopensource.turmeric.runtime.sif.impl.internal.config.ClientConfigManager;
import org.ebayopensource.turmeric.runtime.sif.impl.internal.pipeline.ClientMessageProcessor;
import org.ebayopensource.turmeric.runtime.sif.impl.internal.service.ClientServiceDesc;
import org.ebayopensource.turmeric.runtime.sif.impl.internal.service.ClientServiceDescFactory;
import org.ebayopensource.turmeric.runtime.spf.impl.internal.config.ServiceConfigManager;
import org.ebayopensource.turmeric.runtime.spf.impl.internal.pipeline.ServerMessageProcessor;
import org.ebayopensource.turmeric.runtime.spf.impl.internal.service.ServerServiceDesc;
import org.ebayopensource.turmeric.runtime.spf.impl.internal.service.ServerServiceDescFactory;
import org.ebayopensource.turmeric.runtime.tests.common.AbstractTurmericTestCase;
import org.junit.Test;
import org.junit.AfterClass;

public class CachePolicyTest extends AbstractTurmericTestCase {
	static {
		System.setProperty(ParseUtils.SYS_PROP_CONFIG_SCHEMA_CHECK, "ERROR");
	}

    @AfterClass
    public static void setPropertyToNone() throws Exception {
		System.setProperty(ParseUtils.SYS_PROP_CONFIG_SCHEMA_CHECK, "NONE");
	}

	@SuppressWarnings("rawtypes")
	private  List<Class> getRootClasses1() {
		List<Class> list = new ArrayList<Class>();
		list.add(GetVersionTestRequest.class);
		return list;
	}

	@SuppressWarnings("rawtypes")
	private  List<Class> getRootClasses2() {
		List<Class> list = new ArrayList<Class>();
		list.add(GetVersion2TestRequest.class);
		return list;
	}

	private  List<DataElementSchema> getRootElement1() {
		List<DataElementSchema> list = new ArrayList<DataElementSchema>();

		return list;
	}

	private  Map<String, ServiceOperationParamDesc> createOpDescMap1() throws ServiceCreationException {
		Map<String, ServiceOperationParamDesc> opMap = new HashMap<String, ServiceOperationParamDesc>();
		ServiceOperationParamDescImpl operationParamDesc = null;
		operationParamDesc = new ServiceOperationParamDescImpl(getRootClasses1(), getRootElement1(), null, false);
		opMap.put("getVersion", operationParamDesc);
		return opMap;
	}

	private  Map<String, ServiceOperationParamDesc> createOpDescMap2() {
		Map<String, ServiceOperationParamDesc> opMap = new HashMap<String, ServiceOperationParamDesc>();
		ServiceOperationParamDescImpl operationParamDesc = null;
		try {
			operationParamDesc =
				new ServiceOperationParamDescImpl(getRootClasses1(), getRootElement1(), null, false);
		} catch (ServiceCreationException e) {
		}
		opMap.put("getVersion", operationParamDesc);
		try {
			operationParamDesc =
				new ServiceOperationParamDescImpl(getRootClasses2(), getRootElement1(), null, false);
		} catch (ServiceCreationException e) {

		}
		opMap.put("echo", operationParamDesc);

		return opMap;
	}

	@Test
	public void testCachePlcyHolder_1op_success() throws Exception {
		String xmlbuf = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
		"<serviceCachePolicy xmlns=\"http://www.ebayopensource.org/turmeric/common/config\" name=\"test1\"> " +
			"<operationCachePolicy name=\"getVersion\">" +
				"<TTL>50</TTL>" +
				"<keyExpressionSet>" +
					"<keyExpression>version</keyExpression>" +
					"<keyExpression>flag</keyExpression>" +
				"</keyExpressionSet>" +
			"</operationCachePolicy>" +
			"</serviceCachePolicy>";

		Map<String, ServiceOperationParamDesc> opMap = createOpDescMap1();

		ByteArrayInputStream stream = new ByteArrayInputStream(xmlbuf.getBytes());;

		CachePolicyHolder holder = CachePolicyHolder.loadCachePolicy(stream, "blha", SOAConstants.CACHE_POLICY_SCHEMA);

		assertNotNull("CachePolicyHolder [blha]", holder);
		assertEquals("test1", holder.getServiceName());
		assertEquals("holder.OperationsCachePolicies().size()", 1, holder.getOperationCachePolicies().size());
		OperationCachePolicy operationCachePolicy = holder.getOperationCachePolicies().get("getVersion");
		assertNotNull("OperationCachePolicy", operationCachePolicy);
		assertEquals("OperationCachePolicy.TTL", 50L, operationCachePolicy.getTTL());
		assertEquals("OperationCachePolicy.keyExpressions.size",2,operationCachePolicy.getKeyExpressions().size());
		assertTrue("OperationCachePolicy.keyExpressions[].contains('version')",operationCachePolicy.getKeyExpressions().contains("version"));
		assertTrue("OperationCachePolicy.keyExpressions[].contains('flag')",operationCachePolicy.getKeyExpressions().contains("flag"));

		CachePolicyDesc desc = CachePolicyDesc.create(holder, opMap);

		GetVersionTestRequest testRequest = new GetVersionTestRequest();
		testRequest.version = "1.0";
		testRequest.flag = Boolean.FALSE;

		CacheContext context = new CacheContext().setOpName("getVersion").setRequest(testRequest);
		CacheKey cacheKey = desc.generateCacheKey(context);
		assertNotNull("Generated Cache Key (from context)", cacheKey);

		CacheKey key = CacheKey.createCacheKey(context.getOpName());
		key.add("version", new String("1.0"));
		key.add("flag", Boolean.FALSE);

		assertEquals("Created Cache Key", cacheKey, key);
	}

	@Test
	public void testCachePlcyHolder_2op_success() throws Exception {
		String xmlbuf = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
		"<serviceCachePolicy xmlns=\"http://www.ebayopensource.org/turmeric/common/config\" name=\"test1\"> " +
			"<operationCachePolicy name=\"getVersion\">" +
				"<TTL>50</TTL>" +
				"<keyExpressionSet>" +
					"<keyExpression>version</keyExpression>" +
					"<keyExpression>flag</keyExpression>" +
				"</keyExpressionSet>" +
			"</operationCachePolicy>" +
			"<operationCachePolicy name=\"echo\">" +
			"<TTL>500</TTL>" +
			"<keyExpressionSet>" +
				"<keyExpression>timestamp</keyExpression>" +
				"<keyExpression>count</keyExpression>" +
			"</keyExpressionSet>" +
		"</operationCachePolicy>" +
			"</serviceCachePolicy>";

		Map<String, ServiceOperationParamDesc> opMap = createOpDescMap2();

		ByteArrayInputStream stream = new ByteArrayInputStream(xmlbuf.getBytes());;

		// TestCacheProvider test = new TestCacheProvider();
		CachePolicyHolder holder = null;

		holder = CachePolicyHolder.loadCachePolicy(stream, "blha", SOAConstants.CACHE_POLICY_SCHEMA);

		assertNotNull(holder);
		assertEquals("test1", holder.getServiceName());
		assertEquals(2, holder.getOperationCachePolicies().size());
		OperationCachePolicy operationCachePolicy = holder.getOperationCachePolicies().get("getVersion");
		assertNotNull(operationCachePolicy);
		assertEquals(50L, operationCachePolicy.getTTL());
		assertEquals(2,operationCachePolicy.getKeyExpressions().size());
		assertTrue(operationCachePolicy.getKeyExpressions().contains("version"));
		assertTrue(operationCachePolicy.getKeyExpressions().contains("flag"));

		operationCachePolicy = holder.getOperationCachePolicies().get("echo");
		assertNotNull(operationCachePolicy);
		assertEquals(500L, operationCachePolicy.getTTL());
		assertEquals(2,operationCachePolicy.getKeyExpressions().size());
		assertTrue(operationCachePolicy.getKeyExpressions().contains("timestamp"));
		assertTrue(operationCachePolicy.getKeyExpressions().contains("count"));

		CachePolicyDesc desc = CachePolicyDesc.create(holder, opMap);

		GetVersionTestRequest testRequest = new GetVersionTestRequest();
		testRequest.version = "1.0";
		testRequest.flag = Boolean.FALSE;

		CacheContext context = new CacheContext().setOpName("getVersion").setRequest(testRequest);
		CacheKey cacheKey = desc.generateCacheKey(context);
		assertNotNull(cacheKey);

		CacheKey key = CacheKey.createCacheKey(context.getOpName());
		key.add("version", new String("1.0"));
		key.add("flag", Boolean.FALSE);

		assertEquals(cacheKey,key);

		GetVersion2TestRequest testRequest2 = new GetVersion2TestRequest();
		testRequest2.timestamp = new Date(1000L);
		testRequest2.count = 100;

		CacheContext context2 = new CacheContext().setOpName("echo").setRequest(testRequest2);
		CacheKey cacheKey2 = desc.generateCacheKey(context2);
		assertNotNull(cacheKey2);

		CacheKey key2 = CacheKey.createCacheKey(context2.getOpName());
		key2.add("timestamp", new Date(1000L));
		key2.add("count", Integer.valueOf(100));

		assertTrue(cacheKey2.equals(key2));

	}

	@Test
	public void cachePolicy_validation_Success() throws Exception {
		ServiceConfigManager configManager = ServiceConfigManager.getInstance();
		configManager.setConfigTestCase("configtest5", "configtest5");
		ServerMessageProcessor.getInstance();
		ServerServiceDesc serviceDesc = ServerServiceDescFactory.getInstance().getServiceDesc("cachepolicy1");
		assertNotNull(serviceDesc.getCachePolicyDesc());
	}

	@Test(expected=ServiceCreationException.class)
	public void cachePolicy_invalidKey_NegativeTest() throws Exception {
		ServiceConfigManager configManager = ServiceConfigManager.getInstance();

		configManager.setConfigTestCase("configtest5", "configtest5");
		ServerMessageProcessor.getInstance();
		ServerServiceDescFactory.getInstance().getServiceDesc("cachepolicy2");
	}

	@Test(expected=ServiceCreationException.class)
	public void cachePolicy_InvalidLeafTypeKey_NegativeTest() throws Exception {
		ServiceConfigManager configManager = ServiceConfigManager.getInstance();
		configManager.setConfigTestCase("configtest5", "configtest5");
		ServerMessageProcessor.getInstance();
		ServerServiceDescFactory.getInstance().getServiceDesc("cachepolicy3");
		fail("Exception expected");
	}

	@Test
	public void cachePolicy_ClientServiceDesc_Success() throws Exception {

		ClientConfigManager configManager = ClientConfigManager.getInstance();
		configManager.setConfigTestCase("configtest5", "configtest5");
		ServiceConfigManager.getInstance().setConfigTestCase("configtest5", "configtest5");
		ServerMessageProcessor.getInstance();
		ClientMessageProcessor.getInstance();
		ClientServiceDesc serviceDesc = ClientServiceDescFactory.getInstance().getServiceDesc("cachepolicy1", "cachepolicy1");
		assertTrue(serviceDesc.getCacheProviderClass().getClass().equals(TestCacheProvider.class));
	}
}


text:
BASEDIR=`dirname $0`/../..
DURATION="100 ms"
ERROR_MATCH="Error: mismatch"

. $BASEDIR/support/sh2ju++.sh

cd $BASEDIR/verification/sim_model
export NO_COLOR_OUTPUT=y

juLogSuiteOpen "seq_test"

if [ ! $SVSEED ] ; then
	SVSEED=random
fi

if test $# -gt 0 ; then

  XPARAM="+define+PROGRAM_LENGTH=$1 +define+OPT_BCACHE=$4"

  if test $2 -gt 0 ; then
    XPARAM= "+define+USE_CACHE $XPARAM"
  fi

  if test $3 -gt 0 ; then
    XPARAM="+define+OPT_DMEM_BUS $XPARAM"
  fi

  juLog -name="clean-$1" make clean
  juLog -name="build-$1" make VLOG_XPARAM=$XPARAM
  juLog -name="seq-$1" -error="$ERROR_MATCH" vsim -c -L lib/DW -voptargs="+acc" -novopt -sv_seed $SVSEED work.Sequence_test -do "run $DURATION ; exit -f"
else
  for i in 1 2 4 8 16 32 ; do
    juLog -name="clean-$i" make clean
    juLog -name="build-$i" make VLOG_XPARAM="+define+PROGRAM_LENGTH=$i"
    juLog -name="seq-$i" -error="$ERROR_MATCH" vsim -c -L lib/DW -voptargs="+acc" -novopt -sv_seed $SVSEED work.Sequence_test -do "run $DURATION ; exit -f"
  done
fi

juLogSuiteClose


text:
var temp;
var i = 1;

//Function for button title
function button_style(temp) {
	switch(temp){
		case 'Point':
		case 'MultiPoint':{
			while(i == 1){
				var buttonlayer = document.createElement('button');
					buttonlayer.setAttribute('class', 'layers');
					buttonlayer.innerHTML = 'Point';
					console.log(temp);

				var div = document.getElementsByTagName('div')[0];
					div.appendChild(buttonlayer);
					buttonlayer.addEventListener("click", onClick);

				function onClick(){
				 if (temp == 'Point' || temp == 'MultiPoint' )
					document.getElementById("myPoint").classList.toggle("show");
					}
				i++;
					}
				break;
			};
		case 'LineString':
		case 'MultiLineString': {
			while(i == 1){
				var buttonlayer = document.createElement('button');
					buttonlayer.setAttribute('class', 'layers');
					buttonlayer.innerHTML = 'Line';

				var div = document.getElementsByTagName('div')[0];
					div.appendChild(buttonlayer);
					buttonlayer.addEventListener("click", onClick);
				function onClick(){
						if ( temp == 'LineString' || temp == 'MultiLineString')
							document.getElementById("myLine").classList.toggle("show");
						else
							alert ("add a GeoJSON or GML");
						}
					i++;
					}
				break;
			};
		case 'Polygon':
		case 'MultiPolygon':{
			while(i == 1){
				var buttonlayer = document.createElement('button');
					buttonlayer.setAttribute('class', 'layers');
					buttonlayer.innerHTML = 'Polygon';

				var div = document.getElementsByTagName('div')[0];
					div.appendChild(buttonlayer);
					buttonlayer.addEventListener("click", onClick);

					function onClick(){
					if ( temp == 'MultiPolygon' || temp == 'Polygon' )
						document.getElementById("myPolygon").classList.toggle("show");
					else
						alert ("add a GeoJSON or GML");
						}
					i++;
					}
				break;
			};
		}

}

//Default Style => give the files a default style
	var defaultStyle = {
			'Point': new ol.style.Style({
				image: new ol.style.Circle({
				fill: new ol.style.Fill({
					color: 'rgba(255,255,0,0.5)'
						}),
				radius: 5,
				stroke: new ol.style.Stroke({
					color: '#ff0',
					width: 1
						})
					})
				}),
			'LineString': new ol.style.Style({
				stroke: new ol.style.Stroke({
				color: '#f00',
				width: 3
					})
				}),
			'Polygon': new ol.style.Style({
				fill: new ol.style.Fill({
				color: 'rgba(0,255,255,0.5)'
					}),
				stroke: new ol.style.Stroke({
				color: '#0ff',
				width: 1
					})
				}),
			'MultiPoint': new ol.style.Style({
			  image: new ol.style.Circle({
				fill: new ol.style.Fill({
				color: 'rgba(255,0,255,0.5)'
					}),
				radius: 5,
				stroke: new ol.style.Stroke({
					color: '#f0f',
					width: 1
						})
					})
				}),
			'MultiLineString': new ol.style.Style({
				stroke: new ol.style.Stroke({
				color: '#0f0',
				width: 3
						})
					}),
			'MultiPolygon': new ol.style.Style({
				fill: new ol.style.Fill({
					color: 'rgba(0,0,255,0.5)'
				}),
				stroke: new ol.style.Stroke({
				color: '#00f',
				width: 1
						})
					})
				};

// Style Function => This is the link between the GeoJSON file and the default style
	var styleFunction = function(feature, resolution) {
		var buttonText = null;
			buttonText = feature.getGeometry().getType();
			button_style(buttonText);
		return defaultStyle[buttonText];
	};

//Drag and drop Function => allows the map to load the given extensions
    var dragAndDropInteraction = new ol.interaction.DragAndDrop({
        formatConstructors: [
			ol.format.GeoJSON,
			ol.format.GML
			]
		});

//Map => creates the map
	var map = new ol.Map({
        interactions: ol.interaction.defaults().extend([dragAndDropInteraction]),
        layers: [
			new ol.layer.Tile({
			source: new ol.source.OSM(),
				})
			],
		controls: ol.control.defaults({
          zoom: true,
          attribution: true,
          rotate: true,
        }),
        target: 'map',
        view: new ol.View({
          center: [0, 0],
          zoom: 2,
        })
    });

//  Drag and Drop interaction Function => describes how to respond once the file is dragged and dropped
	dragAndDropInteraction.on('addfeatures', function(event) {
		i = 1;

        var vectorSource = new ol.source.Vector({
			features: event.features
			});
        map.addLayer(new ol.layer.Vector({
			source: vectorSource,
			style: styleFunction,
			}));
        map.getView().fit(
            vectorSource.getExtent(),(map.getSize()));

	});

// This is the function for the transparency scrollbar
		$(document).ready(function(e) {

			$("#myrange_point").change(function(e) {
				$("h1").html(this.value);
				$("img").css("opacity",this.value);  // this is where we'll link the layer to change the transparency for the point layer
			});
			$("#myrange_polygon").change(function(e) {
				$("h2").html(this.value);
				$("img").css("opacity",this.value);  // this is where we'll link the layer to change the transparency for the polygon layaer
			});
			$("#myrange_line").change(function(e) {
				$("h3").html(this.value);
				$("").css("opacity",this.value);  // this is where we'll link the layer to change the transparency for the line layaer
			});
		});


text:
puts 'Hello.  What is your first name?'
first_name = gets.chomp
puts 'And you middle name?'
middle_name = gets.chomp
puts 'And finally, your last name?'
last_name = gets.chomp
puts 'Excellent!  Welcome, '+ first_name +' '+ middle_name +' '+ last_name +'!'

# Bigger, better favorite number

puts 'What is your favorite number?'
favorite_number = gets.to_i
plus_one = 1
puts 'What about ' + (favorite_number.to_i + plus_one).to_s + '? Isn\'t it a bigger, better number?!'

=begin

Exercise links:

Defining Methods:  https://github.com/rmdemp/phase-0/blob/master/week-4/define-method/my_solution.rb

Address:  https://github.com/rmdemp/phase-0/blob/master/week-4/address/my_solution.rb

Math:  https://github.com/rmdemp/phase-0/blob/master/week-4/math/my_solution.rb

How do you define a local variable?

You assign a value to a local variable by using this code:

                          [variable_name] = [value]

A single '=' is always used for variable assignment.  Local variables should start with a lowercase letter and use dashes or underscores between words if using multiple word names (no capitals or camelcase.)  The value can be a number, a string, or even another variable.

- How do you define a method?

You define a method in this manner:

                          def [method_name](parameters)
                            [enter code block here]
                          end

A method definition must always start with "def" and end with "end" so that Ruby (and the computer) understand that these are the bookends, so to speak, that wrap the code block.

- What is the difference between a local variable and a method?

A local variable is a saved value that can be recalled at any time.  A method acts upon a variable when 'called' upon.  (ex. [local.variable].[method] or gets.chomp, etc.)

- How do you run a ruby program from the command line?

Navigate to the directory that holds the .rb file that you would like to run and type 'ruby [filename].rb' to execute the program.

- How do you run an RSpec file from the command line?

Same as above, make sure that you're in the appropriate directory (which contains both the .rb file to be tested and the Rspec test file) and type 'rspec [filename].rb' to execute.

- What was confusing about this material? What made sense?

It takes a little bit to get used to combining strings and variables and the differences in outputting and returning but I felt that it was pretty easy after a few tries.  The various built-in methods that we covered in this challenge made a lot of sense especially after using them (instead of just reading them.)  I think that this is part of the beauty of Ruby, that it is pretty straightforward and rather intuitive even for a novice like myself.

=end


text:
namespace Google.Cloud.Tasks.V2.Snippets
{
    // [START cloudtasks_v2_generated_CloudTasks_UpdateQueue_async]
    using Google.Protobuf.WellKnownTypes;
    using System.Threading.Tasks;
    using gctv = Google.Cloud.Tasks.V2;

    public sealed partial class GeneratedCloudTasksClientSnippets
    {
        /// <summary>Snippet for UpdateQueueAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task UpdateQueueRequestObjectAsync()
        {
            // Create client
            CloudTasksClient cloudTasksClient = await CloudTasksClient.CreateAsync();
            // Initialize request argument(s)
            UpdateQueueRequest request = new UpdateQueueRequest
            {
                Queue = new Queue(),
                UpdateMask = new FieldMask(),
            };
            // Make the request
            Queue response = await cloudTasksClient.UpdateQueueAsync(request);
        }
    }
    // [END cloudtasks_v2_generated_CloudTasks_UpdateQueue_async]
}


text:
/*
 * 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.
 */
package org.ngrinder.security;

import java.util.Date;
import java.util.HashMap;

import org.ngrinder.model.Role;
import org.ngrinder.model.User;
import org.ngrinder.user.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider;
import org.springframework.transaction.annotation.Transactional;

/**
 * nGrinder {@link PreAuthenticatedAuthenticationProvider}.
 *
 * Some SSO system like SiteMinder doesn't need nGrinder login page. If the user info is resolved by plugins
 * implementing {@link javax.servlet.Filter} which stores the {@link Authentication} by following code,
 *
 * <code>
 * SecurityContextHolder.getContext().setAuthentication(authenticate);
 * </code>
 *
 * {@link NGrinderAuthenticationPreAuthProvider} will take this Authentication Object and handles user language and
 * timezone settings and user save
 *
 * @author JunHo Yoon
 * @since 3.0
 *
 */
public class NGrinderAuthenticationPreAuthProvider extends PreAuthenticatedAuthenticationProvider {

	protected static final Logger LOG = LoggerFactory.getLogger(NGrinderAuthenticationPreAuthProvider.class);

	private UserService userService;

	// ~ Methods
	// ========================================================================================================

	/**
	 * Authenticate the given PreAuthenticatedAuthenticationToken.
	 *
	 * If the principal contained in the authentication object is null, the request will be ignored to allow other
	 * providers to authenticate it.
	 *
	 * @param authentication
	 *            authentication
	 * @return authorized {@link Authentication}
	 */
	@SuppressWarnings("unchecked")
	@Override
	public Authentication authenticate(Authentication authentication) {
		Object details = authentication.getDetails();
		Authentication authenticate = super.authenticate(authentication);
		SecuredUser securedUser = (SecuredUser) authenticate.getPrincipal();
		if (details instanceof HashMap) {
			securedUser.getUser().setTimeZone(((HashMap<String, String>) details).get("user_timezone"));
			securedUser.getUser().setUserLanguage(((HashMap<String, String>) details).get("user_language"));
		} else if (details instanceof LanguageAndTimezone) {
			LanguageAndTimezone languageAndTimeZone = ((LanguageAndTimezone) details);
			securedUser.getUser().setTimeZone(languageAndTimeZone.getTimezone());
			securedUser.getUser().setUserLanguage(languageAndTimeZone.getLanguage());
		}
		// If It's the first time to login
		// means.. If the user info provider is not defaultLoginPlugin..
		if (securedUser.getUser().getId() == null) {
			addNewUserIntoLocal(securedUser);
		}
		return authenticate;
	}

	/**
	 * Add new user into local db.
	 *
	 * @param securedUser
	 *            user
	 */
	@Transactional
	public void addNewUserIntoLocal(SecuredUser securedUser) {
		User user = securedUser.getUser();
		user.setAuthProviderClass(securedUser.getUserInfoProviderClass());
		user.setCreatedDate(new Date());
		User findOneByUserId = userService.getOne(user.getUserId());
		if (findOneByUserId != null) {
			user = findOneByUserId.merge(user);
		}
		if (user.getRole() == null) {
			user.setRole(Role.USER);
		}
		User savedUser = userService.save(user);
		securedUser.setUser(savedUser);
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

}


text:
package org.finos.waltz.integration_test.inmem.service;

import org.finos.waltz.integration_test.inmem.BaseInMemoryIntegrationTest;
import org.finos.waltz.model.EntityKind;
import org.finos.waltz.model.EntityReference;
import org.finos.waltz.model.actor.Actor;
import org.finos.waltz.service.actor.ActorService;
import org.finos.waltz.test_common.helpers.ActorHelper;
import org.finos.waltz.test_common.helpers.LogicalFlowHelper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

import static org.finos.waltz.common.CollectionUtilities.first;
import static org.finos.waltz.model.EntityReference.mkRef;
import static org.finos.waltz.test_common.helpers.NameHelper.mkName;
import static org.junit.jupiter.api.Assertions.*;

public class ActorServiceTest extends BaseInMemoryIntegrationTest {

    @Autowired
    private ActorHelper helper;

    @Autowired
    private ActorService svc;

    @Autowired
    private LogicalFlowHelper logicalFlowHelper;

    @Test
    public void actorsCanBeCreated() {
        String name = mkName("actorsCanBeCreated");
        Long id = helper.createActor(name);

        Actor retrieved = svc.getById(id);
        assertEquals(name, retrieved.name());
        assertEquals(name + " Desc", retrieved.description());
        assertTrue(retrieved.isExternal());
    }

    @Test
    public void actorsCanBeDeletedIfNotUsed() {
        int preCount = svc.findAll().size();
        Long id = helper.createActor(mkName("canBeDeletedTest"));

        System.out.println("After creation: " + svc.findAll());
        boolean deleted = svc.delete(id);

        assertTrue(deleted,
                "Actor should be deleted as not used in flows");
        assertEquals(preCount, svc.findAll().size(),
                "After deletion the count of actors should be the same as before the actor was added");
    }

    @Test
    public void actorsCannotBeDeletedIfUsed() {
        Long idA = helper.createActor(mkName("cannotBeDeletedActorA"));
        Long idB = helper.createActor(mkName("cannotBeDeletedActorB"));

        logicalFlowHelper.createLogicalFlow(
                mkRef(EntityKind.ACTOR, idA),
                mkRef(EntityKind.ACTOR, idB));

        int preCount = svc.findAll().size();
        boolean wasDeleted = svc.delete(idA);

        assertFalse(wasDeleted,
                "Actor should not be deleted as used in a flow");
        assertEquals(preCount, svc.findAll().size(),
                "After attempted deletion the count of actors should be the same");
    }

    @Test
    public void actorsCanBeSearched() {
        List<EntityReference> noHits = svc.search("wibble");
        assertTrue(noHits.isEmpty());

        String a = mkName("searchActorA");
        String b = mkName("searchActorB");

        Long aId = helper.createActor(a);
        helper.createActor(b);

        List<EntityReference> hits = svc.search(a + " " + "desc");
        assertEquals(1, hits.size());
        assertEquals(first(hits), mkRef(EntityKind.ACTOR, aId));
    }

}


text:
Caché de Páginas
================

El caché de páginas se refiere a guardar el contenido de toda una página en el almacenamiento de caché del servidor.
Posteriormente, cuando la misma página sea requerida de nuevo, su contenido será devuelto desde el caché en vez de
volver a generarlo desde cero.

El almacenamiento en caché de páginas está soportado por [[yii\filters\PageCache]], un [filtro de acción](structure-filters.md).
Puede ser utilizado de la siguiente forma en un controlador:

```php
public function behaviors()
{
    return [
        [
            'class' => 'yii\filters\PageCache',
            'only' => ['index'],
            'duration' => 60,
            'variations' => [
                \Yii::$app->language,
            ],
            'dependency' => [
                'class' => 'yii\caching\DbDependency',
                'sql' => 'SELECT COUNT(*) FROM post',
            ],
        ],
    ];
}
```

El código anterior establece que el almacenamiento de páginas en caché debe ser utilizado sólo en la acción `index`; el
contenido de la página debería almacenarse durante un máximo de 60 segundos y ser variado por el idioma actual de la
aplicación; además, el almacenamiento de la página en caché debería ser invalidado si el número total de
artículos ha cambiado.

Como puedes ver, el caché de páginas es muy similar al [caché de fragmentos](caching-fragment.md). Ambos soportan opciones
tales como `duration`, `dependencies`, `variations`, y `enabled`. Su principal diferencia es que el caché de páginas es
implementado como un [filtro de acción](structure-filters.md) mientras que el caché de fragmentos se hace en un [widget](structure-widgets.md).

Puedes usar el [caché de fragmentos](caching-fragment.md) así como [contenido dinámico](caching-fragment.md#dynamic-content)
junto con el caché de páginas.


text:
## Frontend for https://github.com/iostrovok/go-bratok systems ##

### Introduction ###

No yet

## DEVELOPER RELEASE. ##


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.burdahackday.ui">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".LoginActivity"
            android:label="@string/app_name"
            android:theme="@style/AppThemeLogin">

        </activity>
        <activity
            android:name="com.burdahackday.permission.PermissionsActivity"
            android:label="@string/app_name" />
        <activity
            android:name=".MainActivity"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity android:name=".TimeLineActivity" />
        <activity android:name=".SplashActivity"
            android:theme="@style/AppThemeLogin">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


text:
// Client7z.cpp

#include "StdAfx.h"

#include "Common/IntToString.h"
#include "Common/MyInitGuid.h"
#include "Common/StringConvert.h"

#include "Windows/DLL.h"
#include "Windows/FileDir.h"
#include "Windows/FileFind.h"
#include "Windows/FileName.h"
#include "Windows/PropVariant.h"
#include "Windows/PropVariantConversions.h"

#include "../../Common/FileStreams.h"

#include "../../Archive/IArchive.h"

#include "../../IPassword.h"
#include "../../MyVersion.h"

// use another CLSIDs, if you want to support other formats (zip, rar, ...).
// {23170F69-40C1-278A-1000-000110070000}
DEFINE_GUID(CLSID_CFormat7z,
  0x23170F69, 0x40C1, 0x278A, 0x10, 0x00, 0x00, 0x01, 0x10, 0x07, 0x00, 0x00);

using namespace NWindows;

#define kDllName "7z.dll"

static const char *kCopyrightString = MY_7ZIP_VERSION
" ("  kDllName " client) "
MY_COPYRIGHT " " MY_DATE;

static const char *kHelpString =
"Usage: Client7z.exe [a | l | x ] archive.7z [fileName ...]\n"
"Examples:\n"
"  Client7z.exe a archive.7z f1.txt f2.txt  : compress two files to archive.7z\n"
"  Client7z.exe l archive.7z   : List contents of archive.7z\n"
"  Client7z.exe x archive.7z   : eXtract files from archive.7z\n";

typedef UINT32 (WINAPI * CreateObjectFunc)(
    const GUID *clsID,
    const GUID *interfaceID,
    void **outObject);

#ifdef _WIN32
#ifndef _UNICODE
bool g_IsNT = false;
static inline bool IsItWindowsNT()
{
  OSVERSIONINFO versionInfo;
  versionInfo.dwOSVersionInfoSize = sizeof(versionInfo);
  if (!::GetVersionEx(&versionInfo))
    return false;
  return (versionInfo.dwPlatformId == VER_PLATFORM_WIN32_NT);
}
#endif
#endif

void PrintString(const UString &s)
{
  printf("%s", (LPCSTR)GetOemString(s));
}

void PrintString(const AString &s)
{
  printf("%s", (LPCSTR)s);
}

void PrintNewLine()
{
  PrintString("\n");
}

void PrintStringLn(const AString &s)
{
  PrintString(s);
  PrintNewLine();
}

void PrintError(const AString &s)
{
  PrintNewLine();
  PrintString(s);
  PrintNewLine();
}

static HRESULT IsArchiveItemProp(IInArchive *archive, UInt32 index, PROPID propID, bool &result)
{
  NCOM::CPropVariant prop;
  RINOK(archive->GetProperty(index, propID, &prop));
  if (prop.vt == VT_BOOL)
    result = VARIANT_BOOLToBool(prop.boolVal);
  else if (prop.vt == VT_EMPTY)
    result = false;
  else
    return E_FAIL;
  return S_OK;
}

static HRESULT IsArchiveItemFolder(IInArchive *archive, UInt32 index, bool &result)
{
  return IsArchiveItemProp(archive, index, kpidIsDir, result);
}

static const wchar_t *kEmptyFileAlias = L"[Content]";

//////////////////////////////////////////////////////////////
// Archive Open callback class

class CArchiveOpenCallback:
  public IArchiveOpenCallback,
  public ICryptoGetTextPassword,
  public CMyUnknownImp
{
public:
  MY_UNKNOWN_IMP1(ICryptoGetTextPassword)

  STDMETHOD(SetTotal)(const UInt64 *files, const UInt64 *bytes);
  STDMETHOD(SetCompleted)(const UInt64 *files, const UInt64 *bytes);

  STDMETHOD(CryptoGetTextPassword)(BSTR *password);

  bool PasswordIsDefined;
  UString Password;

  CArchiveOpenCallback() : PasswordIsDefined(false) {}
};

STDMETHODIMP CArchiveOpenCallback::SetTotal(const UInt64 * /* files */, const UInt64 * /* bytes */)
{
  return S_OK;
}

STDMETHODIMP CArchiveOpenCallback::SetCompleted(const UInt64 * /* files */, const UInt64 * /* bytes */)
{
  return S_OK;
}

STDMETHODIMP CArchiveOpenCallback::CryptoGetTextPassword(BSTR *password)
{
  if (!PasswordIsDefined)
  {
    // You can ask real password here from user
    // Password = GetPassword(OutStream);
    // PasswordIsDefined = true;
    PrintError("Password is not defined");
    return E_ABORT;
  }
  return StringToBstr(Password, password);
}

//////////////////////////////////////////////////////////////
// Archive Extracting callback class

static const wchar_t *kCantDeleteOutputFile = L"ERROR: Can not delete output file ";

static const char *kTestingString    =  "Testing     ";
static const char *kExtractingString =  "Extracting  ";
static const char *kSkippingString   =  "Skipping    ";

static const char *kUnsupportedMethod = "Unsupported Method";
static const char *kCRCFailed = "CRC Failed";
static const char *kDataError = "Data Error";
static const char *kUnknownError = "Unknown Error";

class CArchiveExtractCallback:
  public IArchiveExtractCallback,
  public ICryptoGetTextPassword,
  public CMyUnknownImp
{
public:
  MY_UNKNOWN_IMP1(ICryptoGetTextPassword)

  // IProgress
  STDMETHOD(SetTotal)(UInt64 size);
  STDMETHOD(SetCompleted)(const UInt64 *completeValue);

  // IArchiveExtractCallback
  STDMETHOD(GetStream)(UInt32 index, ISequentialOutStream **outStream, Int32 askExtractMode);
  STDMETHOD(PrepareOperation)(Int32 askExtractMode);
  STDMETHOD(SetOperationResult)(Int32 resultEOperationResult);

  // ICryptoGetTextPassword
  STDMETHOD(CryptoGetTextPassword)(BSTR *aPassword);

private:
  CMyComPtr<IInArchive> _archiveHandler;
  UString _directoryPath;  // Output directory
  UString _filePath;       // name inside arcvhive
  UString _diskFilePath;   // full path to file on disk
  bool _extractMode;
  struct CProcessedFileInfo
  {
    FILETIME MTime;
    UInt32 Attrib;
    bool isDir;
    bool AttribDefined;
    bool MTimeDefined;
  } _processedFileInfo;

  COutFileStream *_outFileStreamSpec;
  CMyComPtr<ISequentialOutStream> _outFileStream;

public:
  void Init(IInArchive *archiveHandler, const UString &directoryPath);

  UInt64 NumErrors;
  bool PasswordIsDefined;
  UString Password;

  CArchiveExtractCallback() : PasswordIsDefined(false) {}
};

void CArchiveExtractCallback::Init(IInArchive *archiveHandler, const UString &directoryPath)
{
  NumErrors = 0;
  _archiveHandler = archiveHandler;
  _directoryPath = directoryPath;
  NFile::NName::NormalizeDirPathPrefix(_directoryPath);
}

STDMETHODIMP CArchiveExtractCallback::SetTotal(UInt64 /* size */)
{
  return S_OK;
}

STDMETHODIMP CArchiveExtractCallback::SetCompleted(const UInt64 * /* completeValue */)
{
  return S_OK;
}

STDMETHODIMP CArchiveExtractCallback::GetStream(UInt32 index,
    ISequentialOutStream **outStream, Int32 askExtractMode)
{
  *outStream = 0;
  _outFileStream.Release();

  {
    // Get Name
    NCOM::CPropVariant prop;
    RINOK(_archiveHandler->GetProperty(index, kpidPath, &prop));

    UString fullPath;
    if (prop.vt == VT_EMPTY)
      fullPath = kEmptyFileAlias;
    else
    {
      if (prop.vt != VT_BSTR)
        return E_FAIL;
      fullPath = prop.bstrVal;
    }
    _filePath = fullPath;
  }

  if (askExtractMode != NArchive::NExtract::NAskMode::kExtract)
    return S_OK;

  {
    // Get Attrib
    NCOM::CPropVariant prop;
    RINOK(_archiveHandler->GetProperty(index, kpidAttrib, &prop));
    if (prop.vt == VT_EMPTY)
    {
      _processedFileInfo.Attrib = 0;
      _processedFileInfo.AttribDefined = false;
    }
    else
    {
      if (prop.vt != VT_UI4)
        return E_FAIL;
      _processedFileInfo.Attrib = prop.ulVal;
      _processedFileInfo.AttribDefined = true;
    }
  }

  RINOK(IsArchiveItemFolder(_archiveHandler, index, _processedFileInfo.isDir));

  {
    // Get Modified Time
    NCOM::CPropVariant prop;
    RINOK(_archiveHandler->GetProperty(index, kpidMTime, &prop));
    _processedFileInfo.MTimeDefined = false;
    switch(prop.vt)
    {
      case VT_EMPTY:
        // _processedFileInfo.MTime = _utcMTimeDefault;
        break;
      case VT_FILETIME:
        _processedFileInfo.MTime = prop.filetime;
        _processedFileInfo.MTimeDefined = true;
        break;
      default:
        return E_FAIL;
    }

  }
  {
    // Get Size
    NCOM::CPropVariant prop;
    RINOK(_archiveHandler->GetProperty(index, kpidSize, &prop));
    bool newFileSizeDefined = (prop.vt != VT_EMPTY);
    UInt64 newFileSize;
    if (newFileSizeDefined)
      newFileSize = ConvertPropVariantToUInt64(prop);
  }

  {
    // Create folders for file
    int slashPos = _filePath.ReverseFind(WCHAR_PATH_SEPARATOR);
    if (slashPos >= 0)
      NFile::NDirectory::CreateComplexDirectory(_directoryPath + _filePath.Left(slashPos));
  }

  UString fullProcessedPath = _directoryPath + _filePath;
  _diskFilePath = fullProcessedPath;

  if (_processedFileInfo.isDir)
  {
    NFile::NDirectory::CreateComplexDirectory(fullProcessedPath);
  }
  else
  {
    NFile::NFind::CFileInfoW fi;
    if (NFile::NFind::FindFile(fullProcessedPath, fi))
    {
      if (!NFile::NDirectory::DeleteFileAlways(fullProcessedPath))
      {
        PrintString(UString(kCantDeleteOutputFile) + fullProcessedPath);
        return E_ABORT;
      }
    }

    _outFileStreamSpec = new COutFileStream;
    CMyComPtr<ISequentialOutStream> outStreamLoc(_outFileStreamSpec);
    if (!_outFileStreamSpec->Open(fullProcessedPath, CREATE_ALWAYS))
    {
      PrintString((UString)L"can not open output file " + fullProcessedPath);
      return E_ABORT;
    }
    _outFileStream = outStreamLoc;
    *outStream = outStreamLoc.Detach();
  }
  return S_OK;
}

STDMETHODIMP CArchiveExtractCallback::PrepareOperation(Int32 askExtractMode)
{
  _extractMode = false;
  switch (askExtractMode)
  {
    case NArchive::NExtract::NAskMode::kExtract:  _extractMode = true; break;
  };
  switch (askExtractMode)
  {
    case NArchive::NExtract::NAskMode::kExtract:  PrintString(kExtractingString); break;
    case NArchive::NExtract::NAskMode::kTest:  PrintString(kTestingString); break;
    case NArchive::NExtract::NAskMode::kSkip:  PrintString(kSkippingString); break;
  };
  PrintString(_filePath);
  return S_OK;
}

STDMETHODIMP CArchiveExtractCallback::SetOperationResult(Int32 operationResult)
{
  switch(operationResult)
  {
    case NArchive::NExtract::NOperationResult::kOK:
      break;
    default:
    {
      NumErrors++;
      PrintString("     ");
      switch(operationResult)
      {
        case NArchive::NExtract::NOperationResult::kUnSupportedMethod:
          PrintString(kUnsupportedMethod);
          break;
        case NArchive::NExtract::NOperationResult::kCRCError:
          PrintString(kCRCFailed);
          break;
        case NArchive::NExtract::NOperationResult::kDataError:
          PrintString(kDataError);
          break;
        default:
          PrintString(kUnknownError);
      }
    }
  }

  if (_outFileStream != NULL)
  {
    if (_processedFileInfo.MTimeDefined)
      _outFileStreamSpec->SetMTime(&_processedFileInfo.MTime);
    RINOK(_outFileStreamSpec->Close());
  }
  _outFileStream.Release();
  if (_extractMode && _processedFileInfo.AttribDefined)
    NFile::NDirectory::MySetFileAttributes(_diskFilePath, _processedFileInfo.Attrib);
  PrintNewLine();
  return S_OK;
}

STDMETHODIMP CArchiveExtractCallback::CryptoGetTextPassword(BSTR *password)
{
  if (!PasswordIsDefined)
  {
    // You can ask real password here from user
    // Password = GetPassword(OutStream);
    // PasswordIsDefined = true;
    PrintError("Password is not defined");
    return E_ABORT;
  }
  return StringToBstr(Password, password);
}

//////////////////////////////////////////////////////////////
// Archive Creating callback class

struct CDirItem
{
  UInt64 Size;
  FILETIME CTime;
  FILETIME ATime;
  FILETIME MTime;
  UString Name;
  UString FullPath;
  UInt32 Attrib;

  bool isDir() const { return (Attrib & FILE_ATTRIBUTE_DIRECTORY) != 0 ; }
};

class CArchiveUpdateCallback:
  public IArchiveUpdateCallback2,
  public ICryptoGetTextPassword2,
  public CMyUnknownImp
{
public:
  MY_UNKNOWN_IMP2(IArchiveUpdateCallback2, ICryptoGetTextPassword2)

  // IProgress
  STDMETHOD(SetTotal)(UInt64 size);
  STDMETHOD(SetCompleted)(const UInt64 *completeValue);

  // IUpdateCallback2
  STDMETHOD(EnumProperties)(IEnumSTATPROPSTG **enumerator);
  STDMETHOD(GetUpdateItemInfo)(UInt32 index,
      Int32 *newData, Int32 *newProperties, UInt32 *indexInArchive);
  STDMETHOD(GetProperty)(UInt32 index, PROPID propID, PROPVARIANT *value);
  STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **inStream);
  STDMETHOD(SetOperationResult)(Int32 operationResult);
  STDMETHOD(GetVolumeSize)(UInt32 index, UInt64 *size);
  STDMETHOD(GetVolumeStream)(UInt32 index, ISequentialOutStream **volumeStream);

  STDMETHOD(CryptoGetTextPassword2)(Int32 *passwordIsDefined, BSTR *password);

public:
  CRecordVector<UInt64> VolumesSizes;
  UString VolName;
  UString VolExt;

  UString DirPrefix;
  const CObjectVector<CDirItem> *DirItems;

  bool PasswordIsDefined;
  UString Password;
  bool AskPassword;

  bool m_NeedBeClosed;

  UStringVector FailedFiles;
  CRecordVector<HRESULT> FailedCodes;

  CArchiveUpdateCallback(): PasswordIsDefined(false), AskPassword(false), DirItems(0) {};

  ~CArchiveUpdateCallback() { Finilize(); }
  HRESULT Finilize();

  void Init(const CObjectVector<CDirItem> *dirItems)
  {
    DirItems = dirItems;
    m_NeedBeClosed = false;
    FailedFiles.Clear();
    FailedCodes.Clear();
  }
};

STDMETHODIMP CArchiveUpdateCallback::SetTotal(UInt64 /* size */)
{
  return S_OK;
}

STDMETHODIMP CArchiveUpdateCallback::SetCompleted(const UInt64 * /* completeValue */)
{
  return S_OK;
}

STDMETHODIMP CArchiveUpdateCallback::EnumProperties(IEnumSTATPROPSTG ** /* enumerator */)
{
  return E_NOTIMPL;
}

STDMETHODIMP CArchiveUpdateCallback::GetUpdateItemInfo(UInt32 /* index */,
      Int32 *newData, Int32 *newProperties, UInt32 *indexInArchive)
{
  if (newData != NULL)
    *newData = BoolToInt(true);
  if (newProperties != NULL)
    *newProperties = BoolToInt(true);
  if (indexInArchive != NULL)
    *indexInArchive = (UInt32)-1;
  return S_OK;
}

STDMETHODIMP CArchiveUpdateCallback::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)
{
  NWindows::NCOM::CPropVariant prop;

  if (propID == kpidIsAnti)
  {
    prop = false;
    prop.Detach(value);
    return S_OK;
  }

  {
    const CDirItem &dirItem = (*DirItems)[index];
    switch(propID)
    {
      case kpidPath:  prop = dirItem.Name; break;
      case kpidIsDir:  prop = dirItem.isDir(); break;
      case kpidSize:  prop = dirItem.Size; break;
      case kpidAttrib:  prop = dirItem.Attrib; break;
      case kpidCTime:  prop = dirItem.CTime; break;
      case kpidATime:  prop = dirItem.ATime; break;
      case kpidMTime:  prop = dirItem.MTime; break;
    }
  }
  prop.Detach(value);
  return S_OK;
}

HRESULT CArchiveUpdateCallback::Finilize()
{
  if (m_NeedBeClosed)
  {
    PrintNewLine();
    m_NeedBeClosed = false;
  }
  return S_OK;
}

static void GetStream2(const wchar_t *name)
{
  PrintString("Compressing  ");
  if (name[0] == 0)
    name = kEmptyFileAlias;
  PrintString(name);
}

STDMETHODIMP CArchiveUpdateCallback::GetStream(UInt32 index, ISequentialInStream **inStream)
{
  RINOK(Finilize());

  const CDirItem &dirItem = (*DirItems)[index];
  GetStream2(dirItem.Name);

  if (dirItem.isDir())
    return S_OK;

  {
    CInFileStream *inStreamSpec = new CInFileStream;
    CMyComPtr<ISequentialInStream> inStreamLoc(inStreamSpec);
    UString path = DirPrefix + dirItem.FullPath;
    if (!inStreamSpec->Open(path))
    {
      DWORD sysError = ::GetLastError();
      FailedCodes.Add(sysError);
      FailedFiles.Add(path);
      // if (systemError == ERROR_SHARING_VIOLATION)
      {
        PrintNewLine();
        PrintError("WARNING: can't open file");
        // PrintString(NError::MyFormatMessageW(systemError));
        return S_FALSE;
      }
      // return sysError;
    }
    *inStream = inStreamLoc.Detach();
  }
  return S_OK;
}

STDMETHODIMP CArchiveUpdateCallback::SetOperationResult(Int32 /* operationResult */)
{
  m_NeedBeClosed = true;
  return S_OK;
}

STDMETHODIMP CArchiveUpdateCallback::GetVolumeSize(UInt32 index, UInt64 *size)
{
  if (VolumesSizes.Size() == 0)
    return S_FALSE;
  if (index >= (UInt32)VolumesSizes.Size())
    index = VolumesSizes.Size() - 1;
  *size = VolumesSizes[index];
  return S_OK;
}

STDMETHODIMP CArchiveUpdateCallback::GetVolumeStream(UInt32 index, ISequentialOutStream **volumeStream)
{
  wchar_t temp[32];
  ConvertUInt64ToString(index + 1, temp);
  UString res = temp;
  while (res.Length() < 2)
    res = UString(L'0') + res;
  UString fileName = VolName;
  fileName += L'.';
  fileName += res;
  fileName += VolExt;
  COutFileStream *streamSpec = new COutFileStream;
  CMyComPtr<ISequentialOutStream> streamLoc(streamSpec);
  if (!streamSpec->Create(fileName, false))
    return ::GetLastError();
  *volumeStream = streamLoc.Detach();
  return S_OK;
}

STDMETHODIMP CArchiveUpdateCallback::CryptoGetTextPassword2(Int32 *passwordIsDefined, BSTR *password)
{
  if (!PasswordIsDefined)
  {
    if (AskPassword)
    {
      // You can ask real password here from user
      // Password = GetPassword(OutStream);
      // PasswordIsDefined = true;
      PrintError("Password is not defined");
      return E_ABORT;
    }
  }
  *passwordIsDefined = BoolToInt(PasswordIsDefined);
  return StringToBstr(Password, password);
}

//////////////////////////////////////////////////////////////////////////
// Main function

int MY_CDECL main(int argc, char* argv[])
{
  #ifdef _WIN32
  #ifndef _UNICODE
  g_IsNT = IsItWindowsNT();
  #endif
  #endif

  PrintStringLn(kCopyrightString);

  if (argc < 3)
  {
    PrintStringLn(kHelpString);
    return 1;
  }
  NWindows::NDLL::CLibrary library;
  if (!library.Load(TEXT(kDllName)))
  {
    PrintError("Can not load library");
    return 1;
  }
  CreateObjectFunc createObjectFunc = (CreateObjectFunc)library.GetProcAddress("CreateObject");
  if (createObjectFunc == 0)
  {
    PrintError("Can not get CreateObject");
    return 1;
  }

  AString command = argv[1];
  command.MakeLower();
  UString archiveName = GetUnicodeString(argv[2], CP_OEMCP);
  if (command.Compare("a") == 0)
  {
    // create archive command
    if (argc < 4)
    {
      PrintStringLn(kHelpString);
      return 1;
    }
    CObjectVector<CDirItem> dirItems;
    int i;
    for (i = 3; i < argc; i++)
    {
      CDirItem di;
      UString name = GetUnicodeString(argv[i], CP_OEMCP);

      NFile::NFind::CFileInfoW fi;
      if (!NFile::NFind::FindFile(name, fi))
      {
        PrintString(UString(L"Can't find file") + name);
        return 1;
      }

      di.Attrib = fi.Attrib;
      di.Size = fi.Size;
      di.CTime = fi.CTime;
      di.ATime = fi.ATime;
      di.MTime = fi.MTime;
      di.Name = name;
      di.FullPath = name;
      dirItems.Add(di);
    }
    COutFileStream *outFileStreamSpec = new COutFileStream;
    CMyComPtr<IOutStream> outFileStream = outFileStreamSpec;
    if (!outFileStreamSpec->Create(archiveName, false))
    {
      PrintError("can't create archive file");
      return 1;
    }

    CMyComPtr<IOutArchive> outArchive;
    if (createObjectFunc(&CLSID_CFormat7z, &IID_IOutArchive, (void **)&outArchive) != S_OK)
    {
      PrintError("Can not get class object");
      return 1;
    }

    CArchiveUpdateCallback *updateCallbackSpec = new CArchiveUpdateCallback;
    CMyComPtr<IArchiveUpdateCallback2> updateCallback(updateCallbackSpec);
    updateCallbackSpec->Init(&dirItems);
    // updateCallbackSpec->PasswordIsDefined = true;
    // updateCallbackSpec->Password = L"1";

    HRESULT result = outArchive->UpdateItems(outFileStream, dirItems.Size(), updateCallback);
    updateCallbackSpec->Finilize();
    if (result != S_OK)
    {
      PrintError("Update Error");
      return 1;
    }
    for (i = 0; i < updateCallbackSpec->FailedFiles.Size(); i++)
    {
      PrintNewLine();
      PrintString((UString)L"Error for file: " + updateCallbackSpec->FailedFiles[i]);
    }
    if (updateCallbackSpec->FailedFiles.Size() != 0)
      return 1;
  }
  else
  {
    if (argc != 3)
    {
      PrintStringLn(kHelpString);
      return 1;
    }

    bool listCommand;
    if (command.Compare("l") == 0)
      listCommand = true;
    else if (command.Compare("x") == 0)
      listCommand = false;
    else
    {
      PrintError("incorrect command");
      return 1;
    }

    CMyComPtr<IInArchive> archive;
    if (createObjectFunc(&CLSID_CFormat7z, &IID_IInArchive, (void **)&archive) != S_OK)
    {
      PrintError("Can not get class object");
      return 1;
    }

    CInFileStream *fileSpec = new CInFileStream;
    CMyComPtr<IInStream> file = fileSpec;

    if (!fileSpec->Open(archiveName))
    {
      PrintError("Can not open archive file");
      return 1;
    }

    {
      CArchiveOpenCallback *openCallbackSpec = new CArchiveOpenCallback;
      CMyComPtr<IArchiveOpenCallback> openCallback(openCallbackSpec);
      openCallbackSpec->PasswordIsDefined = false;
      // openCallbackSpec->PasswordIsDefined = true;
      // openCallbackSpec->Password = L"1";

      if (archive->Open(file, 0, openCallback) != S_OK)
      {
        PrintError("Can not open archive");
        return 1;
      }
    }

    if (listCommand)
    {
      // List command
      UInt32 numItems = 0;
      archive->GetNumberOfItems(&numItems);
      for (UInt32 i = 0; i < numItems; i++)
      {
        {
          // Get uncompressed size of file
          NWindows::NCOM::CPropVariant prop;
          archive->GetProperty(i, kpidSize, &prop);
          UString s = ConvertPropVariantToString(prop);
          PrintString(s);
          PrintString("  ");
        }
        {
          // Get name of file
          NWindows::NCOM::CPropVariant prop;
          archive->GetProperty(i, kpidPath, &prop);
          UString s = ConvertPropVariantToString(prop);
          PrintString(s);
        }
        PrintString("\n");
      }
    }
    else
    {
      // Extract command
      CArchiveExtractCallback *extractCallbackSpec = new CArchiveExtractCallback;
      CMyComPtr<IArchiveExtractCallback> extractCallback(extractCallbackSpec);
      extractCallbackSpec->Init(archive, L""); // second parameter is output folder path
      extractCallbackSpec->PasswordIsDefined = false;
      // extractCallbackSpec->PasswordIsDefined = true;
      // extractCallbackSpec->Password = L"1";
      HRESULT result = archive->Extract(NULL, (UInt32)(Int32)(-1), false, extractCallback);
      if (result != S_OK)
      {
        PrintError("Extract Error");
        return 1;
      }
    }
  }
  return 0;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/txtBillId"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="5dp"
        android:paddingLeft="16dp"
        android:paddingRight="16dp"
        android:paddingTop="5dp"
        android:textSize="16sp"
        android:textColor="@color/fontgrey"/>

    <TextView
        android:id="@+id/txtBillNum"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="5dp"
        android:paddingLeft="16dp"
        android:paddingRight="16dp"
        android:paddingTop="5dp"
        android:text="TITLE"
        android:textSize="16sp"
        android:textColor="@color/fontgrey"/>

    <TextView
        android:id="@+id/txtTradeNum"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="5dp"
        android:paddingLeft="16dp"
        android:paddingRight="16dp"
        android:paddingTop="5dp"
        android:textSize="12sp"
        android:textColor="@color/fontgrey"/>

    <TextView
        android:id="@+id/txtTotalFee"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="5dp"
        android:paddingLeft="16dp"
        android:paddingRight="16dp"
        android:paddingTop="5dp"
        android:textSize="12sp"
        android:textColor="@color/fontgrey"/>

    <TextView
        android:id="@+id/txtChannel"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="5dp"
        android:paddingLeft="16dp"
        android:paddingRight="16dp"
        android:paddingTop="5dp"
        android:textSize="12sp"
        android:textColor="@color/fontgrey"/>

    <TextView
        android:id="@+id/txtSubChannel"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="5dp"
        android:paddingLeft="16dp"
        android:paddingRight="16dp"
        android:paddingTop="5dp"
        android:textSize="12sp"
        android:textColor="@color/fontgrey"/>

    <TextView
        android:id="@+id/txtTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="5dp"
        android:paddingLeft="16dp"
        android:paddingRight="16dp"
        android:paddingTop="5dp"
        android:textSize="12sp"
        android:textColor="@color/fontgrey"/>

    <TextView
        android:id="@+id/txtPayResult"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="5dp"
        android:paddingLeft="16dp"
        android:paddingRight="16dp"
        android:paddingTop="5dp"
        android:textSize="12sp"
        android:textColor="@color/fontgrey"/>

    <TextView
        android:id="@+id/txtCreatedTime"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="5dp"
        android:paddingLeft="16dp"
        android:paddingRight="16dp"
        android:paddingTop="5dp"
        android:textSize="12sp"
        android:textColor="@color/fontgrey"/>

    <TextView
        android:id="@+id/txtOptional"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="5dp"
        android:paddingLeft="16dp"
        android:paddingRight="16dp"
        android:paddingTop="5dp"
        android:textSize="12sp"
        android:textColor="@color/fontgrey"/>

</LinearLayout>


text:
@class Game;

@interface Ball : CCNode {
@private
    Game *game;
    b2World *world;
    b2Body *body;
    b2BodyDef *bodyDef;
    b2PolygonShape *shapeDef;
    b2FixtureDef *fixtureDef;
}

-(void) addBall;

-(id) initWithMgr:(CGPoint)points; // atlasManager reference

-(id) addCCNode:(CCNode *)pSprite;

@property (nonatomic, retain) Game *game;

@property (nonatomic, assign) b2Body *body;

@property (nonatomic, assign) b2BodyDef *bodyDef;

@property (nonatomic, assign) b2PolygonShape *shapeDef;

@property (nonatomic, assign) b2FixtureDef *fixtureDef;

@end


text:
class Regexp::Syntax::V2_0_0 < Regexp::Syntax::V1_9_3
  implements :keep,        Keep::All
  implements :conditional, Conditional::All
  implements :property,    UnicodeProperty::V2_0_0
  implements :nonproperty, UnicodeProperty::V2_0_0
  implements :type,        CharacterType::Clustered

  excludes   :property,    %i[newline]
  excludes   :nonproperty, %i[newline]
end


text:
using System;
using System.IO;
using System.Net;
using System.Text;
using DynamicRest.Helpers;

namespace DynamicRest.HTTPInterfaces.WebWrappers {

    public class HttpWebRequestWrapper : IHttpRequest {

        private readonly HttpWebRequest _webrequest;

        public HttpWebRequestWrapper(HttpWebRequest webrequest) {
            _webrequest = webrequest;
        }

        public Uri RequestURI {
            get { return _webrequest.RequestUri; }
        }

        public HttpVerb HttpVerb {
            get {
                return _webrequest.Method.ToHttpVerb();
            }
            set {
                _webrequest.Method = value.ToString();
            }
        }

        public WebHeaderCollection Headers {
            get { return _webrequest.Headers; }
        }

        public string Accept {
            get {
                return _webrequest.Accept;
            }
            set {
                _webrequest.Accept = value;
            }
        }

        public string ContentType {
            get {
                return _webrequest.ContentType;
            }
        }

        public bool AllowAutoRedirect {
            get { return _webrequest.AllowAutoRedirect; }
            set { _webrequest.AllowAutoRedirect = value; }
        }

        public string UserAgent {
            get {
                return _webrequest.UserAgent;
            }
            set {
                if (!string.IsNullOrWhiteSpace(value))
                {
                    _webrequest.UserAgent = value;
                }
            }
        }

        public int Timeout
        {
            get { return _webrequest.Timeout; }
            set { _webrequest.Timeout = value; }
        }

        public IWebProxy Proxy
        {
            get { return _webrequest.Proxy; }
            set { _webrequest.Proxy = value; }
        }

        public DateTime IfModifiedSince
        {
            get { return _webrequest.IfModifiedSince; }
            set { _webrequest.IfModifiedSince = value; }
        }

        public void AddCredentials(ICredentials credentials) {
            _webrequest.Credentials = credentials;
        }

        public void AddHeaders(WebHeaderCollection headers) {
            _webrequest.Headers.Add(headers);
        }

        public void AddRequestBody(string contentType, string content) {
            if (content != null) {
                byte[] bytes = Encoding.UTF8.GetBytes(content);
                _webrequest.ContentType = contentType;
                _webrequest.ContentLength = bytes.Length;
                using (Stream requestStream = _webrequest.GetRequestStream()) {
                    requestStream.Write(bytes, 0, bytes.Length);
                }
            }
        }

        public void BeginGetResponse(Action<object> action, object asyncRequest) {
            _webrequest.BeginGetResponse(ar => action(ar), asyncRequest);
        }

        public IHttpResponse EndGetResponse(object asyncRequest) {
            return new HttpWebResponseWrapper((HttpWebResponse) _webrequest.EndGetResponse((IAsyncResult) asyncRequest));
        }

        public IHttpResponse GetResponse()
        {
            return new HttpWebResponseWrapper(_webrequest.GetResponse() as HttpWebResponse);
        }
    }
}


text:
package com.robin.core.test.db;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import junit.framework.TestCase;

import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.robin.core.base.dao.JdbcDao;
import com.robin.core.base.spring.SpringContextHolder;
import com.robin.core.query.util.PageQuery;
import com.robin.core.test.model.TestLob;
import com.robin.core.test.service.TestLobService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext-test.xml")
public class TestLobHandler extends TestCase {
    @Test
    public void insertLob() throws Exception {

        TestLobService service = (TestLobService) SpringContextHolder.getBean("lobService");
        TestLob lob = new TestLob();
        lob.setName("test" + String.valueOf(System.currentTimeMillis()));
        BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("LICENSE")));
        StringBuilder builder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            builder.append(line).append("\n");
        }
        lob.setLob1(builder.toString());
        InputStream bytestream = getClass().getClassLoader().getResourceAsStream("pig.ico");
        byte[] bytes = IOUtils.toByteArray(bytestream);
        lob.setLob2(bytes);
        service.saveEntity(lob);
        assertNotNull(lob.getId());
    }

    @Test
    public void testQuerylob() {
        JdbcDao jdbcDao = SpringContextHolder.getBean("jdbcDao", JdbcDao.class);
        PageQuery query = new PageQuery();
        query.setPageSize(1);
        query.setSelectParamId("GET_LOB");
        query.getParameters().put("condition", "");
        jdbcDao.queryBySelectId(query);
        List<Map<String, Object>> rsList = query.getRecordSet();
        assertNotNull(rsList);
    }

    @Test
    public void testQueryVO() {
        TestLobService service = (TestLobService) SpringContextHolder.getBean("lobService");
        TestLob obj = service.getEntity(Long.valueOf("1"));
        try {
            ByteArrayInputStream in = new ByteArrayInputStream(obj.getLob2());
            String path = "/tmp/pig.ico";
            System.out.println(path);
            OutputStream out = new FileOutputStream(new File(path));
            IOUtils.copy(in, out);
            out.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class shike extends MY_Controller {

	function __construct()
	{
		parent::__construct();
	}

	public function index()
	{
		// echo 2;die();
		$this->out_data['con_page'] = 'shike';
		$this->load->view('shike_default', $this->out_data);
	}
}