<commit_before>/* global App */

/**
 * Features module
 *
 * HTML5 feature detection based on the concepts and ideas by Modernizr
 * @link http://html5please.com/
 * @link http://caniuse.com/
 * @link https://github.com/NielsLeenheer/html5test/
 *
 * Modified: 2015/12/06
 * @author softwarespot
 */
App.namespace('core').features = (function featuresModule(window, document, $, core, undefined) {
    // Constants

    // SemVer version number of the module
    var VERSION = '1.0.0';

    // Unique global identifier. Internal usage only
    // var GUID = '3B8C44B7-6A3B-4F84-A031-2D7B5D4ED211';

    // Fields

    // Store if the module has been initialised
    var _isInitialised = false;

    // Native functions
    var _nativeCSS = window.CSS;
    var _nativeHistory = window.history;
    var _nativeLocalStorage = window.localStorage;
    var _nativeNavigator = window.navigator;
    var _nativePromise = window.Promise;
    var _nativeSessionStorage = window.sessionStorage;

    // Store has* results
    // Note: Opera 12 supports window.supportsCSS according to caniuse.com
    var _hasCSSSupports = (core.isFunction(_nativeCSS) && core.isFunction(_nativeCSS.supports)) || window.supportsCSS;
    var _hasGeoLocation = core.isObject(_nativeNavigator) &&
        'geolocation' in _nativeNavigator;

    var _hasHistory = core.isObject(_nativeHistory) &&
        'pushState' in _nativeHistory;

    var _hasLocalStorage = _isStorage(_nativeLocalStorage);
    var _hasSessionStorage = _isStorage(_nativeSessionStorage);
    var _hasWebStorage = _hasLocalStorage && _hasSessionStorage;

    var _hasPromise = core.isFunction(_nativePromise) &&
        'all' in _nativePromise &&
        'race' in _nativePromise &&
        'reject' in _nativePromise &&
        'resolve' in _nativePromise;

    // Hold the input data, with the key being the input type and the value of either true or false as
    // whether or not it's supported by the following browser
    var _inputs = null;

    // Cache the HTML node
    var _html = document.documentElement;
    var _prefixes = ['Khtml', 'Moz', 'Ms', 'O', 'Webkit'];

    // Methods

    /**
     * Initialise the module
     *
     * @return {undefined}
     */
    function init() {
        if (_isInitialised) {
            return;
        }

        // Initialise the input object literal
        _getInputs();

        _isInitialised = true;
    }

    /**
     * Destroy the module
     *
     * @return {undefined}
     */
    function destroy() {
        _isInitialised = false;
    }

    /**
     * Get the version number of the module
     *
     * @returns {number} Version number
     */
    function getVersion() {
        return VERSION;
    }

    // CSS

    /**
     * Checl if CSSSupports exists
     *
     * @return {boolean} True, the feature exists; otherwise, false
     */
    function hasCSSSupports() {
        return _hasCSSSupports;
    }

    // EVENTS
    // https://github.com/Modernizr/Modernizr/blob/master/src/hasEvent.js
    // https://github.com/Modernizr/Modernizr/blob/master/feature-detects/hashchange.js

    // HISTORY

    /**
     * Check if the History API exists
     *
     * Based on the concept by Modernizr URL: https://github.com/Modernizr/Modernizr/blob/master/feature-detects/history.js
     *
     * @return {boolean} True, the feature exists; otherwise, false
     */
    function hasHistory() {
        return _hasHistory;
    }

    // GEOLOCATION

    /**
     * Check if the geolocation API exists
     *
     * Based on the concept by Modernizr, URL: https://github.com/Modernizr/Modernizr/blob/master/feature-detects/geolocation.js
     *
     * @return {boolean} True, the feature exists; otherwise, false
     */
    function hasGeoLocation() {
        return _hasGeoLocation;
    }

    // INPUTS

    /**
     * Check if an input type is supported
     *
     * @param {string} inputType Input type
     * @return {boolean} True the type is supported; otherwise, false
     */
    function hasInput(inputType) {
        // Coerce as a string
        var hasInputResult = _inputs[core.toString(inputType)];
        return core.isUndefined(hasInputResult) ? false : hasInputResult;
    }

    /**
     * Initialise the input object literal
     *
     * Based on the concept by Modernizr, URL: https://github.com/Modernizr/Modernizr/commits/master/feature-detects/inputtypes.js
     *
     * @return {undefined}
     */
    function _getInputs() {
        if (!core.isNull(_inputs)) {
            return;
        }

        // Regular expressions
        var reEmailNumberUrl = /^(?:email|number|url)$/;
        var reRange = /(?:^range$)/;
        var reSearchTel = /^(?:search|tel)$/;

        // Create an empty object literal
        _inputs = {};

        // Input types that will are split as an array
        var inputTypes = 'color date datetime datetime-local email month number range search tel time url week'.split(' ');

        // Create a temporary input element
        var input = document.createElement('input');

        // Document element to bind the input element to
        var documentElem = document.documentElement;

        // Inline stylesheet
        var cssStyles = 'position:absolute;visibility:hidden;';

        // Data to test with
        var testData = '=)';

        // Iterate through the array. A polyfill is available at
        // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Polyfill
        inputTypes.forEach(function forEachInputType(inputType) {

            // Set the attribute type of the input element
            input.setAttribute('type', inputType);

            // Check the type is not text and that it contains a 'style' property
            var isValid = input.type !== 'text' && 'style' in input;

            // If invalid then simply return and don't continue
            if (!isValid) {
                return;
            }

            // First check to see if the type we give it sticks
            // If the type does, we feed it a textual value, which shouldn't be valid
            // If the value doesn't stick, we know there's input sanitization which infers a custom UI
            input.value = testData;

            // Set the style of the input element
            input.style.cssText = cssStyles;

            // If a range type
            if (reRange.test(inputType) && core.isDefined(input.style.WebkitAppearance)) {

                // Append the input element to the current document
                documentElem.appendChild(input);

                // Cache the defaultView
                var defaultView = document.defaultView;

                // Safari 2-4 allows the smiley as a value, despite making a slider
                isValid = defaultView.getComputedStyle &&

                    defaultView.getComputedStyle(input, null)
                    .WebkitAppearance !== 'textfield' &&

                    // The mobile Android web browser has a false positive, so
                    // check the height to see if the widget is actually there
                    (input.offsetHeight !== 0);

                documentElem.removeChild(input);

                // If a search or tel type
            } else if (reSearchTel.test(inputType)) {
                // Specification doesn't define any special parsing or detectable UI
                // behaviours so we pass these through as true

                // Interestingly, Opera fails the earlier test, so it doesn't
                // even make it here (I doubt anymore!)

                // If a email, number or url type
            } else if (reEmailNumberUrl.test(inputType)) {

                // The following types come with pre-backed validation
                isValid = input.checkValidity && input.checkValidity() === false;

                // For all other types check if the value has been sanitised
            } else {

                // If the upgraded input component rejects the :) text, we've got a winner
                isValid = input.value !== testData;

            }

            // Add to the internal object literal
            _inputs[inputType] = !!isValid;

        });
    }

    // PROMISE

    /**
     * Check if the Promise API exists
     *
     * Based on the concept by Modernizr URL: https://github.com/Modernizr/Modernizr/blob/master/feature-detects/es6/promises.js
     *
     * @return {boolean} True, the feature exists; otherwise, false
     */
    function hasPromise() {
        return _hasPromise;
    }

    // STORAGE

    /**
     * Check if the localStorage API exists
     *
     * Based on the concept by Modernizr, URL: https://github.com/Modernizr/Modernizr/blob/master/feature-detects/storage/localstorage.js
     *
     * @return {boolean} True, the feature exists; otherwise, false
     */
    function hasLocalStorage() {
        return _hasLocalStorage;
    }

    /**
     * Check if the sessionStorage API exists
     *
     * Based on the concept by Modernizr, URL: https://github.com/Modernizr/Modernizr/blob/master/feature-detects/storage/sessionstorage.js
     *
     * @return {boolean} True, the feature exists; otherwise, false
     */
    function hasSessionStorage() {
        return _hasSessionStorage;
    }

    /**
     * Check if the webStorage API exists
     *
     * Based on the concept by Modernizr, URL: https://github.com/Modernizr/Modernizr/blob/master/feature-detects/storage/
     *
     * @return {boolean} True, the feature exists; otherwise, false
     */
    function hasWebStorage() {
        return _hasWebStorage;
    }

    /**
     * Check if a CSS style is supported. Automatically checks for common vendor prefixes
     *
     * @param {string} property CSS property to check (without the vendor prefix)
     * @return {boolean} True, the style is supported; otherwise, false
     */
    function isStyleSupported(property) {
        if (!core.isString(property) || property.length === 0) {
            return false;
        }

        // Appears the style is supported
        if (!core.isUndefined(_html.style[property])) {
            return true;
        }

        // Check common vendor prefixes
        property = core.stringLCFirst(property);

        var length = _prefixes.length;
        while (length-- > 0) {
            if (!core.isUndefined(_html.style[_prefixes[length] + property])) {
                return true;
            }
        }

        return false;
    }

    /**
     * Check if a valid storage object
     *
     * @param {type} storage Storage object
     * @return {boolean} storage True, is valid storage object; otherwise, false
     */
    function _isStorage(storage) {
        return core.isObject(storage) &&
            'key' in storage &&
            'getItem' in storage &&
            'setItem' in storage &&
            'removeItem' in storage &&
            'clear' in storage;
    }

    // Public API
    return {
        init: init,
        destroy: destroy,
        getVersion: getVersion,
        hasCSSSupports: hasCSSSupports,
        hasGeoLocation: hasGeoLocation,
        hasHistory: hasHistory,
        hasInput: hasInput,
        hasLocalStorage: hasLocalStorage,
        hasPromise: hasPromise,
        hasSessionStorage: hasSessionStorage,
        hasWebStorage: hasWebStorage,
        isStyleSupported: isStyleSupported,
    };
})(window, window.document, window.jQuery, window.App.core);
<commit_msg>Added attribution<commit_after>/* global App */

/**
 * Features module
 *
 * HTML5 feature detection based on the concepts and ideas by Modernizr
 * @link http://html5please.com/
 * @link http://caniuse.com/
 * @link https://github.com/NielsLeenheer/html5test/
 *
 * Modified: 2015/12/06
 * @author softwarespot
 */
App.namespace('core').features = (function featuresModule(window, document, $, core, undefined) {
    // Constants

    // SemVer version number of the module
    var VERSION = '1.0.0';

    // Unique global identifier. Internal usage only
    // var GUID = '3B8C44B7-6A3B-4F84-A031-2D7B5D4ED211';

    // Fields

    // Store if the module has been initialised
    var _isInitialised = false;

    // Native functions
    var _nativeCSS = window.CSS;
    var _nativeHistory = window.history;
    var _nativeLocalStorage = window.localStorage;
    var _nativeNavigator = window.navigator;
    var _nativePromise = window.Promise;
    var _nativeSessionStorage = window.sessionStorage;

    // Store has* results
    // Note: Opera 12 supports window.supportsCSS according to caniuse.com
    var _hasCSSSupports = (core.isFunction(_nativeCSS) && core.isFunction(_nativeCSS.supports)) || window.supportsCSS;
    var _hasGeoLocation = core.isObject(_nativeNavigator) &&
        'geolocation' in _nativeNavigator;

    var _hasHistory = core.isObject(_nativeHistory) &&
        'pushState' in _nativeHistory;

    var _hasLocalStorage = _isStorage(_nativeLocalStorage);
    var _hasSessionStorage = _isStorage(_nativeSessionStorage);
    var _hasWebStorage = _hasLocalStorage && _hasSessionStorage;

    var _hasPromise = core.isFunction(_nativePromise) &&
        'all' in _nativePromise &&
        'race' in _nativePromise &&
        'reject' in _nativePromise &&
        'resolve' in _nativePromise;

    // Hold the input data, with the key being the input type and the value of either true or false as
    // whether or not it's supported by the following browser
    var _inputs = null;

    // Cache the HTML node
    var _html = document.documentElement;
    var _prefixes = ['Khtml', 'Moz', 'Ms', 'O', 'Webkit'];

    // Methods

    /**
     * Initialise the module
     *
     * @return {undefined}
     */
    function init() {
        if (_isInitialised) {
            return;
        }

        // Initialise the input object literal
        _getInputs();

        _isInitialised = true;
    }

    /**
     * Destroy the module
     *
     * @return {undefined}
     */
    function destroy() {
        _isInitialised = false;
    }

    /**
     * Get the version number of the module
     *
     * @returns {number} Version number
     */
    function getVersion() {
        return VERSION;
    }

    // CSS

    /**
     * Checl if CSSSupports exists
     *
     * @return {boolean} True, the feature exists; otherwise, false
     */
    function hasCSSSupports() {
        return _hasCSSSupports;
    }

    // EVENTS
    // https://github.com/Modernizr/Modernizr/blob/master/src/hasEvent.js
    // https://github.com/Modernizr/Modernizr/blob/master/feature-detects/hashchange.js

    // HISTORY

    /**
     * Check if the History API exists
     *
     * Based on the concept by Modernizr URL: https://github.com/Modernizr/Modernizr/blob/master/feature-detects/history.js
     *
     * @return {boolean} True, the feature exists; otherwise, false
     */
    function hasHistory() {
        return _hasHistory;
    }

    // GEOLOCATION

    /**
     * Check if the geolocation API exists
     *
     * Based on the concept by Modernizr, URL: https://github.com/Modernizr/Modernizr/blob/master/feature-detects/geolocation.js
     *
     * @return {boolean} True, the feature exists; otherwise, false
     */
    function hasGeoLocation() {
        return _hasGeoLocation;
    }

    // INPUTS

    /**
     * Check if an input type is supported
     *
     * @param {string} inputType Input type
     * @return {boolean} True the type is supported; otherwise, false
     */
    function hasInput(inputType) {
        // Coerce as a string
        var hasInputResult = _inputs[core.toString(inputType)];
        return core.isUndefined(hasInputResult) ? false : hasInputResult;
    }

    /**
     * Initialise the input object literal
     *
     * Based on the concept by Modernizr, URL: https://github.com/Modernizr/Modernizr/commits/master/feature-detects/inputtypes.js
     *
     * @return {undefined}
     */
    function _getInputs() {
        if (!core.isNull(_inputs)) {
            return;
        }

        // Regular expressions
        var reEmailNumberUrl = /^(?:email|number|url)$/;
        var reRange = /(?:^range$)/;
        var reSearchTel = /^(?:search|tel)$/;

        // Create an empty object literal
        _inputs = {};

        // Input types that will are split as an array
        var inputTypes = 'color date datetime datetime-local email month number range search tel time url week'.split(' ');

        // Create a temporary input element
        var input = document.createElement('input');

        // Document element to bind the input element to
        var documentElem = document.documentElement;

        // Inline stylesheet
        var cssStyles = 'position:absolute;visibility:hidden;';

        // Data to test with
        var testData = '=)';

        // Iterate through the array. A polyfill is available at
        // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Polyfill
        inputTypes.forEach(function forEachInputType(inputType) {

            // Set the attribute type of the input element
            input.setAttribute('type', inputType);

            // Check the type is not text and that it contains a 'style' property
            var isValid = input.type !== 'text' && 'style' in input;

            // If invalid then simply return and don't continue
            if (!isValid) {
                return;
            }

            // First check to see if the type we give it sticks
            // If the type does, we feed it a textual value, which shouldn't be valid
            // If the value doesn't stick, we know there's input sanitization which infers a custom UI
            input.value = testData;

            // Set the style of the input element
            input.style.cssText = cssStyles;

            // If a range type
            if (reRange.test(inputType) && core.isDefined(input.style.WebkitAppearance)) {

                // Append the input element to the current document
                documentElem.appendChild(input);

                // Cache the defaultView
                var defaultView = document.defaultView;

                // Safari 2-4 allows the smiley as a value, despite making a slider
                isValid = defaultView.getComputedStyle &&

                    defaultView.getComputedStyle(input, null)
                    .WebkitAppearance !== 'textfield' &&

                    // The mobile Android web browser has a false positive, so
                    // check the height to see if the widget is actually there
                    (input.offsetHeight !== 0);

                documentElem.removeChild(input);

                // If a search or tel type
            } else if (reSearchTel.test(inputType)) {
                // Specification doesn't define any special parsing or detectable UI
                // behaviours so we pass these through as true

                // Interestingly, Opera fails the earlier test, so it doesn't
                // even make it here (I doubt anymore!)

                // If a email, number or url type
            } else if (reEmailNumberUrl.test(inputType)) {

                // The following types come with pre-backed validation
                isValid = input.checkValidity && input.checkValidity() === false;

                // For all other types check if the value has been sanitised
            } else {

                // If the upgraded input component rejects the :) text, we've got a winner
                isValid = input.value !== testData;

            }

            // Add to the internal object literal
            _inputs[inputType] = !!isValid;

        });
    }

    // PROMISE

    /**
     * Check if the Promise API exists
     *
     * Based on the concept by Modernizr URL: https://github.com/Modernizr/Modernizr/blob/master/feature-detects/es6/promises.js
     *
     * @return {boolean} True, the feature exists; otherwise, false
     */
    function hasPromise() {
        return _hasPromise;
    }

    // STORAGE

    /**
     * Check if the localStorage API exists
     *
     * Based on the concept by Modernizr, URL: https://github.com/Modernizr/Modernizr/blob/master/feature-detects/storage/localstorage.js
     *
     * @return {boolean} True, the feature exists; otherwise, false
     */
    function hasLocalStorage() {
        return _hasLocalStorage;
    }

    /**
     * Check if the sessionStorage API exists
     *
     * Based on the concept by Modernizr, URL: https://github.com/Modernizr/Modernizr/blob/master/feature-detects/storage/sessionstorage.js
     *
     * @return {boolean} True, the feature exists; otherwise, false
     */
    function hasSessionStorage() {
        return _hasSessionStorage;
    }

    /**
     * Check if the webStorage API exists
     *
     * Based on the concept by Modernizr, URL: https://github.com/Modernizr/Modernizr/blob/master/feature-detects/storage/
     *
     * @return {boolean} True, the feature exists; otherwise, false
     */
    function hasWebStorage() {
        return _hasWebStorage;
    }

    /**
     * Check if a CSS style is supported. Automatically checks for common vendor prefixes
     * Idea by TutsPlus, URL: http://code.tutsplus.com/tutorials/quick-tip-detect-css3-support-in-browsers-with-javascript--net-16444
     *
     * @param {string} property CSS property to check (without the vendor prefix)
     * @return {boolean} True, the style is supported; otherwise, false
     */
    function isStyleSupported(property) {
        if (!core.isString(property) || property.length === 0) {
            return false;
        }

        // Appears the style is supported
        if (!core.isUndefined(_html.style[property])) {
            return true;
        }

        // Check common vendor prefixes
        property = core.stringLCFirst(property);

        var length = _prefixes.length;
        while (length-- > 0) {
            if (!core.isUndefined(_html.style[_prefixes[length] + property])) {
                return true;
            }
        }

        return false;
    }

    /**
     * Check if a valid storage object
     *
     * @param {type} storage Storage object
     * @return {boolean} storage True, is valid storage object; otherwise, false
     */
    function _isStorage(storage) {
        return core.isObject(storage) &&
            'key' in storage &&
            'getItem' in storage &&
            'setItem' in storage &&
            'removeItem' in storage &&
            'clear' in storage;
    }

    // Public API
    return {
        init: init,
        destroy: destroy,
        getVersion: getVersion,
        hasCSSSupports: hasCSSSupports,
        hasGeoLocation: hasGeoLocation,
        hasHistory: hasHistory,
        hasInput: hasInput,
        hasLocalStorage: hasLocalStorage,
        hasPromise: hasPromise,
        hasSessionStorage: hasSessionStorage,
        hasWebStorage: hasWebStorage,
        isStyleSupported: isStyleSupported,
    };
})(window, window.document, window.jQuery, window.App.core);
<|endoftext|>


<commit_before>(function (root, factory) {
  'use strict';

  if (typeof define === 'function' && define.amd) {
    define(factory);
  } else {
    root.nimble = factory();
  }
})(this, function () {
  'use strict';

  // Helper functions
  var newObjectRep = function(type, name, dataSerialization, data) {
    return {
      "type": type,
      "name": name,
      "data-serialization": dataSerialization,
      "data": data,
    };
  };

  var getElementsByXpath = function(path) {
    return document.evalue(path, document, null, XPathResult.ANY_TYPE, null);
  };

  return {
    dataDefaultsURL: chrome.extension.getURL('/defaults.json'),
    getData: function (callback) {
      var dataDefaultsPromise = $.getJSON(this.dataDefaultsURL, function (dataDefaults) {
        var result = [];

        var textSelection = window.getSelection();
        if (textSelection.type === "Range") {
          var text = textSelection.getRangeAt(0).toString();
          result.push(newObjectRep('text', 'Selected text', 'text', text));
        }

        if (document.URL in dataDefaults) {
          for (var i = 0; i < dataDefaults[document.URL].length; i++) {
            var spec = dataDefaults[document.URL][i];
            var elem = $(spec.selector).get(0);
            if (elem !== undefined) {
              result.push(elem);
            }
            // TODO: Returning a list
          }
        }
        result.push(newObjectRep('text', 'Current URL', 'text', document.URL));
        callback(result);
      });

      dataDefaultsPromise.fail(function (d, textStatus, error) {
        // TODO
      });
    },
  };
});
<commit_msg>Fixed getElementByXpath<commit_after>(function (root, factory) {
  'use strict';

  if (typeof define === 'function' && define.amd) {
    define(factory);
  } else {
    root.nimble = factory();
  }
})(this, function () {
  'use strict';

  // Helper functions
  var newObjectRep = function(type, name, dataSerialization, data) {
    return {
      "type": type,
      "name": name,
      "data-serialization": dataSerialization,
      "data": data,
    };
  };

  var getElementsByXpath = function(path) {
    return document.evaluate(path, document, null, XPathResult.ANY_TYPE, null);
  };

  return {
    dataDefaultsURL: chrome.extension.getURL('/defaults.json'),
    getData: function (callback) {
      var dataDefaultsPromise = $.getJSON(this.dataDefaultsURL, function (dataDefaults) {
        var result = [];

        var textSelection = window.getSelection();
        if (textSelection.type === "Range") {
          var text = textSelection.getRangeAt(0).toString();
          result.push(newObjectRep('text', 'Selected text', 'text', text));
        }

        if (document.URL in dataDefaults) {
          for (var i = 0; i < dataDefaults[document.URL].length; i++) {
            var spec = dataDefaults[document.URL][i];
            var elem = $(spec.selector).get(0);
            if (elem !== undefined) {
              result.push(elem);
            }
            // TODO: Returning a list
          }
        }
        result.push(newObjectRep('text', 'Current URL', 'text', document.URL));
        callback(result);
      });

      dataDefaultsPromise.fail(function (d, textStatus, error) {
        // TODO
      });
    },
  };
});
<|endoftext|>


<commit_before>(function(exports) {

	var Corpus = require('fielddb/api/corpus/ComputationalLinguisticsCorpus').ComputationalLinguisticsCorpus;
	Corpus.Orthography = {};
	Corpus.Orthography.Tokenizer = exports.Tokenizer || require('../lexicon/Tokenizer').Tokenizer;

	exports.Corpus = Corpus;

})(typeof exports === 'undefined' ? this : exports);
<commit_msg>loading fielddb if available<commit_after>(function(exports) {

	var Corpus =  exports.FieldDB ? exports.FieldDB.ComputationalLinguisticsCorpus : require('fielddb/api/corpus/ComputationalLinguisticsCorpus').ComputationalLinguisticsCorpus;
	Corpus.Orthography = {};
	Corpus.Orthography.Tokenizer = exports.Tokenizer || require('../lexicon/Tokenizer').Tokenizer;

	exports.Corpus = Corpus;

})(typeof exports === 'undefined' ? this : exports);
<|endoftext|>


<commit_before>// Legend Mod by Jimboy3100

//runs for agar.io
if (location.pathname == "/LMoldskins"){
eval(function(p,a,c,k,e,r){e=function(c){return(c35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('"k l";m(2(){2 e(){7 e=n.p("q"),t=9;r(e){s{t=u.v(e)}w(e){4.x(!1,e)}t&&t.5&&(y.z(t.5),4.A("%c[b] d B C...","D: E"))}}!2(t,a){7 o=3.F("G");o.H="I/J",o.K="L-8",o.6?o.f=2(){"d"!=o.6&&"M"!=o.6||(o.f=9,a&&a())}:(3.g&&3.g.N("O-h-i",t),a&&(o.P=a,o.Q=e)),o.5=t+"?R="+~~(S.T()/U/V),3.W("X")[0].Y(o)}("Z://10.11.12/13/j/h.i.j",2(){4.14("[b] 15 16...")})},0);',62,69,'||function|document|console|src|readyState|var||null||VANILLA||loaded||onreadystatechange|body|vanilla|core|js|use|strict|setTimeout|localStorage||getItem|cachedVanilla|if|try||JSON|parse|catch|assert|window|eval|log|from|cache|color|darkorange|createElement|script|type|text|javascript|charset|utf|complete|setAttribute|data|onload|onerror|ts|Date|now|1e3|60|getElementsByTagName|head|appendChild|http|imasters|org|ru|agar|info|inject|success'.split('|'),0,{}))
setTimeout(function() {

document.body.style.background = "#f3f3f3 url('https://jimboy3100.github.io/banners/iconmod3.png') no-repeat center fixed";
$( "body" ).append('

');
}, 3000);
setTimeout(function() {
$("#canvas").remove();
$("#adsBottom").remove();
$("#rightPanel").remove();
$("#skinButton").click();
$("#imagebig").remove();
$(".center-container").hide();
$("#dailyquests-panel").hide();
$("#overlays").hide();
$(".radio-module").hide();
$("#service-message-area").hide();
$("#leftPanel>div.agario-panel.agario-side-panel.agario-shop-panel").show();
$("#helloContainer").css("margin-left", "-150px");
$("#imagebig").remove();
}, 7000);
}
else if (location.host == "agar.io" && location.pathname == "/") {
	var oldskins = localStorage.getItem("oldskins");
    	if (oldskins=="true"){
        console.log("Old Skins enabled");
        localStorage.setItem("oldskins", "false");
        location.href = "http://agar.io/LMoldskins";
}
	else{
var cpickerCSS = '<link href="https://jimboy3100.github.io/bootstrap-colorpicker.min.css" rel="stylesheet"></link>';
var toastrCSS = '<link href="https://jimboy3100.github.io/toastr.min.css" rel="stylesheet"></link>';
var switchCSS = '<link href="https://jimboy3100.github.io/switchery.min.css" rel="stylesheet"></link>';
var rangeCSS = '<link href="https://jimboy3100.github.io/rangeslider.css" rel="stylesheet"></link>';
var perfectCSS = '<link href="https://jimboy3100.github.io/perfect-scrollbar.min.css" rel="stylesheet"></link>';
var faCSS = '<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"></link>';
var legendarioCSS = '<link href="http://cdn.ogario.ovh/v3/ogario.v3.css?v=339" rel="stylesheet"></link>';

var keyJS = '';
var cpickerJS = '';
var toastrJS = '';
var switchJS = '';
var rangeJS = '';
var perfectJS = '';
var legendJS = '';
var legendJSniffJS = '';
var legendJSniff2JS = '';
var legendJSniff3JS = '';
var legendarioSniffJS = '';
var legendarioJS = '';
var modVersion = "3.2";

var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListenerAgar);
oReq.open("GET", location.href);
oReq.send();
	}

}

//runs only for http://ext.fzogar.xyz/ogs settings
if (location.href == "http://ext.fzogar.xyz/ogs/") {
	var oReq = new XMLHttpRequest();
	oReq.addEventListener("load", reqListener);
	oReq.open("GET", location.href);
	oReq.send();
    setTimeout(function() {
    $("#login_form").append('Powered by http://fzogar.xyz/ogs');
    $("#Loadbtn").after('<input type="submit" id="sendInfo" class="btn btn-default " value="Apply Settings to Mod" style="margin-left: 7px;">');
//    $("#sendInfo").after('<input type="submit" id="sendInfo2" class="btn btn-default " value="Upload from Legend Mod" style="margin-left: 7px;">');
    $("#sendInfo").click(function() {
//        showpaste();
//        alert($("#jsonupdate").val());
        try{window.parent.postMessage("PostedOgarSettings1?datasent="+$("#jsonupdate").val(), "*");
        } catch (e) {}
    });

        }, 1100);
}

//runs only if play.google.com is a popup, doesnt if directly joined
if (location.host == "play.google.com") {
	window.close();
}

// Inject Chat Talky.io Userscript
if (location.host == "talky.io") {

	(function() {
    var link = document.querySelector("link[rel*='icon']") || document.createElement('link');
    link.type = 'image/x-icon';
    link.rel = 'shortcut icon';
    link.href = 'https://jimboy3100.github.io/banners/icon32croped.ico.gif';
    document.getElementsByTagName('head')[0].appendChild(link);
	})();

	document.title="Legend Mod - Talky";

    var url2 = window.location.href;
	url2 = url2.toLowerCase();
    var gamename = getParameterByName("name", url2);
    var IPAgario = getParameterByName("ip", url2);
    var IPtoken = getParameterByName("token", url2);

	if (window.location.href.indexOf("token") != -1){
	var oReq = new XMLHttpRequest();
	oReq.addEventListener("load", reqListener);
	oReq.open("GET", "https://talky.io/");
	oReq.send();
	}
	else{
	var oReq = new XMLHttpRequest();
	oReq.addEventListener("load", reqListener);
	oReq.open("GET", location.href);
	oReq.send();
	}
    setTimeout(function() {
       // document.getElementsByClassName('text__NUZ8yEiB TalkyButton__text _2jD5C')[0].click();
        document.getElementById('join').click();
    }, 4000);

    setTimeout(function() {
        document.getElementsByClassName('create-room-form-input')[0].value = IPtoken;
	//document.getElementById('join').click();
        document.getElementsByClassName('create-room-form-button button button-default button-undefined')[0].click();
        document.getElementById('skip').click();
        document.getElementsByClassName('TalkyButton__text')[0].click();
    }, 2000);
    setTimeout(function() {
        document.getElementsByClassName('SDuUr')[1].value = gamename;
        //Legend Mod Copy Agar.io Token

		if (IPAgario.length==6){
		document.getElementsByClassName('_24sME message message-info message-full-width')[0].before("[Talky.io]: Legend Mod. Server: " + "http://agar.io/#" + IPAgario + " . [PARTY] (Password rooms are different than Public)");}
		else{
		document.getElementsByClassName('_24sME message message-info message-full-width')[0].before("[Talky.io]: Legend Mod. Server: " + "http://agar.io/?sip=" + IPAgario + " . (Password rooms are different than Public)");}

        document.getElementsByClassName('_1U4l9qYTHl6ExTsW9IvwnO')[1].value = gamename;
        document.getElementsByClassName('message message-info message-full-width')[0].style.visibility = 'hidden';
        document.getElementsByClassName('_24sME message message-info message-full-width')[0].remove();
        document.getElementsByClassName('Box _3-HLf')[0].remove();

    }, 6000);
}

//example: https://talky.io/dddd?name=&?ip=

function reqListenerAgar () {
    var doc=this.responseText;
    window.stop();
    document.documentElement.innerHTML = "";
    document.open();
    document.write(doc);
  //console.log(this.responseText);
            document.write("", legendarioSniffJS + cpickerCSS + toastrCSS + switchCSS + rangeCSS + perfectCSS + legendarioCSS + faCSS + cpickerJS + toastrJS + switchJS + rangeJS + perfectJS + keyJS + legendJSniff2JS + "");
            document.write("", legendJSniffJS + "</body");
            setTimeout(function() {
            document.write("", legendarioJS + legendJS + legendJSniff3JS +  "" + "");

            document.close();
                }, 1500);
}

function reqListener () {
    var doc=this.responseText;
    window.stop();
    document.documentElement.innerHTML = "";
    document.open();
    document.write(doc);
    document.close();
}

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

//End of Legend Mod
<commit_msg>Update extension.js<commit_after>// Legend Mod by Jimboy3100

//runs for agar.io
if (location.pathname == "/LMoldskins"){
eval(function(p,a,c,k,e,r){e=function(c){return(c35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('"k l";m(2(){2 e(){7 e=n.p("q"),t=9;r(e){s{t=u.v(e)}w(e){4.x(!1,e)}t&&t.5&&(y.z(t.5),4.A("%c[b] d B C...","D: E"))}}!2(t,a){7 o=3.F("G");o.H="I/J",o.K="L-8",o.6?o.f=2(){"d"!=o.6&&"M"!=o.6||(o.f=9,a&&a())}:(3.g&&3.g.N("O-h-i",t),a&&(o.P=a,o.Q=e)),o.5=t+"?R="+~~(S.T()/U/V),3.W("X")[0].Y(o)}("Z://10.11.12/13/j/h.i.j",2(){4.14("[b] 15 16...")})},0);',62,69,'||function|document|console|src|readyState|var||null||VANILLA||loaded||onreadystatechange|body|vanilla|core|js|use|strict|setTimeout|localStorage||getItem|cachedVanilla|if|try||JSON|parse|catch|assert|window|eval|log|from|cache|color|darkorange|createElement|script|type|text|javascript|charset|utf|complete|setAttribute|data|onload|onerror|ts|Date|now|1e3|60|getElementsByTagName|head|appendChild|http|imasters|org|ru|agar|info|inject|success'.split('|'),0,{}))
setTimeout(function() {

document.body.style.background = "#f3f3f3 url('https://jimboy3100.github.io/banners/iconmod3.png') no-repeat center fixed";
$( "body" ).append('

');
}, 3000);
setTimeout(function() {
$("#canvas").remove();
$("#adsBottom").remove();
$("#rightPanel").remove();
$("#skinButton").click();
$("#imagebig").remove();
$(".center-container").hide();
$("#dailyquests-panel").hide();
$("#overlays").hide();
$(".radio-module").hide();
$("#service-message-area").hide();
$("#leftPanel>div.agario-panel.agario-side-panel.agario-shop-panel").show();
$("#helloContainer").css("margin-left", "-150px");
$("#imagebig").remove();
}, 7000);
}
else if (location.host == "agar.io" && location.pathname == "/") {
	var oldskins = localStorage.getItem("oldskins");
    	if (oldskins=="true"){
        console.log("Old Skins enabled");
        localStorage.setItem("oldskins", "false");
        location.href = "http://agar.io/LMoldskins";
}
	else{
var cpickerCSS = '<link href="https://jimboy3100.github.io/bootstrap-colorpicker.min.css" rel="stylesheet"></link>';
var toastrCSS = '<link href="https://jimboy3100.github.io/toastr.min.css" rel="stylesheet"></link>';
var switchCSS = '<link href="https://jimboy3100.github.io/switchery.min.css" rel="stylesheet"></link>';
var rangeCSS = '<link href="https://jimboy3100.github.io/rangeslider.css" rel="stylesheet"></link>';
var perfectCSS = '<link href="https://jimboy3100.github.io/perfect-scrollbar.min.css" rel="stylesheet"></link>';
var faCSS = '<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"></link>';
var legendarioCSS = '<link href="http://cdn.ogario.ovh/v3/ogario.v3.css?v=339" rel="stylesheet"></link>';

var keyJS = '';
var cpickerJS = '';
var toastrJS = '';
var switchJS = '';
var rangeJS = '';
var perfectJS = '';
var legendJS = '';
var legendJSniffJS = '';
var legendJSniff2JS = '';
var legendJSniff3JS = '';
var legendarioSniffJS = '';
var legendarioJS = '';
var modVersion = "3.2";

var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListenerAgar);
oReq.open("GET", location.href);
oReq.send();
	}

}

//runs only for http://ext.fzogar.xyz/ogs settings
if (location.href == "http://ext.fzogar.xyz/ogs/") {
	var oReq = new XMLHttpRequest();
	oReq.addEventListener("load", reqListener);
	oReq.open("GET", location.href);
	oReq.send();
    setTimeout(function() {
    $("#login_form").append('Powered by http://fzogar.xyz/ogs');
    $("#Loadbtn").after('<input type="submit" id="sendInfo" class="btn btn-default " value="Apply Settings to Mod" style="margin-left: 7px;">');
//    $("#sendInfo").after('<input type="submit" id="sendInfo2" class="btn btn-default " value="Upload from Legend Mod" style="margin-left: 7px;">');
    $("#sendInfo").click(function() {
//        showpaste();
//        alert($("#jsonupdate").val());
        try{window.parent.postMessage("PostedOgarSettings1?datasent="+$("#jsonupdate").val(), "*");
        } catch (e) {}
    });

        }, 1100);
}

//runs only if play.google.com is a popup, doesnt if directly joined
if (location.host == "play.google.com") {
	window.close();
}

// Inject Chat Talky.io Userscript
if (location.host == "talky.io") {

	(function() {
    var link = document.querySelector("link[rel*='icon']") || document.createElement('link');
    link.type = 'image/x-icon';
    link.rel = 'shortcut icon';
    link.href = 'https://jimboy3100.github.io/banners/icon32croped.ico.gif';
    document.getElementsByTagName('head')[0].appendChild(link);
	})();

	document.title="Legend Mod - Talky";

    var url2 = window.location.href;
	url2 = url2.toLowerCase();
    var gamename = getParameterByName("name", url2);
    var IPAgario = getParameterByName("ip", url2);
    var IPtoken = getParameterByName("token", url2);

	if (window.location.href.indexOf("token") != -1){
	var oReq = new XMLHttpRequest();
	oReq.addEventListener("load", reqListener);
	oReq.open("GET", "https://talky.io/");
	oReq.send();
	}
	else{
	var oReq = new XMLHttpRequest();
	oReq.addEventListener("load", reqListener);
	oReq.open("GET", location.href);
	oReq.send();
	}
    setTimeout(function() {
       // document.getElementsByClassName('text__NUZ8yEiB TalkyButton__text _2jD5C')[0].click();
        document.getElementById('join').click();
    }, 4000);

    setTimeout(function() {
        document.getElementsByClassName('create-room-form-input')[0].value = IPtoken;
	//document.getElementById('join').click();
        document.getElementsByClassName('create-room-form-button button button-default button-undefined')[0].click();
        document.getElementById('skip').click();
        document.getElementsByClassName('TalkyButton__text')[0].click();
    }, 2000);
    setTimeout(function() {
        document.getElementsByClassName('SDuUr')[1].value = gamename;
        //Legend Mod Copy Agar.io Token

		if (IPAgario.length==6){
		document.getElementsByClassName('_24sME message message-info message-full-width')[0].before("[Talky.io]: Legend Mod. Server: " + "http://agar.io/#" + IPAgario + " . [PARTY] (Password rooms are different than Public)");}
		else{
		document.getElementsByClassName('_24sME message message-info message-full-width')[0].before("[Talky.io]: Legend Mod. Server: " + "http://agar.io/?sip=" + IPAgario + " . (Password rooms are different than Public)");}

        document.getElementsByClassName('_1U4l9qYTHl6ExTsW9IvwnO')[1].value = gamename;
        document.getElementsByClassName('message message-info message-full-width')[0].style.visibility = 'hidden';
        document.getElementsByClassName('_24sME message message-info message-full-width')[0].remove();
        document.getElementsByClassName('Box _3-HLf')[0].remove();

    }, 6000);
}

//example: https://talky.io/dddd?name=&?ip=

function reqListenerAgar () {
    var doc=this.responseText;
    window.stop();
    document.documentElement.innerHTML = "";
    document.open();
    document.write(doc);
  //console.log(this.responseText);
            document.write("", legendarioSniffJS + cpickerCSS + toastrCSS + switchCSS + rangeCSS + perfectCSS + legendarioCSS + faCSS + cpickerJS + toastrJS + switchJS + rangeJS + perfectJS + keyJS + legendJSniff2JS + "");
            document.write("", legendJSniffJS + "</body");
            setTimeout(function() {
            document.write("", legendarioJS + legendJS + legendJSniff3JS +  "" + "");

            document.close();
                }, 2500);
}

function reqListener () {
    var doc=this.responseText;
    window.stop();
    document.documentElement.innerHTML = "";
    document.open();
    document.write(doc);
    document.close();
}

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

//End of Legend Mod
<|endoftext|>


<commit_before>function removeSpaces()
{
	/*
	var img = document.createElement("img");
	img.src = "http://www.emoji-cheat-sheet.com/graphics/emojis/" + document.getElementById('comment').text + ".png";

*/
		alert("http://www.emoji-cheat-sheet.com/graphics/emojis/" + document.getElementById('comment').value + ".png")

	var img = document.createElement("img");

	var wee = "http://www.emoji-cheat-sheet.com/graphics/emojis/smile.png";

	$('#output').prepend('<img id="img" src=wee />')

}<commit_msg>added :diamond_shape_with_a_dot_inside:<commit_after>function removeSpaces()
{
	/*
		var img = document.createElement("img");
		img.src = "http://www.emoji-cheat-sheet.com/graphics/emojis/" + document.getElementById('comment').text + ".png";
	*/

	var wee = "http://www.emoji-cheat-sheet.com/graphics/emojis/" + document.getElementById('comment').value + ".png";

	var img = document.createElement("img");
	img.src = wee

	var src = document.getElementById("wooloo")

	src.appendChild(img)
	alert(wee)

}<|endoftext|>


<commit_before>// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
const vscode = require('vscode');
const { spawn } = require("child_process");
const { create } = require('domain');
const { textChangeRangeNewSpan } = require('typescript');
const path = require("path");

// this method is called when your extension is activated
// your extension is activated the very first time the command is executed

/**
 * @param {vscode.ExtensionContext} context
 */
function activate(context) {

	async function spawnChild(command, cb) {
		const process = await spawn("howdoi", [command, '-n 3']);
		let result = []
		process.stdout.on("data", data => {

			result.push(String(data));

		});

		process.stderr.on("data", data => {
			console.log(`stderr: ${data}`);
		});

		process.on('error', (error) => {
			console.log(`error: ${error.message}`);
		});

		process.on("close", code => {
			console.log(`child process exited with code ${code}`);
			cb(result);
		});

	}

	function spliceArr(obj) {

		let dataString = String(obj);
		let lines = dataString.split('\n'+'================================================================================' + '\n');

		let newArr = lines.map((elem) => elem.split(' ★'));

		return newArr
	}

	function helperFunc(editor, myArr, userTxt) {

		const newResult = spliceArr(myArr);

		const quickPick = vscode.window.createQuickPick();
			quickPick.items = newResult.map(x => ({label: x[1], link: x[0]}));

			quickPick.onDidChangeSelection(([item]) => {
				// item.answer
				if (item) {

				editor.edit(edit => {
					edit.replace(editor.selection, userTxt + '\n' + item.link + item.label);
					// 								item.text + \n + item.link + \n + item.answer
				});
				quickPick.dispose();
				}
			});
			quickPick.onDidHide(() => quickPick.dispose());
			quickPick.show();
	}
	function modifyCommentedText(textToBeModified){
		var regexBegins =  /^[!@#<>/\$%\^\&*\)\(+=._-]+/
		var regexEnds = /[!@#<>/\$%\^\&*\)\(+=._-]+$/

			if (textToBeModified.match(regexBegins) && textToBeModified.match(regexEnds)){
				textToBeModified = textToBeModified.replace(regexBegins, '')
				textToBeModified = textToBeModified.replace(regexEnds, '')
			}
			else if(textToBeModified.match(regexEnds)){
				textToBeModified = textToBeModified.replace(regexEnds, '')
			}
			else if(textToBeModified.match(regexBegins)){
				textToBeModified = textToBeModified.replace(regexBegins, '')
			}

		return textToBeModified
	}
	function determineCommentStyle(currentlyOpenTabfileName){
	   var fileType = currentlyOpenTabfileName.substring(currentlyOpenTabfileName.lastIndexOf('.')+1, currentlyOpenTabfileName.length) || currentlyOpenTabfileName;

	   console.log("This is the filetype" + fileType)

	   var commentStyleTop = " "
	   if(fileType.equal("py")){
		  commentStyleTop = " ''' "
	   }
	   else if(fileType.equal("java")){
		   commentStyleTop = "/*"
	   }
	   else if(fileType.equal("txt")){
		   commentStyleTop = " "
	   }
	   console.log("none of it" + commentStyleTop)
		return fileType
		//will/should return the comment style instead but using filetype as a placeholder for now
	}

	function getFileName(){
		var currentlyOpenTabfilePath = vscode.window.activeTextEditor.document.uri.fsPath;
		var currentlyOpenTabfileName = path.basename(currentlyOpenTabfilePath);
		console.log( "path"+ currentlyOpenTabfilePath)
		console.log("name that will be passed to determine commentstyle" + currentlyOpenTabfileName)

		//var style = determineCommentStyle(currentlyOpenTabfileName)

	   return currentlyOpenTabfileName

	}

	// The command has been defined in the package.json file
	// Now provide the implementation of the command with  registerCommand
	// The commandId parameter must match the command field in package.json
	let disposable = vscode.commands.registerCommand('howdoi.extension', function () {
		// The code you place here will be executed every time your command is executed
		const editor = vscode.window.activeTextEditor;
		if (!editor) {
			vscode.window.showInformationMessage('create a file to enable howdoi');
			return;
		}

		var nameOfFile = getFileName()
		var commentStyle = determineCommentStyle(nameOfFile)

		//and then pass it to the async function alongside the highlighted text so that it can be used to
		//output something correctly

		var textToBeModified = editor.document.getText(editor.selection);
		var textToBeSearched = modifyCommentedText(textToBeModified)

		spawnChild(textToBeSearched, function(myArr) {
			helperFunc(editor, myArr, textToBeSearched);
		});

	});

	context.subscriptions.push(disposable);
}
exports.activate = activate;

// this method is called when your extension is deactivated
function deactivate() {}

module.exports = {
	activate,
	deactivate
}
<commit_msg>howdoi query enabled<commit_after>// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
const vscode = require('vscode');
const { spawn } = require("child_process");
// const { create } = require('domain');
// const { textChangeRangeNewSpan } = require('typescript');
const path = require("path");

// this method is called when your extension is activated
// your extension is activated the very first time the command is executed

/**
 * @param {vscode.ExtensionContext} context
 */
function activate(context) {

	async function spawnChild(command, cb) {
		const updatedCommand = howdoiPrefix(command);
		const process = await spawn("howdoi", [updatedCommand, '-n 3']);
		let result = [];
		process.stdout.on("data", data => {

			result.push(String(data));

		});

		process.stderr.on("data", data => {
			console.log(`stderr: ${data}`);
		});

		process.on('error', (error) => {
			console.log(`error: ${error.message}`);
		});

		process.on("close", code => {
			console.log(`child process exited with code ${code}`);
			cb(result);
		});

	}

	function spliceArr(obj) {

		let dataString = String(obj);
		let lines = dataString.split('\n'+'================================================================================' + '\n');

		let newArr = lines.map((elem) => elem.split(' ★'));

		return newArr
	}

	function helperFunc(editor, myArr, userTxt) {

		const newResult = spliceArr(myArr);

		const quickPick = vscode.window.createQuickPick();
			quickPick.items = newResult.map(x => ({label: x[1], link: x[0]}));

			quickPick.onDidChangeSelection(([item]) => {
				// item.answer
				if (item) {

				editor.edit(edit => {
					edit.replace(editor.selection, userTxt + '\n' + item.link + item.label);
					// 								item.text + \n + item.link + \n + item.answer
				});
				quickPick.dispose();
				}
			});
			quickPick.onDidHide(() => quickPick.dispose());
			quickPick.show();
	}

	function howdoiPrefix(command) {
		const prefix = "howdoi";

		if (command.includes(prefix)) {
			const newCommand = command.replace(prefix,'');
			console.log('prefix', newCommand);
			return newCommand;
		}
		else {
			console.log('NOprefix');
			return command
		}

	}

	function modifyCommentedText(textToBeModified) {
		var regexBegins =  /^[!@#<>/\$%\^\&*\)\(+=._-]+/
		var regexEnds = /[!@#<>/\$%\^\&*\)\(+=._-]+$/

			if (textToBeModified.match(regexBegins) && textToBeModified.match(regexEnds)){
				textToBeModified = textToBeModified.replace(regexBegins, '');
				textToBeModified = textToBeModified.replace(regexEnds, '');
			}
			else if(textToBeModified.match(regexEnds)){
				textToBeModified = textToBeModified.replace(regexEnds, '');
			}
			else if(textToBeModified.match(regexBegins)){
				textToBeModified = textToBeModified.replace(regexBegins, '');
			}

		return textToBeModified;
	}
	// function determineCommentStyle(currentlyOpenTabfileName){
	//    var fileType = currentlyOpenTabfileName.substring(currentlyOpenTabfileName.lastIndexOf('.')+1, currentlyOpenTabfileName.length) || currentlyOpenTabfileName;

	//    console.log("This is the filetype" + fileType);

	//    var commentStyleTop = " ";
	//    if(fileType.equal("py")){
	// 	  commentStyleTop = " ''' ";
	//    }
	//    else if(fileType.equal("java")){
	// 	   commentStyleTop = "/*";
	//    }
	//    else if(fileType.equal("txt")){
	// 	   commentStyleTop = " ";
	//    }
	//    console.log("none of it" + commentStyleTop);
	// 	return fileType;
	// 	//will/should return the comment style instead but using filetype as a placeholder for now
	// }

	function getFileName(){
		var currentlyOpenTabfilePath = vscode.window.activeTextEditor.document.uri.fsPath;
		var currentlyOpenTabfileName = path.basename(currentlyOpenTabfilePath);
		console.log( "path"+ currentlyOpenTabfilePath);
		console.log("name that will be passed to determine commentstyle" + currentlyOpenTabfileName);

		//var style = determineCommentStyle(currentlyOpenTabfileName)

	   return currentlyOpenTabfileName;

	}

	// The command has been defined in the package.json file
	// Now provide the implementation of the command with  registerCommand
	// The commandId parameter must match the command field in package.json
	let disposable = vscode.commands.registerCommand('howdoi.extension', function () {
		// The code you place here will be executed every time your command is executed
		const editor = vscode.window.activeTextEditor;
		if (!editor) {
			vscode.window.showInformationMessage('create a file to enable howdoi');
			return;
		}

		const nameOfFile = getFileName();
		console.log('nameoffile:', nameOfFile);
		// const commentStyle = determineCommentStyle(nameOfFile);
		// console.log('commentstyle:', commentStyle);
		//and then pass it to the async function alongside the highlighted text so that it can be used to
		//output something correctly

		const textToBeModified = editor.document.getText(editor.selection);
		const textToBeSearched = modifyCommentedText(textToBeModified);

		spawnChild(textToBeSearched, function(myArr) {
			helperFunc(editor, myArr, textToBeSearched);
		});

	});

	context.subscriptions.push(disposable);
}
exports.activate = activate;

// this method is called when your extension is deactivated
function deactivate() {}

module.exports = {
	activate,
	deactivate
}
<|endoftext|>


<commit_before>'use strict';

const express = require('express');
const app = express();
const port = 80;
const httpsPort = 443;
const https = require('https');
const forge = require('node-forge');

let f = require('../../net2/Firewalla.js');

const httpsOptions = genHttpsOptions();

app.use('*', (req, res) => {
  let txt = `Ads Blocked by Firewalla: ${req.ip} => ${req.method}: ${req.hostname}${req.originalUrl}`;
  res.send(txt);
  console.log(txt);
});

app.listen(port, () => console.log(`Httpd istening on port ${port}!`));

https.createServer(httpsOptions, app).listen(httpsPort, () => console.log(`Httpd istening on port ${httpsPort}!`));

function genHttpsOptions() {
// generate a keypair and create an X.509v3 certificate
  const pki = forge.pki;
  console.log('Generating 1024-bit key-pair...');
  const keys = pki.rsa.generateKeyPair(1024);
  console.log('Key-pair created.');

  console.log('Creating self-signed certificate...');
  const cert = pki.createCertificate();
  cert.publicKey = keys.publicKey;
  cert.serialNumber = '01';
  cert.validity.notBefore = new Date();
  cert.validity.notAfter = new Date();
  cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + 1);
  let attrs = [{
    name: 'commonName',
    value: 'blackhole.firewalla.com'
  }, {
    name: 'countryName',
    value: 'US'
  }, {
    shortName: 'ST',
    value: 'New York'
  }, {
    name: 'localityName',
    value: 'Brooklyn'
  }, {
    name: 'organizationName',
    value: 'BLACKHOLE'
  }, {
    shortName: 'OU',
    value: 'BLACKHOLE'
  }];
  cert.setSubject(attrs);
  cert.setIssuer(attrs);
  cert.setExtensions([{
    name: 'basicConstraints',
    cA: true/*,
  pathLenConstraint: 4*/
  }, {
    name: 'keyUsage',
    keyCertSign: true,
    digitalSignature: true,
    nonRepudiation: true,
    keyEncipherment: true,
    dataEncipherment: true
  }, {
    name: 'extKeyUsage',
    serverAuth: true,
    clientAuth: true,
    codeSigning: true,
    emailProtection: true,
    timeStamping: true
  }, {
    name: 'nsCertType',
    client: true,
    server: true,
    email: true,
    objsign: true,
    sslCA: true,
    emailCA: true,
    objCA: true
  }]);
  cert.sign(keys.privateKey);
  console.log('Certificate created.');

  return {
    key: pki.privateKeyToPem(keys.privateKey),
    cert: pki.certificateToPem(cert)
  };
}<commit_msg>remove unnecessary deps to reduce memory footprint<commit_after>'use strict';

const express = require('express');
const app = express();
const port = 80;
const httpsPort = 443;
const https = require('https');
const forge = require('node-forge');

const httpsOptions = genHttpsOptions();

app.use('*', (req, res) => {
  let txt = `Ads Blocked by Firewalla: ${req.ip} => ${req.method}: ${req.hostname}${req.originalUrl}`;
  res.send(txt);
  console.log(txt);
});

app.listen(port, () => console.log(`Httpd istening on port ${port}!`));

https.createServer(httpsOptions, app).listen(httpsPort, () => console.log(`Httpd istening on port ${httpsPort}!`));

function genHttpsOptions() {
// generate a keypair and create an X.509v3 certificate
  const pki = forge.pki;
  console.log('Generating 1024-bit key-pair...');
  const keys = pki.rsa.generateKeyPair(1024);
  console.log('Key-pair created.');

  console.log('Creating self-signed certificate...');
  const cert = pki.createCertificate();
  cert.publicKey = keys.publicKey;
  cert.serialNumber = '01';
  cert.validity.notBefore = new Date();
  cert.validity.notAfter = new Date();
  cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + 1);
  let attrs = [{
    name: 'commonName',
    value: 'blackhole.firewalla.com'
  }, {
    name: 'countryName',
    value: 'US'
  }, {
    shortName: 'ST',
    value: 'New York'
  }, {
    name: 'localityName',
    value: 'Brooklyn'
  }, {
    name: 'organizationName',
    value: 'BLACKHOLE'
  }, {
    shortName: 'OU',
    value: 'BLACKHOLE'
  }];
  cert.setSubject(attrs);
  cert.setIssuer(attrs);
  cert.setExtensions([{
    name: 'basicConstraints',
    cA: true/*,
  pathLenConstraint: 4*/
  }, {
    name: 'keyUsage',
    keyCertSign: true,
    digitalSignature: true,
    nonRepudiation: true,
    keyEncipherment: true,
    dataEncipherment: true
  }, {
    name: 'extKeyUsage',
    serverAuth: true,
    clientAuth: true,
    codeSigning: true,
    emailProtection: true,
    timeStamping: true
  }, {
    name: 'nsCertType',
    client: true,
    server: true,
    email: true,
    objsign: true,
    sslCA: true,
    emailCA: true,
    objCA: true
  }]);
  cert.sign(keys.privateKey);
  console.log('Certificate created.');

  return {
    key: pki.privateKeyToPem(keys.privateKey),
    cert: pki.certificateToPem(cert)
  };
}<|endoftext|>


<commit_before>// Copyright 2012, 2013 Patrick Wang <kk1fff@patrickz.net>
//
// 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.

//  1. Create a folder in output dir, with the name is the new photo name.
//  2. Resize the photo into the photo folder.
//  3. Read add additional information (EXIF) and write to the photo folder.
//  4. Generate page for that photo.

var crypto        = require('crypto'),
    EventEmitter  = require('events').EventEmitter,
    mkdirp        = require('mkdirp'),
    ii            = require('./imagemagick-interface.js'),
    ei            = require('./exiftool-interface.js'),
    generatePage  = require('./template-interface.js').generatePage,
    config        = null;

function generatePhotoPage(pi) {
  var generatingPage = generatePage('photo.html', pi);
  generatingPage.on('ok', function(page) {
    console.log('Page is generated: ' + (pi.title || "for " + pi.originalFileName));
    if (config.debug)
      console.log('Page is generated: ' + page);
    fs.writeFile(pi.photoDir + '/index.html', page, 'utf8', function(err) {
      if (err) {
        pi.e.emit('error', err);
      } else {
        pi.e.emit('ok', pi.newName);
      }
    });
  });
  generatingPage.on('error', function(err) {
    pi.e.emit('error', err);
  });
}

// Resize to specified size.
function shrink(sizeArray, pi) {
  var waitingShrinking = 0;
  var e = new EventEmitter();
  function onShrunk() {
    waitingShrinking--;
    if (waitingShrinking == 0) {
      e.emit('ok');
    }
  }
  sizeArray.forEach(function (size) {
    waitingShrinking++;
    console.log("Shrink " + pi.originalPhoto + " to " + size + "px");
    var ee = ii.shrinkSize(size, pi.originalPhoto, pi.photoDir + "/" + size + ".jpg");
    ee.on('ok', function() {
      onShrunk();
    });
    ee.on('error', function(err) {
      console.error(err);
      e.emit('error', err);
      onShrunk();
    });
  });

  return e;
};

function getExif(pi) {
  var ee = ei.getExif(pi.originalPhoto);
  ee.on('ok', function(exif) {
    if (exif) {
      pi.exif = exif;
    }
    generatePhotoPage(pi);
  });
  ee.on('error', function(err) {
    pi.e.emit('error', err);
  });
}

function createPhotoDir(pi) {
  fs.mkdir(pi.photoDir, "755", function(err) {
    if (err) {
      // This photo is already be used in other album. It's ok, we can skip
      // all futher file operations to this file.
      if (err.code == 'EEXIST') {
        pi.e.emit('ok', pi.newName);
        return;
      }

      pi.e.emit('error', err);
      return;
    }

    // Right now we have a folder for the picture, we will create shrunk
    // version and web page and place them into this folder.
    var shrinking = shrink(config.imageSizes, pi);
    shrinking.on('ok', function() {
      getExif(pi);
    });
    shrinking.on('error', function(err) {
      pi.e.emit('error', err);
    });
  });
};

exports.processPhoto = function processPhoto(albumPath, photoFileName, title, desc) {
  var e = new EventEmitter(),
      originalPhoto = albumPath + "/" + photoFileName,
      photoInfo = {
        title: title,
        desc: desc,
        originalPhoto: originalPhoto,
        originalFileName: photoFileName,
        e: e,
        page: {
          title: title
        }
      },
      sha1 = crypto.createHash('sha1'),
      stream = fs.createReadStream(originalPhoto);

  // Lazy initialize.
  if (!config) {
    config = require('./config.js').getCachedConfig();
  }

  // We take title and desc into hash code, so the same photos but with different
  // titles and descs will be different folder.
  if (title) sha1.update(title);
  if (desc) sha1.update(desc);

  stream.on('data', function(d) {
    sha1.update(d);
  });
  stream.on('end', function() {
    photoInfo.newName = "photo-" + sha1.digest('hex');
    photoInfo.photoDir = config.outputDir + '/' + photoInfo.newName;
    createPhotoDir(photoInfo);
  });
  stream.on('error', function(err) {
    e.emit('error', err);
  });

  return e;
}
<commit_msg>New name is an I/O bound operation, use a queue to limit maximum concurrent operation<commit_after>// Copyright 2012, 2013 Patrick Wang <kk1fff@patrickz.net>
//
// 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.

//  1. Create a folder in output dir, with the name is the new photo name.
//  2. Resize the photo into the photo folder.
//  3. Read add additional information (EXIF) and write to the photo folder.
//  4. Generate page for that photo.

var crypto        = require('crypto'),
    EventEmitter  = require('events').EventEmitter,
    mkdirp        = require('mkdirp'),
    ii            = require('./imagemagick-interface.js'),
    ei            = require('./exiftool-interface.js'),
    generatePage  = require('./template-interface.js').generatePage,
    config        = null,
    newNameQueue       = [],
    runningNewNameTask = 0,
    newNameTaskLimit   = 5;

function generatePhotoPage(pi) {
  var generatingPage = generatePage('photo.html', pi);
  generatingPage.on('ok', function(page) {
    console.log('Page is generated: ' + (pi.title || "for " + pi.originalFileName));
    if (config.debug)
      console.log('Page is generated: ' + page);
    fs.writeFile(pi.photoDir + '/index.html', page, 'utf8', function(err) {
      if (err) {
        pi.e.emit('error', err);
      } else {
        pi.e.emit('ok', pi.newName);
      }
    });
  });
  generatingPage.on('error', function(err) {
    pi.e.emit('error', err);
  });
}

// Resize to specified size.
function shrink(sizeArray, pi) {
  var waitingShrinking = 0;
  var e = new EventEmitter();
  function onShrunk() {
    waitingShrinking--;
    if (waitingShrinking == 0) {
      e.emit('ok');
    }
  }
  sizeArray.forEach(function (size) {
    waitingShrinking++;
    console.log("Shrink " + pi.originalPhoto + " to " + size + "px");
    var ee = ii.shrinkSize(size, pi.originalPhoto, pi.photoDir + "/" + size + ".jpg");
    ee.on('ok', function() {
      onShrunk();
    });
    ee.on('error', function(err) {
      console.error(err);
      e.emit('error', err);
      onShrunk();
    });
  });

  return e;
};

function getExif(pi) {
  var ee = ei.getExif(pi.originalPhoto);
  ee.on('ok', function(exif) {
    if (exif) {
      pi.exif = exif;
    }
    generatePhotoPage(pi);
  });
  ee.on('error', function(err) {
    pi.e.emit('error', err);
  });
}

function createPhotoDir(pi) {
  fs.mkdir(pi.photoDir, "755", function(err) {
    if (err) {
      // This photo is already be used in other album. It's ok, we can skip
      // all futher file operations to this file.
      if (err.code == 'EEXIST') {
        pi.e.emit('ok', pi.newName);
        return;
      }

      pi.e.emit('error', err);
      return;
    }

    // Right now we have a folder for the picture, we will create shrunk
    // version and web page and place them into this folder.
    var shrinking = shrink(config.imageSizes, pi);
    shrinking.on('ok', function() {
      getExif(pi);
    });
    shrinking.on('error', function(err) {
      pi.e.emit('error', err);
    });
  });
};

function getNewName(photoInfo) {

  function done() {
    runningNewNameTask--;
    setTimeout(deque, 0);
  }

  function doGetNewName(pi) {
    var sha1 = crypto.createHash('sha1'),
        stream = fs.createReadStream(pi.originalPhoto);

    // We take title and desc into hash code, so the same photos but with different
    // titles and descs will be different folder.
    if (pi.title) sha1.update(pi.title);
    if (pi.desc) sha1.update(pi.desc);

    stream.on('data', function(d) {
      sha1.update(d);
    });

    stream.on('end', function() {
      pi.newName = "photo-" + sha1.digest('hex');
      pi.photoDir = config.outputDir + '/' + pi.newName;
      done();
      createPhotoDir(pi);
    });

    stream.on('error', function(err) {
      done();
      e.emit('error', err);
    });
  }

  function deque() {
    // console.log("deque: " + runningNewNameTask);
    var newNameTask;
    if (runningNewNameTask < newNameTaskLimit) {
      while (!newNameTask && newNameQueue.length > 0) {
        newNameTask = newNameQueue.shift();
      }
      if (newNameTask) {
        runningNewNameTask++;
        doGetNewName(newNameTask.photoInfo);
      }
    }
  }

  newNameQueue.push({
    photoInfo: photoInfo
  });

  setTimeout(deque, 0);
}

exports.processPhoto = function processPhoto(albumPath, photoFileName, title, desc) {
  var e = new EventEmitter(),
      originalPhoto = albumPath + "/" + photoFileName,
      photoInfo = {
        title: title,
        desc: desc,
        originalPhoto: originalPhoto,
        originalFileName: photoFileName,
        e: e,
        page: {
          title: title
        }
      };

  // Lazy initialize.
  if (!config) config = require('./config.js').getCachedConfig();

  getNewName(photoInfo);

  return e;
}
<|endoftext|>


<commit_before>"use strict";

var $ = require('jquery'),
    _ = require('lodash'),
    Backbone = require('../../shim/backbone'),
    moment = require('moment'),
    settings = require('../core/settings');

var REQUEST_TIMED_OUT_CODE = 408;
var DESCRIPTION_MAX_LENGTH = 100;
var PAGE_SIZE = settings.get('data_catalog_page_size');

var FilterModel = Backbone.Model.extend({
    defaults: {
        id: '',
        type: '',
        isValid: true
    },

    reset: function() {
        // Clear all model attributes and set back any defaults.
        // Once we've called `.clear()` we lose the ability to detect
        // actual changed attributes after the `.set()`.
        // Store the prev state to check if a change event
        // should fire
        var prevAttr = _.clone(this.attributes);
        this.clear({ silent: true }).set(this.defaults,
                                         { silent: true });
        if (!_.isEqual(this.attributes, prevAttr)) {
            this.trigger("change", this);
        }
    },

    validate: function() {
        return true;
    },

    isActive: function() {
        window.console.error("Use of unimplemented function",
                             "FilterModel.isActive");
        return false;
    }
});

var SearchOption = FilterModel.extend({
    defaults: _.defaults({
        active: false,
    }, FilterModel.prototype.defaults),

    isActive: function() {
        return this.get('active');
    }
});

var GriddedServicesFilter = SearchOption.extend({
    defaults: _.defaults({
        id: 'gridded',
        type: 'checkbox',
        label: 'Gridded Services',
    }, SearchOption.prototype.defaults)
});

var DateFilter = FilterModel.extend({
    defaults: _.defaults({
        id: 'date',
        type: 'date',
        fromDate: null,
        toDate: null,
    }, FilterModel.prototype.defaults),

    isActive: function() {
        return this.get('fromDate') || this.get('toDate');
    },

    validate: function() {
        // Only need to validate if there are two dates.  Ensure that
        // before is earlier than after
        var dateFormat = "MM/DD/YYYY",
            toDate = this.get('toDate'),
            fromDate = this.get('fromDate'),
            isValid = true;

        if (toDate && !moment(toDate, dateFormat).isValid()) {
            isValid = false;
        }

        if (fromDate && !moment(fromDate, dateFormat).isValid()) {
            isValid = false;
        }

        if (toDate && fromDate){
            isValid = moment(fromDate, dateFormat)
                .isBefore(moment(toDate, dateFormat));
        }

        this.set('isValid', isValid);
        return isValid;
    }
});

var FilterCollection = Backbone.Collection.extend({
    model: FilterModel,

    countActive: function() {
        var isActive = function(filter) { return filter.isActive(); };

        return this.filter(isActive).length;
    },
});

var Catalog = Backbone.Model.extend({
    defaults: {
        id: '',
        name: '',
        description: '',
        query: '',
        geom: '',
        loading: false,
        stale: false, // Should search run when catalog becomes active?
        active: false,
        results: null, // Results collection
        resultCount: 0,
        filters: null, // FiltersCollection
        is_pageable: true,
        page: 1,
        error: '',
        detail_result: null
    },

    initialize: function() {
        var self = this;
        this.get('results').on('change:show_detail', function() {
            self.set('detail_result', self.get('results').getDetail());
        });

        // Initialize and listen to filters for changes
        if (this.get('filters') === null) {
            this.set({ filters: new FilterCollection() });
        }
        this.get('filters').on('change', function() {
            if (self.isSearchValid()) {
                if (self.get('active')) {
                    self.startSearch(1);
                } else {
                    self.set('stale', true);
                }
            }
        });
    },

    searchIfNeeded: function(query, geom) {
        var self = this,
            error = this.get('error'),
            stale = this.get('stale'),
            isSameSearch = query === this.get('query') &&
                           geom === this.get('geom');

        if (!isSameSearch || stale || error) {
            this.cancelSearch();
            this.searchPromise = this.search(query, geom)
                                     .always(function() {
                                        delete self.searchPromise;
                                     });
        }

        return this.searchPromise || $.when();
    },

    cancelSearch: function() {
        if (this.searchPromise) {
            this.searchPromise.abort();
        }
    },

    search: function(query, geom) {
        this.set({
            query: query,
            geom: geom,
        });

        return this.startSearch(1);
    },

    isSearchValid: function() {
        var query = this.get('query'),
            validate = function(filter) { return filter.validate(); },
            valid = this.get('filters').map(validate);

        return query && _.every(valid);
    },

    startSearch: function(page) {
        var filters = this.get('filters'),
            dateFilter = filters.findWhere({ id: 'date' }),
            fromDate = null,
            toDate = null;

        if (dateFilter) {
            fromDate = dateFilter.get('fromDate');
            toDate = dateFilter.get('toDate');
        }

        var lastPage = Math.ceil(this.get('resultCount') / PAGE_SIZE),
            thisPage = parseInt(page) || 1,
            isSearchOption = function(filter) { return filter instanceof SearchOption; },
            searchOptions = filters.filter(isSearchOption),
            data = {
                catalog: this.id,
                query: this.get('query'),
                geom: this.get('geom'),
                from_date: fromDate,
                to_date: toDate,
            };

        if (thisPage > 1 && thisPage <= lastPage) {
            _.assign(data, { page: thisPage });
        }

        if (searchOptions && searchOptions.length > 0) {
            var isActive = function(option) { return option.isActive(); },
                id = function(option) { return option.get('id'); };
            _.assign(data, {
                options: _.map(_.filter(searchOptions, isActive), id).join(',')
            });
        }

        this.set('loading', true);
        this.set('error', false);

        var request = {
            data: JSON.stringify(data),
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json'
        };

        return this.get('results')
                   .fetch(request)
                   .done(_.bind(this.doneSearch, this))
                   .fail(_.bind(this.failSearch, this))
                   .always(_.bind(this.finishSearch, this));
    },

    doneSearch: function(response) {
        var data = _.findWhere(response, { catalog: this.id });

        this.set({
            page: data.page || 1,
            resultCount: data.count,
        });
    },

    failSearch: function(response, textStatus) {
        if (textStatus === "abort") {
            // Do nothing if the search failed because it
            // was purposefully cancelled
            return;
        }
        if (response.status === REQUEST_TIMED_OUT_CODE){
            this.set('error', "Searching took too long. " +
                              "Consider trying a smaller area of interest " +
                              "or a more specific search term.");
        } else {
            this.set('error', "Error");
        }
    },

    finishSearch: function() {
        this.set({
            loading: false,
            stale: false,
        });
    },

    previousPage: function() {
        var page = this.get('page');

        if (page > 1) {
            return this.startSearch(page - 1);
        } else {
            return $.when();
        }
    },

    nextPage: function() {
        var page = this.get('page'),
            count = this.get('resultCount'),
            lastPage = Math.ceil(count / PAGE_SIZE);

        if (page < lastPage) {
            return this.startSearch(page + 1);
        } else {
            return $.when();
        }
    }
});

var Catalogs = Backbone.Collection.extend({
    model: Catalog,

    getActiveCatalog: function() {
        return this.findWhere({ active: true });
    }
});

var Result = Backbone.Model.extend({
    defaults: {
        id: '',
        title: '',
        description: '',
        geom: null, // GeoJSON
        links: null, // Array
        created_at: '',
        updated_at: '',
        active: false,
        show_detail: false // Show this result as the detail view?
    },

    getSummary: function() {
        var text = this.get('description') || '';
        if (text.length <= DESCRIPTION_MAX_LENGTH) {
            return text;
        }
        var truncated = text.substr(0,
            text.indexOf(' ', DESCRIPTION_MAX_LENGTH));
        return truncated + '…';
    },

    getDetailsUrl: function() {
        var links = this.get('links') || [],
            detailsUrl = _.findWhere(links, { type: 'details' });
        return detailsUrl && detailsUrl.href;
    },

    toJSON: function() {
        return _.assign({}, this.attributes, {
            summary: this.getSummary(),
            detailsUrl: this.getDetailsUrl()
        });
    }
});

var Results = Backbone.Collection.extend({
    url: '/bigcz/search',
    model: Result,

    initialize: function(models, options) {
        this.catalog = options.catalog;
    },

    parse: function(response) {
        return _.findWhere(response, { catalog: this.catalog }).results;
    },

    getDetail: function() {
        return this.findWhere({ show_detail: true});
    },

    showDetail: function(result) {
        var currentDetail = this.getDetail();

        if (currentDetail) {
            // Do nothing if the selected result is already the detail shown
            if (currentDetail.get('id') === result.get('id')) {
                return;
            }
            // Turn off the actively shown detail. There should only be
            // one with `show_detail` true at a time
            currentDetail.set('show_detail', false);
        }

        result.set('show_detail', true);
    },

    closeDetail: function() {
        var currentDetail = this.getDetail();

        if (!currentDetail) {
            return;
        }

        currentDetail.set('show_detail', false);
    }
});

var SearchForm = Backbone.Model.extend({
    defaults: {
        query: '',
    }
});

var PopoverControllerModel = Backbone.Model.extend({
    defaults: {
        activeResult: null // Result
    }
});

module.exports = {
    GriddedServicesFilter: GriddedServicesFilter,
    DateFilter: DateFilter,
    FilterCollection: FilterCollection,
    Catalog: Catalog,
    Catalogs: Catalogs,
    Result: Result,
    Results: Results,
    SearchForm: SearchForm,
    PopoverControllerModel: PopoverControllerModel,
};
<commit_msg>Abstract out DATE_FORMAT for reuse<commit_after>"use strict";

var $ = require('jquery'),
    _ = require('lodash'),
    Backbone = require('../../shim/backbone'),
    moment = require('moment'),
    settings = require('../core/settings');

var REQUEST_TIMED_OUT_CODE = 408;
var DESCRIPTION_MAX_LENGTH = 100;
var PAGE_SIZE = settings.get('data_catalog_page_size');

var DATE_FORMAT = 'MM/DD/YYYY';

var FilterModel = Backbone.Model.extend({
    defaults: {
        id: '',
        type: '',
        isValid: true
    },

    reset: function() {
        // Clear all model attributes and set back any defaults.
        // Once we've called `.clear()` we lose the ability to detect
        // actual changed attributes after the `.set()`.
        // Store the prev state to check if a change event
        // should fire
        var prevAttr = _.clone(this.attributes);
        this.clear({ silent: true }).set(this.defaults,
                                         { silent: true });
        if (!_.isEqual(this.attributes, prevAttr)) {
            this.trigger("change", this);
        }
    },

    validate: function() {
        return true;
    },

    isActive: function() {
        window.console.error("Use of unimplemented function",
                             "FilterModel.isActive");
        return false;
    }
});

var SearchOption = FilterModel.extend({
    defaults: _.defaults({
        active: false,
    }, FilterModel.prototype.defaults),

    isActive: function() {
        return this.get('active');
    }
});

var GriddedServicesFilter = SearchOption.extend({
    defaults: _.defaults({
        id: 'gridded',
        type: 'checkbox',
        label: 'Gridded Services',
    }, SearchOption.prototype.defaults)
});

var DateFilter = FilterModel.extend({
    defaults: _.defaults({
        id: 'date',
        type: 'date',
        fromDate: null,
        toDate: null,
    }, FilterModel.prototype.defaults),

    isActive: function() {
        return this.get('fromDate') || this.get('toDate');
    },

    validate: function() {
        // Only need to validate if there are two dates.  Ensure that
        // before is earlier than after
        var toDate = this.get('toDate'),
            fromDate = this.get('fromDate'),
            isValid = true;

        if (toDate && !moment(toDate, DATE_FORMAT).isValid()) {
            isValid = false;
        }

        if (fromDate && !moment(fromDate, DATE_FORMAT).isValid()) {
            isValid = false;
        }

        if (toDate && fromDate){
            isValid = moment(fromDate, DATE_FORMAT)
                .isBefore(moment(toDate, DATE_FORMAT));
        }

        this.set('isValid', isValid);
        return isValid;
    }
});

var FilterCollection = Backbone.Collection.extend({
    model: FilterModel,

    countActive: function() {
        var isActive = function(filter) { return filter.isActive(); };

        return this.filter(isActive).length;
    },
});

var Catalog = Backbone.Model.extend({
    defaults: {
        id: '',
        name: '',
        description: '',
        query: '',
        geom: '',
        loading: false,
        stale: false, // Should search run when catalog becomes active?
        active: false,
        results: null, // Results collection
        resultCount: 0,
        filters: null, // FiltersCollection
        is_pageable: true,
        page: 1,
        error: '',
        detail_result: null
    },

    initialize: function() {
        var self = this;
        this.get('results').on('change:show_detail', function() {
            self.set('detail_result', self.get('results').getDetail());
        });

        // Initialize and listen to filters for changes
        if (this.get('filters') === null) {
            this.set({ filters: new FilterCollection() });
        }
        this.get('filters').on('change', function() {
            if (self.isSearchValid()) {
                if (self.get('active')) {
                    self.startSearch(1);
                } else {
                    self.set('stale', true);
                }
            }
        });
    },

    searchIfNeeded: function(query, geom) {
        var self = this,
            error = this.get('error'),
            stale = this.get('stale'),
            isSameSearch = query === this.get('query') &&
                           geom === this.get('geom');

        if (!isSameSearch || stale || error) {
            this.cancelSearch();
            this.searchPromise = this.search(query, geom)
                                     .always(function() {
                                        delete self.searchPromise;
                                     });
        }

        return this.searchPromise || $.when();
    },

    cancelSearch: function() {
        if (this.searchPromise) {
            this.searchPromise.abort();
        }
    },

    search: function(query, geom) {
        this.set({
            query: query,
            geom: geom,
        });

        return this.startSearch(1);
    },

    isSearchValid: function() {
        var query = this.get('query'),
            validate = function(filter) { return filter.validate(); },
            valid = this.get('filters').map(validate);

        return query && _.every(valid);
    },

    startSearch: function(page) {
        var filters = this.get('filters'),
            dateFilter = filters.findWhere({ id: 'date' }),
            fromDate = null,
            toDate = null;

        if (dateFilter) {
            fromDate = dateFilter.get('fromDate');
            toDate = dateFilter.get('toDate');
        }

        var lastPage = Math.ceil(this.get('resultCount') / PAGE_SIZE),
            thisPage = parseInt(page) || 1,
            isSearchOption = function(filter) { return filter instanceof SearchOption; },
            searchOptions = filters.filter(isSearchOption),
            data = {
                catalog: this.id,
                query: this.get('query'),
                geom: this.get('geom'),
                from_date: fromDate,
                to_date: toDate,
            };

        if (thisPage > 1 && thisPage <= lastPage) {
            _.assign(data, { page: thisPage });
        }

        if (searchOptions && searchOptions.length > 0) {
            var isActive = function(option) { return option.isActive(); },
                id = function(option) { return option.get('id'); };
            _.assign(data, {
                options: _.map(_.filter(searchOptions, isActive), id).join(',')
            });
        }

        this.set('loading', true);
        this.set('error', false);

        var request = {
            data: JSON.stringify(data),
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json'
        };

        return this.get('results')
                   .fetch(request)
                   .done(_.bind(this.doneSearch, this))
                   .fail(_.bind(this.failSearch, this))
                   .always(_.bind(this.finishSearch, this));
    },

    doneSearch: function(response) {
        var data = _.findWhere(response, { catalog: this.id });

        this.set({
            page: data.page || 1,
            resultCount: data.count,
        });
    },

    failSearch: function(response, textStatus) {
        if (textStatus === "abort") {
            // Do nothing if the search failed because it
            // was purposefully cancelled
            return;
        }
        if (response.status === REQUEST_TIMED_OUT_CODE){
            this.set('error', "Searching took too long. " +
                              "Consider trying a smaller area of interest " +
                              "or a more specific search term.");
        } else {
            this.set('error', "Error");
        }
    },

    finishSearch: function() {
        this.set({
            loading: false,
            stale: false,
        });
    },

    previousPage: function() {
        var page = this.get('page');

        if (page > 1) {
            return this.startSearch(page - 1);
        } else {
            return $.when();
        }
    },

    nextPage: function() {
        var page = this.get('page'),
            count = this.get('resultCount'),
            lastPage = Math.ceil(count / PAGE_SIZE);

        if (page < lastPage) {
            return this.startSearch(page + 1);
        } else {
            return $.when();
        }
    }
});

var Catalogs = Backbone.Collection.extend({
    model: Catalog,

    getActiveCatalog: function() {
        return this.findWhere({ active: true });
    }
});

var Result = Backbone.Model.extend({
    defaults: {
        id: '',
        title: '',
        description: '',
        geom: null, // GeoJSON
        links: null, // Array
        created_at: '',
        updated_at: '',
        active: false,
        show_detail: false // Show this result as the detail view?
    },

    getSummary: function() {
        var text = this.get('description') || '';
        if (text.length <= DESCRIPTION_MAX_LENGTH) {
            return text;
        }
        var truncated = text.substr(0,
            text.indexOf(' ', DESCRIPTION_MAX_LENGTH));
        return truncated + '…';
    },

    getDetailsUrl: function() {
        var links = this.get('links') || [],
            detailsUrl = _.findWhere(links, { type: 'details' });
        return detailsUrl && detailsUrl.href;
    },

    toJSON: function() {
        return _.assign({}, this.attributes, {
            summary: this.getSummary(),
            detailsUrl: this.getDetailsUrl()
        });
    }
});

var Results = Backbone.Collection.extend({
    url: '/bigcz/search',
    model: Result,

    initialize: function(models, options) {
        this.catalog = options.catalog;
    },

    parse: function(response) {
        return _.findWhere(response, { catalog: this.catalog }).results;
    },

    getDetail: function() {
        return this.findWhere({ show_detail: true});
    },

    showDetail: function(result) {
        var currentDetail = this.getDetail();

        if (currentDetail) {
            // Do nothing if the selected result is already the detail shown
            if (currentDetail.get('id') === result.get('id')) {
                return;
            }
            // Turn off the actively shown detail. There should only be
            // one with `show_detail` true at a time
            currentDetail.set('show_detail', false);
        }

        result.set('show_detail', true);
    },

    closeDetail: function() {
        var currentDetail = this.getDetail();

        if (!currentDetail) {
            return;
        }

        currentDetail.set('show_detail', false);
    }
});

var SearchForm = Backbone.Model.extend({
    defaults: {
        query: '',
    }
});

var PopoverControllerModel = Backbone.Model.extend({
    defaults: {
        activeResult: null // Result
    }
});

module.exports = {
    GriddedServicesFilter: GriddedServicesFilter,
    DateFilter: DateFilter,
    FilterCollection: FilterCollection,
    Catalog: Catalog,
    Catalogs: Catalogs,
    Result: Result,
    Results: Results,
    SearchForm: SearchForm,
    PopoverControllerModel: PopoverControllerModel,
};
<|endoftext|>