<commit_before>/**
 * Подменяем и расширяем Backbone.View, добавляя в него милые методы для работы с селекторами, выбором элементов и
 * дата атрибутами
 * @class Backbone.ElementsView
 * @extends Backbone.View
 */
Backbone.ElementsView = Backbone.View.redefine(function (origin) {
    return /**@lends Backbone.View*/{

        /**
         * @protected
         */
        _initProperties: function () {
            origin._initProperties.apply(this, arguments);

            /**
             * @type {jQuery}
             * @protected
             */
            this._$window = $(window);

            /**
             * @type {jQuery}
             * @protected
             */
            this._$document = $(document);

            /**
             * @type {jQuery}
             * @protected
             */
            this._$body = $(document.body);
        },

        setElement: function () {
            origin.setElement.apply(this, arguments);

            /**
             * Дата атрибуты {@link Backbone.View.$el} в camelCase
             * @type {Object.<string, string>}
             * @protected
             */
            this._data = this.$el.data() || {};
            this._resetCaches();
            return this;
        },

        /**
         * Сбрасывает кэши клаасов, селекторов и элементов
         * @private
         */
        _resetCaches: function () {

            /**
             * Здесь сохраняются закешированные классы, полученные из
             * {@link Backbone.ElementsView._classes}
             * @type {Object.<string, string>}
             * @private
             */
            this._cachedClasses = this._classes();

            /**
             * Здесь сохраняются закешированные селекторы, в том числе полученные из
             * {@link Backbone.ElementsView._classes}
             * @type {Object.<string, string>}
             * @private
             */
            this._cachedSelectors = this._selectors();

            /**
             * Кеш для {@link Backbone.ElementsView._elem}
             * @type {Object.<string, jQuery>}
             * @private
             */
            this._cachedElements = {};
        },

        /**
         * CSS классы используемые во вьюшке складываются сюда. Ключи - имена элементов, значение - названия классов.
         * Свойство можно переопределять в наследуемых классах
         * @returns {Object.<string, string>}
         * @protected
         * @example
         *     _classes: function(){
         *         return {
         *             table: 'js-table'
         *         };
         *     }
         *
         */
        _classes: function () {
            return {};
        },

        /**
         * Возвращает css класс элемента по его имени, классы берутся из {@link Backbone.ElementsView._classes}
         * @param {String} name название элемента
         * @returns {String} css класс
         * @throws {Error} если название елемента нигде не найдено
         * @protected
         */
        _class: function (name) {
            var cl = this._cachedClasses[name];
            if (cl == null) {
                throw new Error('Selector for ' + name + ' does not found');
            }

            return cl;
        },

        /**
         * Селекторы используемые во вьюшке описываются здесь. Метод надо переопределять в наследуемых классах
         * @returns {Object.<string, string>} Ключи - названия элементов, значения - селекторы
         * @protected
         * @example
         *      _selectors: function(){
         *          return {
         *              map: '.google-map:first'
         *          };
         *      }
         *
         */
        _selectors: function () {
            return {};
        },

        /**
         * Возвращает селектор элемента по его имени, селекторы берутся из {@link Backbone.ElementsView._selectors} или
         * {@link Backbone.ElementsView._classes}
         * @param {String} name название элемента
         * @returns {String} селектор
         * @protected
         * @example
         *      events: function(){
         *          var events = {};
         *          events['click ' + this._selector('map')] = this._clickOnMap;
         *          events['click ' + this._selector('table')] = this._clickOnTable;
         *          return events;
         *      }
         *
         */
        _selector: function (name) {
            var args = null,
                cacheKey = this._getCacheKey.apply(this, arguments),
                selector = this._cachedSelectors[cacheKey];

            if (selector == null) {
                if (!this._cachedSelectors[name]) {
                    selector = '.' + this._class(name);
                    this._cachedSelectors[name] = selector;
                }

                args = Array.prototype.slice.call(arguments, 1);
                if (args.length) {
                    args.unshift(this._cachedSelectors[name]);
                    selector = _.sprintf.apply(_, args);
                    this._cachedSelectors[cacheKey] = selector;
                }
            }
            return selector;
        },

        /**
         * @param {String} name
         * @returns {Boolean}
         * @protected
         */
        _hasSelector: function (name) {
            return !!(this._cachedClasses[name] || this._cachedSelectors[name]);
        },

        /**
         * Возвращает jQuery коллекцию по имени из {@link Backbone.ElementsView._selectors} или
         * {@link Backbone.ElementsView._classes}. Кэширует результаты, для сброса кеша см.
         * {@link Backbone.ElementsView._dropElemCache}
         * @param {String} name название элемента
         * @returns {jQuery}
         * @protected
         * @example
         *     this._elem('table').hide();
         *
         */
        _elem: function (name) {
            var cacheKey = this._getCacheKey.apply(this, arguments),
                $elem = this._cachedElements[cacheKey];

            if ($elem != null) {
                return $elem;
            }

            $elem = this._findElem.apply(this, arguments);
            this._cachedElements[cacheKey] = $elem;

            return $elem;
        },

        /**
         * @param name
         * @returns {string}
         * @private
         */
        _getCacheKey: function (name) {
            return Array.prototype.join.call(arguments, '|');
        },

        /**
         * Finds element without using cache
         * @param {string} name
         * @returns {jQuery}
         * @protected
         */
        _findElem: function (name) {
            return this.$(this._selector.apply(this, arguments));
        },

        /**
         * Replaces element with passed content
         * @param {string} name
         * @param {HTMLElement|jQuery|string} content
         * @protected
         */
        _replaceElem: function (name, content) {
            var $el = this._elem(name),
                focusOnElem = $el[0] == document.activeElement || $el.has(document.activeElement).length;

            this._elem(name).replaceWith(content);
            this._dropElemCache(name);

            if (focusOnElem) {
                this._fixFocus(this._elem(name));
            }
        },

        /**
         * Sets element innerHTML
         * @param {string} name
         * @param {HTMLElement|jQuery|string} content
         * @protected
         */
        _setElemContent: function (name, content) {
            var $el = this._elem(name),
                focusInsideElem = $el.has(document.activeElement).length;

            $el.html(content);
            if (focusInsideElem) {
                this._fixFocus($el);
            }
        },

        /**
         * Emulate focus on passed element (focuses closest focusable element)
         * @param {jQuery} $el
         * @private
         */
        _fixFocus: function ($el) {
            var $focused = $el.closest('[tabindex],a,button:not(:disabled)');
            if ($focused.length) {
                $focused[0].focus();
            }
        },

        /**
         * Трет кеш для {@link Backbone.ElementsView._elem}
         * @param {String} [name] имя элемента для которого надо убрать кеш, если не задано - сотрется весь кеш
         * @protected
         */
        _dropElemCache: function (name) {
            if (name != null) {
                delete this._cachedElements[this._getCacheKey.apply(this, arguments)];
            }
            else {
                this._cachedElements = {};
            }
            return this;
        },

        /**
         * Возвращает дата атрибуты для элемента по его имени и имени атрибута
         * @param {String} name имя элемента
         * @param {String} [attr] имя атрибута, если не задано, то вернется объект со всеми дата атрибутами для элемента
         * @returns {*|Object}
         * @protected
         */
        _getElemData: function (name, attr) {
            var data = this._elem(name).data();
            if (attr == null) {
                return data;
            }

            return data[attr];
        },

        /**
         * Совместимость с Backbone.Decorate
         */
        beforeDecorate: function () {
            this._resetCaches();

            if (typeof origin.beforeDecorate == "function") {
                origin.beforeDecorate.apply(this, arguments);
            }
        }
    }
});<commit_msg>PSDJS-8015 _class method now with arguments too<commit_after>/**
 * Подменяем и расширяем Backbone.View, добавляя в него милые методы для работы с селекторами, выбором элементов и
 * дата атрибутами
 * @class Backbone.ElementsView
 * @extends Backbone.View
 */
Backbone.ElementsView = Backbone.View.redefine(function (origin) {
    return /**@lends Backbone.View*/{

        /**
         * @protected
         */
        _initProperties: function () {
            origin._initProperties.apply(this, arguments);

            /**
             * @type {jQuery}
             * @protected
             */
            this._$window = $(window);

            /**
             * @type {jQuery}
             * @protected
             */
            this._$document = $(document);

            /**
             * @type {jQuery}
             * @protected
             */
            this._$body = $(document.body);
        },

        setElement: function () {
            origin.setElement.apply(this, arguments);

            /**
             * Дата атрибуты {@link Backbone.View.$el} в camelCase
             * @type {Object.<string, string>}
             * @protected
             */
            this._data = this.$el.data() || {};
            this._resetCaches();
            return this;
        },

        /**
         * Сбрасывает кэши клаасов, селекторов и элементов
         * @private
         */
        _resetCaches: function () {

            /**
             * Здесь сохраняются закешированные классы, полученные из
             * {@link Backbone.ElementsView._classes}
             * @type {Object.<string, string>}
             * @private
             */
            this._cachedClasses = this._classes();

            /**
             * Здесь сохраняются закешированные селекторы, в том числе полученные из
             * {@link Backbone.ElementsView._classes}
             * @type {Object.<string, string>}
             * @private
             */
            this._cachedSelectors = this._selectors();

            /**
             * Кеш для {@link Backbone.ElementsView._elem}
             * @type {Object.<string, jQuery>}
             * @private
             */
            this._cachedElements = {};
        },

        /**
         * CSS классы используемые во вьюшке складываются сюда. Ключи - имена элементов, значение - названия классов.
         * Свойство можно переопределять в наследуемых классах
         * @returns {Object.<string, string>}
         * @protected
         * @example
         *     _classes: function(){
         *         return {
         *             table: 'js-table'
         *         };
         *     }
         *
         */
        _classes: function () {
            return {};
        },

        /**
         * Возвращает css класс элемента по его имени, классы берутся из {@link Backbone.ElementsView._classes}
         * @param {String} name название элемента
         * @returns {String} css класс
         * @throws {Error} если название елемента нигде не найдено
         * @protected
         */
        _class: function (name) {
            var cl = this._cachedClasses[name];
            if (cl == null) {
                throw new Error('Selector for ' + name + ' does not found');
            }

            if (arguments.length > 1){
                var args = Array.prototype.slice.call(arguments, 1);
                args.unshift(cl);
                cl = _.sprintf.apply(_, args);
            }

            return cl;
        },

        /**
         * Селекторы используемые во вьюшке описываются здесь. Метод надо переопределять в наследуемых классах
         * @returns {Object.<string, string>} Ключи - названия элементов, значения - селекторы
         * @protected
         * @example
         *      _selectors: function(){
         *          return {
         *              map: '.google-map:first'
         *          };
         *      }
         *
         */
        _selectors: function () {
            return {};
        },

        /**
         * Возвращает селектор элемента по его имени, селекторы берутся из {@link Backbone.ElementsView._selectors} или
         * {@link Backbone.ElementsView._classes}
         * @param {String} name название элемента
         * @returns {String} селектор
         * @protected
         * @example
         *      events: function(){
         *          var events = {};
         *          events['click ' + this._selector('map')] = this._clickOnMap;
         *          events['click ' + this._selector('table')] = this._clickOnTable;
         *          return events;
         *      }
         *
         */
        _selector: function (name) {
            var args = null,
                cacheKey = this._getCacheKey.apply(this, arguments),
                selector = this._cachedSelectors[cacheKey];

            if (selector == null) {
                if (!this._cachedSelectors[name]) {
                    selector = '.' + this._class(name);
                    this._cachedSelectors[name] = selector;
                }

                args = Array.prototype.slice.call(arguments, 1);
                if (args.length) {
                    args.unshift(this._cachedSelectors[name]);
                    selector = _.sprintf.apply(_, args);
                    this._cachedSelectors[cacheKey] = selector;
                }
            }
            return selector;
        },

        /**
         * @param {String} name
         * @returns {Boolean}
         * @protected
         */
        _hasSelector: function (name) {
            return !!(this._cachedClasses[name] || this._cachedSelectors[name]);
        },

        /**
         * Возвращает jQuery коллекцию по имени из {@link Backbone.ElementsView._selectors} или
         * {@link Backbone.ElementsView._classes}. Кэширует результаты, для сброса кеша см.
         * {@link Backbone.ElementsView._dropElemCache}
         * @param {String} name название элемента
         * @returns {jQuery}
         * @protected
         * @example
         *     this._elem('table').hide();
         *
         */
        _elem: function (name) {
            var cacheKey = this._getCacheKey.apply(this, arguments),
                $elem = this._cachedElements[cacheKey];

            if ($elem != null) {
                return $elem;
            }

            $elem = this._findElem.apply(this, arguments);
            this._cachedElements[cacheKey] = $elem;

            return $elem;
        },

        /**
         * @param name
         * @returns {string}
         * @private
         */
        _getCacheKey: function (name) {
            return Array.prototype.join.call(arguments, '|');
        },

        /**
         * Finds element without using cache
         * @param {string} name
         * @returns {jQuery}
         * @protected
         */
        _findElem: function (name) {
            return this.$(this._selector.apply(this, arguments));
        },

        /**
         * Replaces element with passed content
         * @param {string} name
         * @param {HTMLElement|jQuery|string} content
         * @protected
         */
        _replaceElem: function (name, content) {
            var $el = this._elem(name),
                focusOnElem = $el[0] == document.activeElement || $el.has(document.activeElement).length;

            this._elem(name).replaceWith(content);
            this._dropElemCache(name);

            if (focusOnElem) {
                this._fixFocus(this._elem(name));
            }
        },

        /**
         * Sets element innerHTML
         * @param {string} name
         * @param {HTMLElement|jQuery|string} content
         * @protected
         */
        _setElemContent: function (name, content) {
            var $el = this._elem(name),
                focusInsideElem = $el.has(document.activeElement).length;

            $el.html(content);
            if (focusInsideElem) {
                this._fixFocus($el);
            }
        },

        /**
         * Emulate focus on passed element (focuses closest focusable element)
         * @param {jQuery} $el
         * @private
         */
        _fixFocus: function ($el) {
            var $focused = $el.closest('[tabindex],a,button:not(:disabled)');
            if ($focused.length) {
                $focused[0].focus();
            }
        },

        /**
         * Трет кеш для {@link Backbone.ElementsView._elem}
         * @param {String} [name] имя элемента для которого надо убрать кеш, если не задано - сотрется весь кеш
         * @protected
         */
        _dropElemCache: function (name) {
            if (name != null) {
                delete this._cachedElements[this._getCacheKey.apply(this, arguments)];
            }
            else {
                this._cachedElements = {};
            }
            return this;
        },

        /**
         * Возвращает дата атрибуты для элемента по его имени и имени атрибута
         * @param {String} name имя элемента
         * @param {String} [attr] имя атрибута, если не задано, то вернется объект со всеми дата атрибутами для элемента
         * @returns {*|Object}
         * @protected
         */
        _getElemData: function (name, attr) {
            var data = this._elem(name).data();
            if (attr == null) {
                return data;
            }

            return data[attr];
        },

        /**
         * Совместимость с Backbone.Decorate
         */
        beforeDecorate: function () {
            this._resetCaches();

            if (typeof origin.beforeDecorate == "function") {
                origin.beforeDecorate.apply(this, arguments);
            }
        }
    }
});<|endoftext|>


<commit_before>(function() {

  var container;
  var camera, scene, renderer, particles, geometry, materials = [], parameters, i, h, color;
  var mouseX = 0, mouseY = 0;

  var width = sample_defaults.width * 2;
  var height = sample_defaults.height * 2;

  function render() {
    var time = Date.now() * 0.00005;

    for ( i = 0; i < scene.children.length; i ++ ) {
      var object = scene.children[ i ];

      if ( object instanceof THREE.ParticleSystem ) {
        object.rotation.y = time * ( i < 4 ? i + 1 : - ( i + 1 ) );
      }
    }

    for ( i = 0; i < materials.length; i ++ ) {
      color = parameters[i][0];

      h = ( 360 * ( color[0] + time ) % 360 ) / 360;
      materials[i].color.setHSV( h, color[1], color[2] );
    }

    renderer.render( scene, camera );
  }

  window.samples.particles = {

    initialize: function(canvas) {

      camera = new THREE.PerspectiveCamera( 75, width / height, 1, 3000 );
      camera.position.z = 1000;

      scene = new THREE.Scene();
      scene.fog = new THREE.FogExp2( 0x000000, 0.0007 );

      geometry = new THREE.Geometry();

      for ( i = 0; i < 10000; i ++ ) {

        var vertex = new THREE.Vector3();
        vertex.x = Math.random() * 2000 - 1000;
        vertex.y = Math.random() * 2000 - 1000;
        vertex.z = Math.random() * 2000 - 1000;

        geometry.vertices.push( vertex );
      }

      parameters = [ [ [1.0, 1.0, 1.0], 5 ], [ [0.95, 1, 1], 4 ], [ [0.90, 1, 1], 3 ], [ [0.85, 1, 1], 2 ], [ [0.80, 1, 1], 1 ] ];

      for ( i = 0; i < parameters.length; i ++ ) {

        size  = parameters[i][1];
        color = parameters[i][0];

        materials[i] = new THREE.ParticleBasicMaterial( { size: size } );
        materials[i].color.setHSV( color[0], color[1], color[2] );

        particles = new THREE.ParticleSystem( geometry, materials[i] );

        particles.rotation.x = Math.random() * 6;
        particles.rotation.y = Math.random() * 6;
        particles.rotation.z = Math.random() * 6;

        scene.add( particles );
      }

      renderer = new THREE.WebGLRenderer({canvas: canvas});
      renderer.setSize( width, height );

      var instance = { active: false };
      function animate() {
        requestAnimationFrame( animate );
        if(!instance.active || sample_defaults.paused) return;
        render();
      }

      animate();
      return instance;
    }
  };
})();
<commit_msg>Particle sample is now an instance of a class<commit_after>(function() {

  function ParticleSample() {
    var container;
    var camera, scene, renderer, particles, geometry, materials = [], parameters, i, h, color;
    var mouseX = 0, mouseY = 0;

    var width = sample_defaults.width * 2;
    var height = sample_defaults.height * 2;

    function render() {
      var time = Date.now() * 0.00005;

      for ( i = 0; i < scene.children.length; i ++ ) {
        var object = scene.children[ i ];

        if ( object instanceof THREE.ParticleSystem ) {
          object.rotation.y = time * ( i < 4 ? i + 1 : - ( i + 1 ) );
        }
      }

      for ( i = 0; i < materials.length; i ++ ) {
        color = parameters[i][0];

        h = ( 360 * ( color[0] + time ) % 360 ) / 360;
        materials[i].color.setHSV( h, color[1], color[2] );
      }

      renderer.render( scene, camera );
    }

    this.initialize = function(canvas) {

      camera = new THREE.PerspectiveCamera( 75, width / height, 1, 3000 );
      camera.position.z = 1000;

      scene = new THREE.Scene();
      scene.fog = new THREE.FogExp2( 0x000000, 0.0007 );

      geometry = new THREE.Geometry();

      for ( i = 0; i < 10000; i ++ ) {

        var vertex = new THREE.Vector3();
        vertex.x = Math.random() * 2000 - 1000;
        vertex.y = Math.random() * 2000 - 1000;
        vertex.z = Math.random() * 2000 - 1000;

        geometry.vertices.push( vertex );
      }

      parameters = [ [ [1.0, 1.0, 1.0], 5 ], [ [0.95, 1, 1], 4 ], [ [0.90, 1, 1], 3 ], [ [0.85, 1, 1], 2 ], [ [0.80, 1, 1], 1 ] ];

      for ( i = 0; i < parameters.length; i ++ ) {

        size  = parameters[i][1];
        color = parameters[i][0];

        materials[i] = new THREE.ParticleBasicMaterial( { size: size } );
        materials[i].color.setHSV( color[0], color[1], color[2] );

        particles = new THREE.ParticleSystem( geometry, materials[i] );

        particles.rotation.x = Math.random() * 6;
        particles.rotation.y = Math.random() * 6;
        particles.rotation.z = Math.random() * 6;

        scene.add( particles );
      }

      renderer = new THREE.WebGLRenderer({canvas: canvas});
      renderer.setSize( width, height );

      var instance = { active: false };
      function animate() {
        requestAnimationFrame( animate );
        if(!instance.active || sample_defaults.paused) return;
        render();
      }

      animate();
      return instance;
    }
  }

  window.samples.particles = {
    initialize: function(canvas) {
      var particleSample = new ParticleSample();
      return particleSample.initialize(canvas);
    }
  };
})();
<|endoftext|>


<commit_before>import { bufferToInt } from 'ethereumjs-util';

const getBufferFromHex = hex => {
  hex = sanitizeHex(hex);
  const _hex = hex.toLowerCase().replace('0x', '');
  return new Buffer(_hex, 'hex');
};
const padLeftEven = hex => {
  hex = hex.length % 2 != 0 ? '0' + hex : hex;
  return hex;
};
const sanitizeHex = hex => {
  hex = hex.substring(0, 2) == '0x' ? hex.substring(2) : hex;
  if (hex == '') return '';
  return '0x' + padLeftEven(hex);
};
const bufferToHex = buffer => {
  return '0x' + buffer.toString('hex');
};
const getHexTxObject = tx => {
  return {
    to: sanitizeHex(tx.to.toString('hex')),
    value: sanitizeHex(tx.value.toString('hex')),
    data: sanitizeHex(tx.data.toString('hex')),
    chainId: tx.getChainId(),
    nonce: sanitizeHex(tx.nonce.toString('hex')),
    gasLimit: sanitizeHex(tx.gasLimit.toString('hex')),
    gasPrice: sanitizeHex(tx.gasPrice.toString('hex'))
  };
};
const getSignTransactionObject = tx => {
  return {
    rawTransaction: bufferToHex(tx.serialize()),
    tx: {
      nonce: bufferToHex(tx.nonce),
      gasPrice: bufferToHex(tx.gasPrice),
      gas: tx.gasLimit ? bufferToHex(tx.gasLimit) : bufferToHex(tx.gas),
      to: bufferToHex(tx.to),
      value: bufferToHex(tx.value),
      input: bufferToHex(tx.data),
      v: bufferToHex(tx.v),
      r: bufferToHex(tx.r),
      s: bufferToHex(tx.s),
      hash: bufferToHex(tx.hash())
    }
  };
};
const calculateChainIdFromV = v => {
  const sigV = bufferToInt(v);
  let chainId = Math.floor((sigV - 35) / 2);
  if (chainId < 0) chainId = 0;
  return chainId;
};
export {
  getBufferFromHex,
  bufferToHex,
  getSignTransactionObject,
  sanitizeHex,
  padLeftEven,
  getHexTxObject,
  calculateChainIdFromV
};
<commit_msg>fix: 🐛 add check for hex before substring is called<commit_after>import { bufferToInt } from 'ethereumjs-util';

const getBufferFromHex = hex => {
  hex = sanitizeHex(hex);
  const _hex = hex.toLowerCase().replace('0x', '');
  return new Buffer(_hex, 'hex');
};
const padLeftEven = hex => {
  hex = hex.length % 2 != 0 ? '0' + hex : hex;
  return hex;
};
const sanitizeHex = hex => {
  hex = hex ? (hex.substring(0, 2) == '0x' ? hex.substring(2) : hex) : '';
  if (hex == '') return '';
  return '0x' + padLeftEven(hex);
};
const bufferToHex = buffer => {
  return '0x' + buffer.toString('hex');
};
const getHexTxObject = tx => {
  return {
    to: sanitizeHex(tx.to.toString('hex')),
    value: sanitizeHex(tx.value.toString('hex')),
    data: sanitizeHex(tx.data.toString('hex')),
    chainId: tx.getChainId(),
    nonce: sanitizeHex(tx.nonce.toString('hex')),
    gasLimit: sanitizeHex(tx.gasLimit.toString('hex')),
    gasPrice: sanitizeHex(tx.gasPrice.toString('hex'))
  };
};
const getSignTransactionObject = tx => {
  return {
    rawTransaction: bufferToHex(tx.serialize()),
    tx: {
      nonce: bufferToHex(tx.nonce),
      gasPrice: bufferToHex(tx.gasPrice),
      gas: tx.gasLimit ? bufferToHex(tx.gasLimit) : bufferToHex(tx.gas),
      to: bufferToHex(tx.to),
      value: bufferToHex(tx.value),
      input: bufferToHex(tx.data),
      v: bufferToHex(tx.v),
      r: bufferToHex(tx.r),
      s: bufferToHex(tx.s),
      hash: bufferToHex(tx.hash())
    }
  };
};
const calculateChainIdFromV = v => {
  const sigV = bufferToInt(v);
  let chainId = Math.floor((sigV - 35) / 2);
  if (chainId < 0) chainId = 0;
  return chainId;
};
export {
  getBufferFromHex,
  bufferToHex,
  getSignTransactionObject,
  sanitizeHex,
  padLeftEven,
  getHexTxObject,
  calculateChainIdFromV
};
<|endoftext|>


<commit_before><commit_msg>tweaks<commit_after><|endoftext|>


<commit_before>/**
 * Подменяем и расширяем Backbone.View, добавляя в него милые методы для работы с селекторами, выбором элементов и
 * дата атрибутами
 * @class Backbone.ElementsView
 * @extends Backbone.View
 */
Backbone.ElementsView = Backbone.View.redefine(function (origin) {
    return /**@lends Backbone.View*/{
        /**
         * @protected
         * @constructor
         */
        initialize: function () {
            this._cachedClasses = this._classes();

            /**
             * Здесь сохраняются закешированные селекторы, в том числе полученные из
             * {@link Backbone.ElementsView._classes}
             * @type {Object.<string, string>}
             * @private
             */
            this._cachedSelectors = this._selectors();

            /**
             * Кеш для {@link Backbone.ElementsView._elem}
             * @type {Object.<string, jQuery>}
             * @private
             */
            this._cachedElements = {};

            /**
             * Дата атрибуты {@link Backbone.View.$el} в camelCase
             * @type {Object.<string, string>}
             * @protected
             */
            this._data = this.$el.data();

            origin.initialize.apply(this, arguments);
        },

        /**
         * CSS классы используемые во вьюшке складываются сюда. Ключи - имена элементов, значение - названия классов.
         * Свойство можно переопределять в наследуемых классах
         * @returns {Object.<string, string>}
         * @protected
         * @example
         *     _classes: function(){
         *         return {
         *             table: 'js-table'
         *         };
         *     }
         *
         */
        _classes: function(){
            return {};
        },

        /**
         * Возвращает css класс элемента по его имени, классы берутся из {@link Backbone.ElementsView._classes}
         * @param {String} name название элемента
         * @returns {String} css класс
         * @throws {Error} если название елемента нигде не найдено
         * @protected
         */
        _class: function (name) {
            var cl = this._cachedClasses[name];
            if (cl == null) {
                throw new Error('Selector for ' + name + ' does not found');
            }

            return cl;
        },

        /**
         * Селекторы используемые во вьюшке описываются здесь. Метод надо переопределять в наследуемых классах
         * @returns {Object.<string, string>} Ключи - названия элементов, значения - селекторы
         * @protected
         * @example
         *      _selectors: function(){
         *          return {
         *              map: '.google-map:first'
         *          };
         *      }
         *
         */
        _selectors: function () {
            return {};
        },

        /**
         * Возвращает селектор элемента по его имени, селекторы берутся из {@link Backbone.ElementsView._selectors} или
         * {@link Backbone.ElementsView._classes}
         * @param {String} name название элемента
         * @returns {String} селектор
         * @protected
         * @example
         *      events: function(){
         *          var events = {};
         *          events['click ' + this._selector('map')] = this._clickOnMap;
         *          events['click ' + this._selector('table')] = this._clickOnTable;
         *          return events;
         *      }
         *
         */
        _selector: function (name) {
            var selector = this._cachedSelectors[name];
            if (selector != null) {
                return selector;
            }

            selector = '.' + this._class(name);
            this._cachedSelectors[name] = selector;

            return selector;
        },

        /**
         * Возвращает jQuery коллекцию по имени из {@link Backbone.ElementsView._selectors} или
         * {@link Backbone.ElementsView._classes}. Кэширует результаты, для сброса кеша см.
         * {@link Backbone.ElementsView._dropElemCache}
         * @param {String} name название элемента
         * @returns {jQuery}
         * @protected
         * @example
         *     this._elem('table').hide();
         *
         */
        _elem: function (name) {
            var $elem = this._cachedElements[name];
            if ($elem != null) {
                return $elem;
            }

            $elem = this.$(this._selector(name));
            this._cachedElements[name] = $elem;
            return $elem;
        },

        /**
         * Трет кеш для {@link Backbone.ElementsView._elem}
         * @param {String} [name] имя элемента для которого надо убрать кеш, если не задано - сотрется весь кеш
         * @protected
         */
        _dropElemCache: function (name) {
            if (name != null) {
                delete this._cachedElements[name];
            }
            else {
                this._cachedElements = {};
            }
        },

        /**
         * Возвращает дата атрибуты для элемента по его имени и имени атрибута
         * @param {String} name имя элемента
         * @param {String} [attr] имя атрибута, если не задано, то вернется объект со всеми дата атрибутами для элемента
         * @returns {*|Object}
         * @protected
         */
        _getElemData: function (name, attr) {
            var data = this._elem(name).data();
            if (attr == null) {
                return data;
            }

            return data[attr];
        }
    }
});<commit_msg>Backbone View _hasSelector method added<commit_after>/**
 * Подменяем и расширяем Backbone.View, добавляя в него милые методы для работы с селекторами, выбором элементов и
 * дата атрибутами
 * @class Backbone.ElementsView
 * @extends Backbone.View
 */
Backbone.ElementsView = Backbone.View.redefine(function (origin) {
    return /**@lends Backbone.View*/{
        /**
         * @protected
         * @constructor
         */
        initialize: function () {
            this._cachedClasses = this._classes();

            /**
             * Здесь сохраняются закешированные селекторы, в том числе полученные из
             * {@link Backbone.ElementsView._classes}
             * @type {Object.<string, string>}
             * @private
             */
            this._cachedSelectors = this._selectors();

            /**
             * Кеш для {@link Backbone.ElementsView._elem}
             * @type {Object.<string, jQuery>}
             * @private
             */
            this._cachedElements = {};

            /**
             * Дата атрибуты {@link Backbone.View.$el} в camelCase
             * @type {Object.<string, string>}
             * @protected
             */
            this._data = this.$el.data();

            origin.initialize.apply(this, arguments);
        },

        /**
         * CSS классы используемые во вьюшке складываются сюда. Ключи - имена элементов, значение - названия классов.
         * Свойство можно переопределять в наследуемых классах
         * @returns {Object.<string, string>}
         * @protected
         * @example
         *     _classes: function(){
         *         return {
         *             table: 'js-table'
         *         };
         *     }
         *
         */
        _classes: function(){
            return {};
        },

        /**
         * Возвращает css класс элемента по его имени, классы берутся из {@link Backbone.ElementsView._classes}
         * @param {String} name название элемента
         * @returns {String} css класс
         * @throws {Error} если название елемента нигде не найдено
         * @protected
         */
        _class: function (name) {
            var cl = this._cachedClasses[name];
            if (cl == null) {
                throw new Error('Selector for ' + name + ' does not found');
            }

            return cl;
        },

        /**
         * Селекторы используемые во вьюшке описываются здесь. Метод надо переопределять в наследуемых классах
         * @returns {Object.<string, string>} Ключи - названия элементов, значения - селекторы
         * @protected
         * @example
         *      _selectors: function(){
         *          return {
         *              map: '.google-map:first'
         *          };
         *      }
         *
         */
        _selectors: function () {
            return {};
        },

        /**
         * Возвращает селектор элемента по его имени, селекторы берутся из {@link Backbone.ElementsView._selectors} или
         * {@link Backbone.ElementsView._classes}
         * @param {String} name название элемента
         * @returns {String} селектор
         * @protected
         * @example
         *      events: function(){
         *          var events = {};
         *          events['click ' + this._selector('map')] = this._clickOnMap;
         *          events['click ' + this._selector('table')] = this._clickOnTable;
         *          return events;
         *      }
         *
         */
        _selector: function (name) {
            var selector = this._cachedSelectors[name];
            if (selector != null) {
                return selector;
            }

            selector = '.' + this._class(name);
            this._cachedSelectors[name] = selector;

            return selector;
        },

        /**
         * @param {String} name
         * @returns {Boolean}
         * @protected
         */
        _hasSelector: function (name) {
            return !!(this._cachedClasses[name] || this._cachedSelectors[name]);
        },

        /**
         * Возвращает jQuery коллекцию по имени из {@link Backbone.ElementsView._selectors} или
         * {@link Backbone.ElementsView._classes}. Кэширует результаты, для сброса кеша см.
         * {@link Backbone.ElementsView._dropElemCache}
         * @param {String} name название элемента
         * @returns {jQuery}
         * @protected
         * @example
         *     this._elem('table').hide();
         *
         */
        _elem: function (name) {
            var $elem = this._cachedElements[name];
            if ($elem != null) {
                return $elem;
            }

            $elem = this.$(this._selector(name));
            this._cachedElements[name] = $elem;
            return $elem;
        },

        /**
         * Трет кеш для {@link Backbone.ElementsView._elem}
         * @param {String} [name] имя элемента для которого надо убрать кеш, если не задано - сотрется весь кеш
         * @protected
         */
        _dropElemCache: function (name) {
            if (name != null) {
                delete this._cachedElements[name];
            }
            else {
                this._cachedElements = {};
            }
        },

        /**
         * Возвращает дата атрибуты для элемента по его имени и имени атрибута
         * @param {String} name имя элемента
         * @param {String} [attr] имя атрибута, если не задано, то вернется объект со всеми дата атрибутами для элемента
         * @returns {*|Object}
         * @protected
         */
        _getElemData: function (name, attr) {
            var data = this._elem(name).data();
            if (attr == null) {
                return data;
            }

            return data[attr];
        }
    }
});<|endoftext|>


<commit_before>/**
 * @module denali
 * @submodule runtime
 */

/**
 * Services are typically used to represent either external systems (i.e. a
 * caching service) or a cross-cutting, reusable piece of application logic
 * (i.e. an authorization / roles service).
 *
 * Services are mostly conventional - they are just singleton Denali.Objects
 * with no additional special behavior. The common base class ensures they are
 * singletons, makes user intent clear, and paves the way for introducing
 * additional common functionality in future versions of Denali.
 *
 * @class Service
 * @constructor
 */
export default class Service {}
<commit_msg>[jsdoc] Remove ervice Denali.Object comment<commit_after>/**
 * @module denali
 * @submodule runtime
 */

/**
 * Services are typically used to represent either external systems (i.e. a
 * caching service) or a cross-cutting, reusable piece of application logic
 * (i.e. an authorization / roles service).
 *
 * Services are mostly conventional - they are just singletons with no
 * special behavior. The common base class ensures they are
 * singletons, makes user intent clear, and paves the way for introducing
 * additional common functionality in future versions of Denali.
 *
 * @class Service
 * @constructor
 */
export default class Service {}
<|endoftext|>


<commit_before>/**
* correlation coefficients plotting using d3
* Isaak Y Tecle <iyt2@cornell.edu>
*
*/

jQuery(document).ready( function() {
    var page = document.URL;

    if (page.match(/solgs\/traits\/all\//) != null ||
        page.match(/solgs\/models\/combined\/trials\//) != null) {
        listGenCorPopulations();
    } else {
        phenotypicCorrelation();
    }
});

jQuery("#run_genetic_correlation").live("click", function() {
    var popId   = jQuery("#corre_selected_population_id").val();
    var popType = jQuery("#corre_selected_population_type").val();

    jQuery("#correlation_canvas").empty();

    jQuery("#correlation_message")
        .css({"padding-left": '0px'})
        .html("Running genetic correlation analysis...");

    formatGenCorInputData(popId, popType);

});

function listGenCorPopulations ()  {
    var modelData = getTrainingPopulationData();

    var trainingPopIdName = JSON.stringify(modelData);

    var  popsList =  '
'
        + '
 Choose a population
'
        + '
'
        + '
'
        + '
'
        + '' + modelData.name + '' + trainingPopIdName + ''
        + '
';

    popsList += '

';

    jQuery("#corre_select_a_population_div").empty().append(popsList).show();

    var dbSelPopsList;
    if (modelData.id.match(/uploaded/) == null) {
        dbSelPopsList = addSelectionPopulations();
    }

    if (dbSelPopsList) {
            jQuery("#corre_select_a_population_div ul").append(dbSelPopsList);
    }

    var userUploadedSelExists = jQuery("#uploaded_selection_pops_table").doesExist();
    if (userUploadedSelExists == true) {

        var userSelPops = listUploadedSelPopulations();
        if (userSelPops) {

            jQuery("#corre_select_a_population_div ul").append(userSelPops);
        }
    }

    jQuery(".corre_dropdown dt a").click(function() {
        jQuery(".corre_dropdown dd ul").toggle();
    });

    jQuery(".corre_dropdown dd ul li a").click(function() {

        var text = jQuery(this).html();

        jQuery(".corre_dropdown dt a span").html(text);
        jQuery(".corre_dropdown dd ul").hide();

        var idPopName = jQuery("#corre_selected_population").find("dt a span.value").html();
        idPopName     = JSON.parse(idPopName);
        modelId       = jQuery("#model_id").val();

        selectedPopId   = idPopName.id;
        selectedPopName = idPopName.name;
        selectedPopType = idPopName.pop_type;

        jQuery("#corre_selected_population_name").val(selectedPopName);
        jQuery("#corre_selected_population_id").val(selectedPopId);
        jQuery("#corre_selected_population_type").val(selectedPopType);

    });

    jQuery(".corre_dropdown").bind('click', function(e) {
        var clicked = jQuery(e.target);

        if (! clicked.parents().hasClass("corre_dropdown"))
            jQuery(".corre_dropdown dd ul").hide();

        e.preventDefault();

    });
}

function formatGenCorInputData (popId, type, indexFile) {
    var modelDetail = getPopulationDetails();

    jQuery.ajax({
        type: 'POST',
        dataType: 'json',
        data: {'model_id': modelDetail.population_id, 'corr_population_id': popId, 'type' : type, 'index_file': indexFile},
        url: '/correlation/genetic/data/',
        success: function(response) {

            if(response.status == 'success') {
                gebvsFile = response.gebvs_file;

                var divPlace;
                if(indexFile) {
                    divPlace = '#si_correlation_canvas';
                }

                var args = {
                    'model_id': modelDetail.population_id,
                    'corr_population_id': popId,
                    'type': type,
                    'gebvs_file': response.gebvs_file,
                    'div_place' : divPlace,
                };

                runGenCorrelationAnalysis(args);

            } else {
                jQuery("#correlation_message")
                    .css({"padding-left": '0px'})
                    .html("This population has no additive genetic data.");
            }
        },
        error: function(response) {
            jQuery("#correlation_message")
                .css({"padding-left": '0px'})
                .html("Error occured preparing the additive genetic data for correlation analysis.");

            jQuery.unblockUI();
        }
    });
}

function getPopulationDetails () {

    var populationId = jQuery("#population_id").val();
    var populationName = jQuery("#population_name").val();

    if (populationId == 'undefined') {
        populationId = jQuery("#model_id").val();
        populationName = jQuery("#model_name").val();
    }

    return {'population_id' : populationId,
            'population_name' : populationName
           };
}

function phenotypicCorrelation () {

    var population = getPopulationDetails();

    jQuery.ajax({
            type: 'POST',
            dataType: 'json',
            data: {'population_id': population.population_id },
            url: '/correlation/phenotype/data/',
            success: function(response) {
                if (response.status == 'success') {
                    runPhenoCorrelationAnalysis();
                } else {
                    jQuery("#correlation_message")
                        .css({"padding-left": '0px'})
                        .html("This population has no phenotype data.");
                }
            },
            error: function(response) {
                jQuery("#correlation_message")
                    .css({"padding-left": '0px'})
                    .html("Error occured preparing the phenotype data for correlation analysis.");
            }
    });
}

function runPhenoCorrelationAnalysis () {
    var population = getPopulationDetails();

    jQuery.ajax({
        type: 'POST',
        dataType: 'json',
        data: {'population_id': population.population_id },
        url: '/phenotypic/correlation/analysis/output',
        success: function(response) {
            if (response.status == 'success') {
                plotCorrelation(response.data);
                jQuery("#correlation_message").empty();
            } else {
                jQuery("#correlation_message")
                    .css({"padding-left": '0px'})
                    .html("There is no correlation output for this dataset.");
            }
        },
        error: function(response) {
            jQuery("#correlation_message")
                .css({"padding-left": '0px'})
                .html("Error occured running the correlation analysis.");
        }
    });
}

function runGenCorrelationAnalysis (args) {

    jQuery.ajax({
        type: 'POST',
        dataType: 'json',
        data: args,
        url: '/genetic/correlation/analysis/output',
        success: function(response) {
            if (response.status == 'success') {

                divPlace = args.div_place;

                if (divPlace === '#si_correlation_canvas') {
                    jQuery("#si_correlation_section").show();
                }

                plotCorrelation(response.data, divPlace);
                jQuery("#correlation_message").empty();
                jQuery("#si_correlation_message").empty();

                if (divPlace === '#si_correlation_canvas') {

                    var popName   = jQuery("#selected_population_name").val();
                    var corLegDiv = "

";

                    var legendValues = legendParams();
                    var corLegDivVal = jQuery(corLegDiv).html(legendValues.legend);

                    jQuery("#si_correlation_canvas").append(corLegDivVal).show();

                } else {

                    var popName = jQuery("#corre_selected_population_name").val();
                    var corLegDiv  = "

";

                    var corLegDivVal = jQuery(corLegDiv).html(popName);
                    jQuery("#correlation_canvas").append(corLegDivVal).show();
                }

            } else {
                jQuery("#correlation_message")
                    .css({"padding-left": '0px'})
                    .html("There is no genetic correlation output for this dataset.");
            }

            jQuery.unblockUI();
        },
        error: function(response) {
            jQuery("#correlation_message")
                .css({"padding-left": '0px'})
                .html("Error occured running the genetic correlation analysis.");

            jQuery.unblockUI();
        }
    });
}

function plotCorrelation (data, divPlace) {

    data = data.replace(/\s/g, '');
    data = data.replace(/\\/g, '');
    data = data.replace(/^\"/, '');
    data = data.replace(/\"$/, '');
    data = data.replace(/\"NA\"/g, 100);

    data = JSON.parse(data);

    var height = 400;
    var width  = 400;

    var nTraits = data.traits.length;

    if (nTraits < 8) {
        height = height * 0.5;
        width  = width  * 0.5;
    }

    var pad    = {left:70, top:20, right:100, bottom: 70};
    var totalH = height + pad.top + pad.bottom;
    var totalW = width + pad.left + pad.right;

    var corXscale = d3.scale.ordinal().domain(d3.range(nTraits)).rangeBands([0, width]);
    var corYscale = d3.scale.ordinal().domain(d3.range(nTraits)).rangeBands([height, 0]);
    var corZscale = d3.scale.linear().domain([-1, 0, 1]).range(["#6A0888","white", "#86B404"]);

    var xAxisScale = d3.scale.ordinal()
        .domain(data.traits)
        .rangeBands([0, width]);

    var yAxisScale = d3.scale.ordinal()
        .domain(data.traits)
        .rangeRoundBands([height, 0]);

    if ( divPlace == null) {
        divPlace = '#correlation_canvas';
    }

    var svg = d3.select(divPlace)
        .append("svg")
        .attr("height", totalH)
        .attr("width", totalW);

    var xAxis = d3.svg.axis()
        .scale(xAxisScale)
        .orient("bottom");

    var yAxis = d3.svg.axis()
        .scale(yAxisScale)
        .orient("left");

    var corrplot = svg.append("g")
        .attr("id", "correlation_plot")
        .attr("transform", "translate(" + pad.left + "," + pad.top + ")");

    corrplot.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height +")")
        .call(xAxis)
        .selectAll("text")
        .attr("y", 0)
        .attr("x", 10)
        .attr("dy", ".1em")
        .attr("transform", "rotate(90)")
        .attr("fill", "purple")
        .style({"text-anchor":"start", "fill": "#3306FC"});

    corrplot.append("g")
        .attr("class", "y axis")
        .attr("transform", "translate(0,0)")
        .call(yAxis)
        .selectAll("text")
        .attr("y", 0)
        .attr("x", -10)
        .attr("dy", ".1em")
        .attr("fill", "#523CB5")
        .style("fill", "#523CB5");

    var corr = [];
    var coefs = [];
    for (var i=0; i<data.coefficients.length; i++) {
        for (var j=0;  j<data.coefficients[i].length; j++) {
            corr.push({"row":i, "col":j, "value": data.coefficients[i][j]});

            if (data.coefficients[i][j] != 100) {
                coefs.push(data.coefficients[i][j]);
            }
        }
    }

    var cell = corrplot.selectAll("rect")
        .data(corr)
        .enter().append("rect")
        .attr("class", "cell")
        .attr("x", function (d) { return corXscale(d.col)})
        .attr("y", function (d) { return corYscale(d.row)})
        .attr("width", corXscale.rangeBand())
        .attr("height", corYscale.rangeBand())
        .attr("fill", function (d) {
                if (d.value === 100) {return "white";}
                else {return corZscale(d.value)}
            })
        .attr("stroke", "white")
        .attr("stroke-width", 1)
        .on("mouseover", function (d) {
                if(d.value != 100) {
                    d3.select(this)
                        .attr("stroke", "green")
                    corrplot.append("text")
                        .attr("id", "corrtext")
                        .text("[" + data.traits[d.row]
                              + " vs. " + data.traits[d.col]
                              + ": " + d3.format(".2f")(d.value)
                              + "]")
                        .style("fill", function () {
                            if (d.value > 0)
                            { return "#86B404"; }
                            else if (d.value < 0)
                            { return "#6A0888"; }
                        })
                        .attr("x", totalW * 0.5)
                        .attr("y", totalH * 0.5)
                        .attr("font-weight", "bold")
                        .attr("dominant-baseline", "middle")
                        .attr("text-anchor", "middle")
                }
        })
        .on("mouseout", function() {
                d3.selectAll("text.corrlabel").remove()
                d3.selectAll("text#corrtext").remove()
                d3.select(this).attr("stroke","white")
            });

    corrplot.append("rect")
        .attr("height", height)
        .attr("width", width)
        .attr("fill", "none")
        .attr("stroke", "#523CB5")
        .attr("stroke-width", 1)
        .attr("pointer-events", "none");

    var legendValues = [];

    if (d3.min(coefs) > 0 && d3.max(coefs) > 0 ) {
        legendValues = [[0, 0], [1, d3.max(coefs)]];
    } else if (d3.min(coefs) < 0 && d3.max(coefs) < 0 )  {
        legendValues = [[0, d3.min(coefs)], [1, 0]];
    } else {
        legendValues = [[0, d3.min(coefs)], [1, 0], [2, d3.max(coefs)]];
    }

    var legend = corrplot.append("g")
        .attr("class", "cell")
        .attr("transform", "translate(" + (width + 10) + "," +  (height * 0.25) + ")")
        .attr("height", 100)
        .attr("width", 100);

    var recLH = 20;
    var recLW = 20;

    legend = legend.selectAll("rect")
        .data(legendValues)
        .enter()
        .append("rect")
        .attr("x", function (d) { return 1;})
        .attr("y", function (d) {return 1 + (d[0] * recLH) + (d[0] * 5); })
        .attr("width", recLH)
        .attr("height", recLW)
        .style("stroke", "black")
        .attr("fill", function (d) {
            if (d === 100) {return "white"}
            else {return corZscale(d[1])}
        });

    var legendTxt = corrplot.append("g")
        .attr("transform", "translate(" + (width + 40) + "," + ((height * 0.25) + (0.5 * recLW)) + ")")
        .attr("id", "legendtext");

    legendTxt.selectAll("text")
        .data(legendValues)
        .enter()
        .append("text")
        .attr("fill", "#523CB5")
        .style("fill", "#523CB5")
        .attr("x", 1)
        .attr("y", function (d) { return 1 + (d[0] * recLH) + (d[0] * 5); })
        .text(function (d) {
            if (d[1] > 0) { return "Positive"; }
            else if (d[1] < 0) { return "Negative"; }
            else if (d[1] === 0) { return "Neutral"; }
        })
        .attr("dominant-baseline", "middle")
        .attr("text-anchor", "start");

}

<commit_msg>match axes colors..<commit_after>/**
* correlation coefficients plotting using d3
* Isaak Y Tecle <iyt2@cornell.edu>
*
*/

jQuery(document).ready( function() {
    var page = document.URL;

    if (page.match(/solgs\/traits\/all\//) != null ||
        page.match(/solgs\/models\/combined\/trials\//) != null) {
        listGenCorPopulations();
    } else {
        phenotypicCorrelation();
    }
});

jQuery("#run_genetic_correlation").live("click", function() {
    var popId   = jQuery("#corre_selected_population_id").val();
    var popType = jQuery("#corre_selected_population_type").val();

    jQuery("#correlation_canvas").empty();

    jQuery("#correlation_message")
        .css({"padding-left": '0px'})
        .html("Running genetic correlation analysis...");

    formatGenCorInputData(popId, popType);

});

function listGenCorPopulations ()  {
    var modelData = getTrainingPopulationData();

    var trainingPopIdName = JSON.stringify(modelData);

    var  popsList =  '
'
        + '
 Choose a population
'
        + '
'
        + '
'
        + '
'
        + '' + modelData.name + '' + trainingPopIdName + ''
        + '
';

    popsList += '

';

    jQuery("#corre_select_a_population_div").empty().append(popsList).show();

    var dbSelPopsList;
    if (modelData.id.match(/uploaded/) == null) {
        dbSelPopsList = addSelectionPopulations();
    }

    if (dbSelPopsList) {
            jQuery("#corre_select_a_population_div ul").append(dbSelPopsList);
    }

    var userUploadedSelExists = jQuery("#uploaded_selection_pops_table").doesExist();
    if (userUploadedSelExists == true) {

        var userSelPops = listUploadedSelPopulations();
        if (userSelPops) {

            jQuery("#corre_select_a_population_div ul").append(userSelPops);
        }
    }

    jQuery(".corre_dropdown dt a").click(function() {
        jQuery(".corre_dropdown dd ul").toggle();
    });

    jQuery(".corre_dropdown dd ul li a").click(function() {

        var text = jQuery(this).html();

        jQuery(".corre_dropdown dt a span").html(text);
        jQuery(".corre_dropdown dd ul").hide();

        var idPopName = jQuery("#corre_selected_population").find("dt a span.value").html();
        idPopName     = JSON.parse(idPopName);
        modelId       = jQuery("#model_id").val();

        selectedPopId   = idPopName.id;
        selectedPopName = idPopName.name;
        selectedPopType = idPopName.pop_type;

        jQuery("#corre_selected_population_name").val(selectedPopName);
        jQuery("#corre_selected_population_id").val(selectedPopId);
        jQuery("#corre_selected_population_type").val(selectedPopType);

    });

    jQuery(".corre_dropdown").bind('click', function(e) {
        var clicked = jQuery(e.target);

        if (! clicked.parents().hasClass("corre_dropdown"))
            jQuery(".corre_dropdown dd ul").hide();

        e.preventDefault();

    });
}

function formatGenCorInputData (popId, type, indexFile) {
    var modelDetail = getPopulationDetails();

    jQuery.ajax({
        type: 'POST',
        dataType: 'json',
        data: {'model_id': modelDetail.population_id, 'corr_population_id': popId, 'type' : type, 'index_file': indexFile},
        url: '/correlation/genetic/data/',
        success: function(response) {

            if(response.status == 'success') {
                gebvsFile = response.gebvs_file;

                var divPlace;
                if(indexFile) {
                    divPlace = '#si_correlation_canvas';
                }

                var args = {
                    'model_id': modelDetail.population_id,
                    'corr_population_id': popId,
                    'type': type,
                    'gebvs_file': response.gebvs_file,
                    'div_place' : divPlace,
                };

                runGenCorrelationAnalysis(args);

            } else {
                jQuery("#correlation_message")
                    .css({"padding-left": '0px'})
                    .html("This population has no additive genetic data.");
            }
        },
        error: function(response) {
            jQuery("#correlation_message")
                .css({"padding-left": '0px'})
                .html("Error occured preparing the additive genetic data for correlation analysis.");

            jQuery.unblockUI();
        }
    });
}

function getPopulationDetails () {

    var populationId = jQuery("#population_id").val();
    var populationName = jQuery("#population_name").val();

    if (populationId == 'undefined') {
        populationId = jQuery("#model_id").val();
        populationName = jQuery("#model_name").val();
    }

    return {'population_id' : populationId,
            'population_name' : populationName
           };
}

function phenotypicCorrelation () {

    var population = getPopulationDetails();

    jQuery.ajax({
            type: 'POST',
            dataType: 'json',
            data: {'population_id': population.population_id },
            url: '/correlation/phenotype/data/',
            success: function(response) {
                if (response.status == 'success') {
                    runPhenoCorrelationAnalysis();
                } else {
                    jQuery("#correlation_message")
                        .css({"padding-left": '0px'})
                        .html("This population has no phenotype data.");
                }
            },
            error: function(response) {
                jQuery("#correlation_message")
                    .css({"padding-left": '0px'})
                    .html("Error occured preparing the phenotype data for correlation analysis.");
            }
    });
}

function runPhenoCorrelationAnalysis () {
    var population = getPopulationDetails();

    jQuery.ajax({
        type: 'POST',
        dataType: 'json',
        data: {'population_id': population.population_id },
        url: '/phenotypic/correlation/analysis/output',
        success: function(response) {
            if (response.status == 'success') {
                plotCorrelation(response.data);
                jQuery("#correlation_message").empty();
            } else {
                jQuery("#correlation_message")
                    .css({"padding-left": '0px'})
                    .html("There is no correlation output for this dataset.");
            }
        },
        error: function(response) {
            jQuery("#correlation_message")
                .css({"padding-left": '0px'})
                .html("Error occured running the correlation analysis.");
        }
    });
}

function runGenCorrelationAnalysis (args) {

    jQuery.ajax({
        type: 'POST',
        dataType: 'json',
        data: args,
        url: '/genetic/correlation/analysis/output',
        success: function(response) {
            if (response.status == 'success') {

                divPlace = args.div_place;

                if (divPlace === '#si_correlation_canvas') {
                    jQuery("#si_correlation_section").show();
                }

                plotCorrelation(response.data, divPlace);
                jQuery("#correlation_message").empty();
                jQuery("#si_correlation_message").empty();

                if (divPlace === '#si_correlation_canvas') {

                    var popName   = jQuery("#selected_population_name").val();
                    var corLegDiv = "

";

                    var legendValues = legendParams();
                    var corLegDivVal = jQuery(corLegDiv).html(legendValues.legend);

                    jQuery("#si_correlation_canvas").append(corLegDivVal).show();

                } else {

                    var popName = jQuery("#corre_selected_population_name").val();
                    var corLegDiv  = "

";

                    var corLegDivVal = jQuery(corLegDiv).html(popName);
                    jQuery("#correlation_canvas").append(corLegDivVal).show();
                }

            } else {
                jQuery("#correlation_message")
                    .css({"padding-left": '0px'})
                    .html("There is no genetic correlation output for this dataset.");
            }

            jQuery.unblockUI();
        },
        error: function(response) {
            jQuery("#correlation_message")
                .css({"padding-left": '0px'})
                .html("Error occured running the genetic correlation analysis.");

            jQuery.unblockUI();
        }
    });
}

function plotCorrelation (data, divPlace) {

    data = data.replace(/\s/g, '');
    data = data.replace(/\\/g, '');
    data = data.replace(/^\"/, '');
    data = data.replace(/\"$/, '');
    data = data.replace(/\"NA\"/g, 100);

    data = JSON.parse(data);

    var height = 400;
    var width  = 400;

    var nTraits = data.traits.length;

    if (nTraits < 8) {
        height = height * 0.5;
        width  = width  * 0.5;
    }

    var pad    = {left:70, top:20, right:100, bottom: 70};
    var totalH = height + pad.top + pad.bottom;
    var totalW = width + pad.left + pad.right;

    var corXscale = d3.scale.ordinal().domain(d3.range(nTraits)).rangeBands([0, width]);
    var corYscale = d3.scale.ordinal().domain(d3.range(nTraits)).rangeBands([height, 0]);
    var corZscale = d3.scale.linear().domain([-1, 0, 1]).range(["#6A0888","white", "#86B404"]);

    var xAxisScale = d3.scale.ordinal()
        .domain(data.traits)
        .rangeBands([0, width]);

    var yAxisScale = d3.scale.ordinal()
        .domain(data.traits)
        .rangeRoundBands([height, 0]);

    if ( divPlace == null) {
        divPlace = '#correlation_canvas';
    }

    var svg = d3.select(divPlace)
        .append("svg")
        .attr("height", totalH)
        .attr("width", totalW);

    var xAxis = d3.svg.axis()
        .scale(xAxisScale)
        .orient("bottom");

    var yAxis = d3.svg.axis()
        .scale(yAxisScale)
        .orient("left");

    var corrplot = svg.append("g")
        .attr("id", "correlation_plot")
        .attr("transform", "translate(" + pad.left + "," + pad.top + ")");

    corrplot.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height +")")
        .call(xAxis)
        .selectAll("text")
        .attr("y", 0)
        .attr("x", 10)
        .attr("dy", ".1em")
        .attr("transform", "rotate(90)")
        .attr("fill", "#523CB5")
        .style({"text-anchor":"start", "fill": "#523CB5"});

    corrplot.append("g")
        .attr("class", "y axis")
        .attr("transform", "translate(0,0)")
        .call(yAxis)
        .selectAll("text")
        .attr("y", 0)
        .attr("x", -10)
        .attr("dy", ".1em")
        .attr("fill", "#523CB5")
        .style("fill", "#523CB5");

    var corr = [];
    var coefs = [];
    for (var i=0; i<data.coefficients.length; i++) {
        for (var j=0;  j<data.coefficients[i].length; j++) {
            corr.push({"row":i, "col":j, "value": data.coefficients[i][j]});

            if (data.coefficients[i][j] != 100) {
                coefs.push(data.coefficients[i][j]);
            }
        }
    }

    var cell = corrplot.selectAll("rect")
        .data(corr)
        .enter().append("rect")
        .attr("class", "cell")
        .attr("x", function (d) { return corXscale(d.col)})
        .attr("y", function (d) { return corYscale(d.row)})
        .attr("width", corXscale.rangeBand())
        .attr("height", corYscale.rangeBand())
        .attr("fill", function (d) {
                if (d.value === 100) {return "white";}
                else {return corZscale(d.value)}
            })
        .attr("stroke", "white")
        .attr("stroke-width", 1)
        .on("mouseover", function (d) {
                if(d.value != 100) {
                    d3.select(this)
                        .attr("stroke", "green")
                    corrplot.append("text")
                        .attr("id", "corrtext")
                        .text("[" + data.traits[d.row]
                              + " vs. " + data.traits[d.col]
                              + ": " + d3.format(".2f")(d.value)
                              + "]")
                        .style("fill", function () {
                            if (d.value > 0)
                            { return "#86B404"; }
                            else if (d.value < 0)
                            { return "#6A0888"; }
                        })
                        .attr("x", totalW * 0.5)
                        .attr("y", totalH * 0.5)
                        .attr("font-weight", "bold")
                        .attr("dominant-baseline", "middle")
                        .attr("text-anchor", "middle")
                }
        })
        .on("mouseout", function() {
                d3.selectAll("text.corrlabel").remove()
                d3.selectAll("text#corrtext").remove()
                d3.select(this).attr("stroke","white")
            });

    corrplot.append("rect")
        .attr("height", height)
        .attr("width", width)
        .attr("fill", "none")
        .attr("stroke", "#523CB5")
        .attr("stroke-width", 1)
        .attr("pointer-events", "none");

    var legendValues = [];

    if (d3.min(coefs) > 0 && d3.max(coefs) > 0 ) {
        legendValues = [[0, 0], [1, d3.max(coefs)]];
    } else if (d3.min(coefs) < 0 && d3.max(coefs) < 0 )  {
        legendValues = [[0, d3.min(coefs)], [1, 0]];
    } else {
        legendValues = [[0, d3.min(coefs)], [1, 0], [2, d3.max(coefs)]];
    }

    var legend = corrplot.append("g")
        .attr("class", "cell")
        .attr("transform", "translate(" + (width + 10) + "," +  (height * 0.25) + ")")
        .attr("height", 100)
        .attr("width", 100);

    var recLH = 20;
    var recLW = 20;

    legend = legend.selectAll("rect")
        .data(legendValues)
        .enter()
        .append("rect")
        .attr("x", function (d) { return 1;})
        .attr("y", function (d) {return 1 + (d[0] * recLH) + (d[0] * 5); })
        .attr("width", recLH)
        .attr("height", recLW)
        .style("stroke", "black")
        .attr("fill", function (d) {
            if (d === 100) {return "white"}
            else {return corZscale(d[1])}
        });

    var legendTxt = corrplot.append("g")
        .attr("transform", "translate(" + (width + 40) + "," + ((height * 0.25) + (0.5 * recLW)) + ")")
        .attr("id", "legendtext");

    legendTxt.selectAll("text")
        .data(legendValues)
        .enter()
        .append("text")
        .attr("fill", "#523CB5")
        .style("fill", "#523CB5")
        .attr("x", 1)
        .attr("y", function (d) { return 1 + (d[0] * recLH) + (d[0] * 5); })
        .text(function (d) {
            if (d[1] > 0) { return "Positive"; }
            else if (d[1] < 0) { return "Negative"; }
            else if (d[1] === 0) { return "Neutral"; }
        })
        .attr("dominant-baseline", "middle")
        .attr("text-anchor", "start");

}

<|endoftext|>


<commit_before>/**
 * Clone.js
 *
 * Full source at http://github.com/mdarse/clone.js
 * Copyright (c) 2013 Mathieu Darse <hello@mathieudarse.fr>
 *
 * Clone.js may be freely distributed under the MIT license.
 */
Object.clone || Object.clone = function clone(object, deepClone, clonePrototype) {
    var visited = [],
        set = [];
    return _clone(object);

    function _clone(object) {
        if (typeof object !== 'object' || object === null) { // because typeof null => 'object'
            // immutable primitive types (string, number, boolean, undefined), function or null
            clone = object;
        } else {
            var index = visited.indexOf(object), clone;
            if (index === -1) {
                clone = _createInstance(object);
                visited.push(object);
                set.push(clone);
                _extend(clone, object);
            } else {
                clone = set[index];
            }
        }
        return clone;
    }

    function _createInstance(object) {
        var className = Object.prototype.toString.call(object).slice(8, -1);
        switch (className) {
            // primitive wrapper types
            case 'Boolean':
                return new Boolean(!!object);
            case 'Number': // includes NaN
                return new Number(+object);
            case 'String':
                return new String('' + object);
            // special types
            case 'Function': // TODO clone with Function.prototype.bind ?
            case 'Error':
                return object; // Can't clone these
            case 'Date':
                return new Date(+object);
            case 'RegExp':
                return new RegExp(object);
            // regular types
            case 'Array':
                return new Array(object.length);
            case 'Object':
                var prototype = Object.getPrototypeOf(object);
                if (clonePrototype && prototype !== Object.prototype) {
                    var ctorDescriptor = {
                        value: prototype.constructor,
                        writable: true,
                        enumerable: false,
                        configurable: true
                    };
                    prototype = _clone(prototype);
                    Object.defineProperty(prototype, 'constructor', ctorDescriptor);
                }
                return Object.create(prototype);
            default:
                throw new TypeError("Can't clone object, type \"%1\" is unsupported".replace('%1', className));
        }
    }

    function _extend(base, object) {
        if (base === object) return;
        var keys = Object.keys(object);
        // var keys = Object.getOwnPropertyNames(object);
        for (var i = 0, l = keys.length; i < l; i++) {
            var key = keys[i];
            var value = object[key];
            var descriptor = Object.getOwnPropertyDescriptor(object, key);
            descriptor.value = deepClone ? _clone(value) : value;
            Object.defineProperty(base, key, descriptor);
        }
    }
};
<commit_msg>Clone functions by wrapping them<commit_after>/**
 * Clone.js
 *
 * Full source at http://github.com/mdarse/clone.js
 * Copyright (c) 2013 Mathieu Darse <hello@mathieudarse.fr>
 *
 * Clone.js may be freely distributed under the MIT license.
 */
Object.clone || Object.clone = function clone(object, deepClone, clonePrototype) {
    var visited = [],
        set = [];
    return _clone(object);

    function _clone(object) {
        if (typeof object !== 'object' || object === null) { // because typeof null => 'object'
            // immutable primitive types (string, number, boolean, undefined), function or null
            clone = object;
        } else {
            var index = visited.indexOf(object), clone;
            if (index === -1) {
                clone = _createInstance(object);
                visited.push(object);
                set.push(clone);
                _extend(clone, object);
            } else {
                clone = set[index];
            }
        }
        return clone;
    }

    function _createInstance(object) {
        var className = Object.prototype.toString.call(object).slice(8, -1);
        switch (className) {
            // primitive wrapper types
            case 'Boolean':
                return new Boolean(!!object);
            case 'Number': // includes NaN
                return new Number(+object);
            case 'String':
                return new String('' + object);
            // special types
            case 'Function':
                // Wrap functions because they can have object properties
                // We loose function name here, but it is not a standard property
                var wrap = function cloneWrap() {
                    // We reuse original wrapped function to prevent nested wrappers
                    (object.__wrapped__ || object).apply(this, arguments);
                };
                Object.defineProperty(wrap, '__wrapped__', {
                    value: object,
                    writable: false,
                    enumerable: false,
                    configurable: false
                });
                return wrap;
            case 'Error':
                return object; // Can't clone these
            case 'Date':
                return new Date(+object);
            case 'RegExp':
                return new RegExp(object);
            // regular types
            case 'Array':
                return new Array(object.length);
            case 'Object':
                var prototype = Object.getPrototypeOf(object);
                if (clonePrototype && prototype !== Object.prototype) {
                    var ctorDescriptor = {
                        value: prototype.constructor,
                        writable: true,
                        enumerable: false,
                        configurable: true
                    };
                    prototype = _clone(prototype);
                    Object.defineProperty(prototype, 'constructor', ctorDescriptor);
                }
                return Object.create(prototype);
            default:
                throw new TypeError("Can't clone object, type \"%1\" is unsupported".replace('%1', className));
        }
    }

    function _extend(base, object) {
        if (base === object) return;
        var keys = Object.keys(object);
        // var keys = Object.getOwnPropertyNames(object);
        for (var i = 0, l = keys.length; i < l; i++) {
            var key = keys[i];
            var value = object[key];
            var descriptor = Object.getOwnPropertyDescriptor(object, key);
            descriptor.value = deepClone ? _clone(value) : value;
            Object.defineProperty(base, key, descriptor);
        }
    }
};
<|endoftext|>


<commit_before><commit_msg>Do knife stab check before doing equip knife check<commit_after><|endoftext|>


<commit_before>---
---
var sponsorOverride = {
  '62463-balzss': {
    url: 'https://balzss.github.io/',
  },
  '41853-ergodox-ez': {
    url: 'http://www.ergodox-ez.com',
    frontImageUrl: '/images/sponsors/ergodox-ez-logo.png'
  },
  '37206-ganwell': {
    url: 'http://ganwell.github.io/neovim.html',
    frontImageUrl: '/images/sponsors/ganwell.png',
  },
  '32537-hautelook': {
    url: 'http://hautelook.github.io/',
    frontImageUrl: '/images/sponsors/hautelook-logo.png',
  },
  '32681-namely-labs-namelyhr-namely-com': {
    url: 'http://www.namely.com/',
    frontImageUrl: '/images/sponsors/Namely_logo.jpg',
  },
  '39969-blumenversand': {
    url: 'https://blumenversender.com',
  },
  '34279-pygeek': {
    url: 'http://pygeek.com',
  },
  '34942-madis-nomme': {
    url: 'https://mad.is',
    name: 'Madis Nõmme'
  },
  '347-stefanpenner': {
    url: 'http://iamstef.net/',
  },
  '32451-twokul': {
    url: 'http://twokul.io',
  },
  '26545-kvannotten': {
    url: 'https://kristof.io',
  },
  '32345-jtinsky': {
    url: 'http://rutherstone.net/wp/',
  },
  '32362-vagmi': {
    url: 'http://coderwall.com/vagmi',
  },
  '23966-wbinnssmith': {
    url: 'http://wbinnssmith.com',
  },
  '30557-nemith': {
    url: 'http://inetpro.org',
  },
  '32395-apskim': {
    url: 'http://alexpolozov.com',
  },
  '24658-ndj': {
    url: 'dejonghenico.be',
  },
  '24164-mikl': {
    url: 'http://mikkel.hoegh.org/',
  },
  '32439-lsocrate': {
    url: 'http://www.socrate.com.br/',
  },
  '23889-dphase': {
    url: 'http://dphase.net',
  },
  '20492-victorbjelkholm': {
    url: 'http://twitter.com/VictorBjelkholm',
  },
  '24103-demizer': {
    url: 'www.demizerone.com',
  },
  '30137-ianks': {
    url: 'http://ianks.com',
  },
  '32359-jwhear': {
    url: 'www.economicmodeling.com',
  },
  '32367-dhruvasagar': {
    url: 'http://dhruvasagar.com/',
  },
  '24566-bruno': {
    url: 'http://greenbackyard.net',
  },
  '24014-tarrant': {
    url: 'http://daemonomicon.com',
  },
  '32394-tim': {
    url: 'http://tfletcher.com/',
  },
  '24354-wezm': {
    url: 'http://www.wezm.net/',
  },
  '32398-dshills': {
    url: 'http://dsgeek.blogspot.com/',
  },
  '32399-bwells': {
    url: 'www.altalang.com',
  },
  '32427-okaythree': {
    url: 'http://okaythree.com',
  },
  '26081-eglimi': {
    url: 'http://wisol.ch',
  },
  '32480-igort': {
    url: 'http://terzicigor.com/',
  },
  '24120-xvilka': {
    url: 'http://www.xvilka.me/',
  },
  '24042-macat': {
    url: 'https://twitter.com/macat',
  },
  '24386-drodger': {
    url: 'devslant.com',
  },
  '32584-zefei': {
    url: 'http://zef.io/',
  },
  '26581-gotgenes': {
    url: 'http://www.gotgenes.com/',
  },
  '25130-jwoudenberg': {
    url: 'http://jasperwoudenberg.com',
  },
  '32617-musically-ut': {
    url: 'http://musicallyut.in',
  },
  '32629-jhchabran': {
    url: 'http://jhchabran.com',
  },
  '32644-tchak': {
    url: 'http://capitainetrain.com',
  },
  '23874-leon-barrett': {
    url: 'http://leon.barrettnexus.com/',
  },
  '24543-jamesaoverton': {
    url: 'http://james.overton.ca',
  },
  '24499-jochen': {
    url: 'http://www.zerties.org',
  },
  '24721-tmandry': {
    url: 'https://www.linkedin.com/profile/view?id=79377885',
  },
  '25052-jwhitley': {
    url: 'http://bangpath.org/',
  },
  '33151-m42e': {
    url: 'https://bilger.info',
  },
  '32833-velrok': {
    url: 'velrok.github.io',
  },
  '32311-rach': {
    url: 'http://lostpropertyhq.com',
  },
  '20347-derickbailey': {
    url: 'http://derickbailey.com',
  },
  '17979-thejspr': {
    url: 'https://thejspr.com',
  },
  '32315-jthomas': {
    url: 'http://jamesthom.as',
  },
  '32317-mikker': {
    url: 'http://mikker.github.io',
  },
  '27722-dictvm': {
    url: 'https://blog.dictvm.org',
  },
  '22105-brunohenrique': {
    url: 'http://garulab.com/',
  },
  '24693-xsb': {
    url: 'http://xavisb.com',
  },
  '24401-dirkr': {
    url: 'http://niebegeg.net',
  },
  '32328-skattyadz': {
    url: 'imakesh.it',
  },
  '29586-davidosomething': {
    url: 'http://davidosomething.com/',
  },
  '32332-kennykaye': {
    url: 'http://kaye.us',
  },
  '32334-lerrua': {
    url: 'http://www.lerrua.com',
  },
  '24125-beloglazov': {
    url: 'http://beloglazov.info',
  },
  '32340-rillian': {
    url: 'http://advogato.org/person/rillian',
  },
  '28042-justinnhli': {
    url: 'http://justinnhli.com/',
  },
  '23870-fortes': {
    url: 'http://www.fortes.com/',
  },
  '32342-badeip': {
    url: 'https://www.twitter.com/badeip',
  },
  '32348-udp': {
    url: 'fieryclock.com',
  },
  '32352-adambiggs': {
    url: 'lightmaker.com',
  },
  '24970-hallettj': {
    url: 'http://sitr.us/',
  },
  '32363-apenney': {
    url: 'http://www.ntoggle.com',
  },
  '24148-alxndr': {
    url: 'http://eleven-twelve.net',
  },
  '24338-adri': {
    url: 'http://adrian-philipp.com',
  },
  '27129-pipeep': {
    url: 'http://benjam.info/',
  },
  '24937-bilalq': {
    url: 'http://bilalquadri.com',
  },
  '32381-kkuchta': {
    url: 'http://www.kevinkuchta.com',
  },
  '23998-rolisz': {
    url: 'https://rolisz.ro',
  },
  '32383-objectivetruth': {
    url: 'http://www.objectivetruth.ca',
  },
  '32388-norcalli': {
    url: 'norcalli.com',
  },
  '23915-joebadmo': {
    url: 'https://joe.xoxomoon.com',
  },
  '32389-faun': {
    url: 'http://www.faun.me',
  },
  '32403-stanimir-mladenov': {
    url: 'www.zoneprojects.com',
  },
  '32404-phlip9': {
    url: 'phlip9.com',
  },
  '24003-kopischke': {
    url: 'http://martin.kopischke.net',
  },
  '32417-azp': {
    url: 'http://volatileint.blogspot.com',
  },
  '32385-actionshrimp': {
    url: 'www.actionshrimp.com',
  },
  '18449-brainopia': {
    url: 'http://twitter.com/brainopia',
  },
  '32432-davidlowryduda': {
    url: 'http://davidlowryduda.com',
  },
  '24062-grahams': {
    url: 'http://sean-graham.com/',
  },
  '31425-bertocq': {
    url: 'http://www.bertocq.es',
  },
  '24163-linduxed': {
    url: 'http://www.linduxed.se',
  },
  '20659-jakesjews': {
    url: 'http://www.immersiveapplications.com',
  },
  '32445-joesfer': {
    url: 'http://www.joesfer.com',
  },
  '32415-p8952': {
    url: 'https://p8952.info',
  },
  '24655-tejo': {
    url: 'http://www.parmi.it',
  },
  '32477-neh': {
    url: 'http://nathanhowell.net',
  },
  '32479-topaxi': {
    url: 'http://topaxi.ch/',
  },
  '30935-danthecoloradan': {
    url: 'http://www.blazingaddles.com',
  },
  '32521-gypsydave5': {
    url: 'http://gypsydave5.com',
  },
  '25643-seebi': {
    url: 'http://sebastian.tramp.name',
  },
  '22048-ugtastic': {
    url: 'http://www.ugtastic.com',
  },
  '32550-luctus': {
    url: 'http://dailytics.com',
  },
  '23866-jimhester': {
    url: 'http://www.jimhester.com',
  },
  '32554-mmacia': {
    url: 'http://codeup.net',
  },
  '26466-jbuedel': {
    url: 'landofjosh.com',
  },
  '24835-henry4k': {
    url: 'henry4k.de',
  },
  '24318-jherdman': {
    url: 'http://jherdman.ca',
  },
  '24713-dsummersl': {
    url: 'viming.blogspot.com',
  },
  '25207-huftis': {
    url: 'http://huftis.org/',
  },
  '32575-palexander': {
    url: 'http://bioportal.bioontology.org',
  },
  '23994-dpc': {
    url: 'http://dpc.pw',
  },
  '31875-zardus': {
    url: 'http://blog.yancomm.net',
  },
  '21537-padde': {
    url: 'http://patrickoscity.de',
  },
  '32594-jaredmcateer': {
    url: 'jaredmcateer.com',
  },
  '26030-lovek323': {
    url: 'http://oconal.id.au/',
  },
  '32597-bugeats': {
    url: 'http://discoautomatic.com/',
  },
  '24780-lightningdb': {
    url: 'http://davidbolton.net',
  },
  '32622-dev0x': {
    url: 'http://dev0x.com',
  },
  '29935-benjohnson': {
    url: 'http://benjohnson.ca',
  },
  '32668-greyblake': {
    url: 'http://greyblake.com',
  },
  '31218-mstyles': {
    url: 'http://mstyles.github.io',
  },
  '32678-krampstudio': {
    url: 'http://krampstudio.com',
  },
  '32749-whabash090': {
    url: 'blog.whabash.com',
  },
  '32764-lexun': {
    url: 'https://plus.google.com/+LukeBarbuto/posts',
  },
  '32776-jcamp748': {
    url: 'http://www.jordancamp.net',
  },
  '32818-jordwest': {
    url: 'http://west.io/',
  },
  '18647-s0undt3ch': {
    url: 'https://github.com/s0undt3ch'
  },
  '25127-peter-edge': {
    url: 'https://github.com/peter-edge'
  },
  '20486-beau': {
    url: 'https://beaugunderson.com/'
  },
  '25255-mmikowski': {
    url: 'http://michaelmikowski.com'
  },
  '47915-wojtek-kruszewski': {
    url: 'http://www.kruszewski.com'
  },
  '49943-sleekwristbands-com': {
    url: 'https://www.sleekwristbands.com'
  },
  '66308-danmikita': {
    url: 'https://github.com/danmikita'
  },
  '65509-lukas-waymann-meribold': {
    url: 'https://meribold.xyz'
  }
};
<commit_msg>Added sponsor agence-web-maroc #168<commit_after>---
---
var sponsorOverride = {
  '62463-balzss': {
    url: 'https://balzss.github.io/',
  },
  '41853-ergodox-ez': {
    url: 'http://www.ergodox-ez.com',
    frontImageUrl: '/images/sponsors/ergodox-ez-logo.png'
  },
  '37206-ganwell': {
    url: 'http://ganwell.github.io/neovim.html',
    frontImageUrl: '/images/sponsors/ganwell.png',
  },
  '32537-hautelook': {
    url: 'http://hautelook.github.io/',
    frontImageUrl: '/images/sponsors/hautelook-logo.png',
  },
  '32681-namely-labs-namelyhr-namely-com': {
    url: 'http://www.namely.com/',
    frontImageUrl: '/images/sponsors/Namely_logo.jpg',
  },
  '39969-blumenversand': {
    url: 'https://blumenversender.com',
  },
  '34279-pygeek': {
    url: 'http://pygeek.com',
  },
  '34942-madis-nomme': {
    url: 'https://mad.is',
    name: 'Madis Nõmme'
  },
  '347-stefanpenner': {
    url: 'http://iamstef.net/',
  },
  '32451-twokul': {
    url: 'http://twokul.io',
  },
  '26545-kvannotten': {
    url: 'https://kristof.io',
  },
  '32345-jtinsky': {
    url: 'http://rutherstone.net/wp/',
  },
  '32362-vagmi': {
    url: 'http://coderwall.com/vagmi',
  },
  '23966-wbinnssmith': {
    url: 'http://wbinnssmith.com',
  },
  '30557-nemith': {
    url: 'http://inetpro.org',
  },
  '32395-apskim': {
    url: 'http://alexpolozov.com',
  },
  '24658-ndj': {
    url: 'dejonghenico.be',
  },
  '24164-mikl': {
    url: 'http://mikkel.hoegh.org/',
  },
  '32439-lsocrate': {
    url: 'http://www.socrate.com.br/',
  },
  '23889-dphase': {
    url: 'http://dphase.net',
  },
  '20492-victorbjelkholm': {
    url: 'http://twitter.com/VictorBjelkholm',
  },
  '24103-demizer': {
    url: 'www.demizerone.com',
  },
  '30137-ianks': {
    url: 'http://ianks.com',
  },
  '32359-jwhear': {
    url: 'www.economicmodeling.com',
  },
  '32367-dhruvasagar': {
    url: 'http://dhruvasagar.com/',
  },
  '24566-bruno': {
    url: 'http://greenbackyard.net',
  },
  '24014-tarrant': {
    url: 'http://daemonomicon.com',
  },
  '32394-tim': {
    url: 'http://tfletcher.com/',
  },
  '24354-wezm': {
    url: 'http://www.wezm.net/',
  },
  '32398-dshills': {
    url: 'http://dsgeek.blogspot.com/',
  },
  '32399-bwells': {
    url: 'www.altalang.com',
  },
  '32427-okaythree': {
    url: 'http://okaythree.com',
  },
  '26081-eglimi': {
    url: 'http://wisol.ch',
  },
  '32480-igort': {
    url: 'http://terzicigor.com/',
  },
  '24120-xvilka': {
    url: 'http://www.xvilka.me/',
  },
  '24042-macat': {
    url: 'https://twitter.com/macat',
  },
  '24386-drodger': {
    url: 'devslant.com',
  },
  '32584-zefei': {
    url: 'http://zef.io/',
  },
  '26581-gotgenes': {
    url: 'http://www.gotgenes.com/',
  },
  '25130-jwoudenberg': {
    url: 'http://jasperwoudenberg.com',
  },
  '32617-musically-ut': {
    url: 'http://musicallyut.in',
  },
  '32629-jhchabran': {
    url: 'http://jhchabran.com',
  },
  '32644-tchak': {
    url: 'http://capitainetrain.com',
  },
  '23874-leon-barrett': {
    url: 'http://leon.barrettnexus.com/',
  },
  '24543-jamesaoverton': {
    url: 'http://james.overton.ca',
  },
  '24499-jochen': {
    url: 'http://www.zerties.org',
  },
  '24721-tmandry': {
    url: 'https://www.linkedin.com/profile/view?id=79377885',
  },
  '25052-jwhitley': {
    url: 'http://bangpath.org/',
  },
  '33151-m42e': {
    url: 'https://bilger.info',
  },
  '32833-velrok': {
    url: 'velrok.github.io',
  },
  '32311-rach': {
    url: 'http://lostpropertyhq.com',
  },
  '20347-derickbailey': {
    url: 'http://derickbailey.com',
  },
  '17979-thejspr': {
    url: 'https://thejspr.com',
  },
  '32315-jthomas': {
    url: 'http://jamesthom.as',
  },
  '32317-mikker': {
    url: 'http://mikker.github.io',
  },
  '27722-dictvm': {
    url: 'https://blog.dictvm.org',
  },
  '22105-brunohenrique': {
    url: 'http://garulab.com/',
  },
  '24693-xsb': {
    url: 'http://xavisb.com',
  },
  '24401-dirkr': {
    url: 'http://niebegeg.net',
  },
  '32328-skattyadz': {
    url: 'imakesh.it',
  },
  '29586-davidosomething': {
    url: 'http://davidosomething.com/',
  },
  '32332-kennykaye': {
    url: 'http://kaye.us',
  },
  '32334-lerrua': {
    url: 'http://www.lerrua.com',
  },
  '24125-beloglazov': {
    url: 'http://beloglazov.info',
  },
  '32340-rillian': {
    url: 'http://advogato.org/person/rillian',
  },
  '28042-justinnhli': {
    url: 'http://justinnhli.com/',
  },
  '23870-fortes': {
    url: 'http://www.fortes.com/',
  },
  '32342-badeip': {
    url: 'https://www.twitter.com/badeip',
  },
  '32348-udp': {
    url: 'fieryclock.com',
  },
  '32352-adambiggs': {
    url: 'lightmaker.com',
  },
  '24970-hallettj': {
    url: 'http://sitr.us/',
  },
  '32363-apenney': {
    url: 'http://www.ntoggle.com',
  },
  '24148-alxndr': {
    url: 'http://eleven-twelve.net',
  },
  '24338-adri': {
    url: 'http://adrian-philipp.com',
  },
  '27129-pipeep': {
    url: 'http://benjam.info/',
  },
  '24937-bilalq': {
    url: 'http://bilalquadri.com',
  },
  '32381-kkuchta': {
    url: 'http://www.kevinkuchta.com',
  },
  '23998-rolisz': {
    url: 'https://rolisz.ro',
  },
  '32383-objectivetruth': {
    url: 'http://www.objectivetruth.ca',
  },
  '32388-norcalli': {
    url: 'norcalli.com',
  },
  '23915-joebadmo': {
    url: 'https://joe.xoxomoon.com',
  },
  '32389-faun': {
    url: 'http://www.faun.me',
  },
  '32403-stanimir-mladenov': {
    url: 'www.zoneprojects.com',
  },
  '32404-phlip9': {
    url: 'phlip9.com',
  },
  '24003-kopischke': {
    url: 'http://martin.kopischke.net',
  },
  '32417-azp': {
    url: 'http://volatileint.blogspot.com',
  },
  '32385-actionshrimp': {
    url: 'www.actionshrimp.com',
  },
  '18449-brainopia': {
    url: 'http://twitter.com/brainopia',
  },
  '32432-davidlowryduda': {
    url: 'http://davidlowryduda.com',
  },
  '24062-grahams': {
    url: 'http://sean-graham.com/',
  },
  '31425-bertocq': {
    url: 'http://www.bertocq.es',
  },
  '24163-linduxed': {
    url: 'http://www.linduxed.se',
  },
  '20659-jakesjews': {
    url: 'http://www.immersiveapplications.com',
  },
  '32445-joesfer': {
    url: 'http://www.joesfer.com',
  },
  '32415-p8952': {
    url: 'https://p8952.info',
  },
  '24655-tejo': {
    url: 'http://www.parmi.it',
  },
  '32477-neh': {
    url: 'http://nathanhowell.net',
  },
  '32479-topaxi': {
    url: 'http://topaxi.ch/',
  },
  '30935-danthecoloradan': {
    url: 'http://www.blazingaddles.com',
  },
  '32521-gypsydave5': {
    url: 'http://gypsydave5.com',
  },
  '25643-seebi': {
    url: 'http://sebastian.tramp.name',
  },
  '22048-ugtastic': {
    url: 'http://www.ugtastic.com',
  },
  '32550-luctus': {
    url: 'http://dailytics.com',
  },
  '23866-jimhester': {
    url: 'http://www.jimhester.com',
  },
  '32554-mmacia': {
    url: 'http://codeup.net',
  },
  '26466-jbuedel': {
    url: 'landofjosh.com',
  },
  '24835-henry4k': {
    url: 'henry4k.de',
  },
  '24318-jherdman': {
    url: 'http://jherdman.ca',
  },
  '24713-dsummersl': {
    url: 'viming.blogspot.com',
  },
  '25207-huftis': {
    url: 'http://huftis.org/',
  },
  '32575-palexander': {
    url: 'http://bioportal.bioontology.org',
  },
  '23994-dpc': {
    url: 'http://dpc.pw',
  },
  '31875-zardus': {
    url: 'http://blog.yancomm.net',
  },
  '21537-padde': {
    url: 'http://patrickoscity.de',
  },
  '32594-jaredmcateer': {
    url: 'jaredmcateer.com',
  },
  '26030-lovek323': {
    url: 'http://oconal.id.au/',
  },
  '32597-bugeats': {
    url: 'http://discoautomatic.com/',
  },
  '24780-lightningdb': {
    url: 'http://davidbolton.net',
  },
  '32622-dev0x': {
    url: 'http://dev0x.com',
  },
  '29935-benjohnson': {
    url: 'http://benjohnson.ca',
  },
  '32668-greyblake': {
    url: 'http://greyblake.com',
  },
  '31218-mstyles': {
    url: 'http://mstyles.github.io',
  },
  '32678-krampstudio': {
    url: 'http://krampstudio.com',
  },
  '32749-whabash090': {
    url: 'blog.whabash.com',
  },
  '32764-lexun': {
    url: 'https://plus.google.com/+LukeBarbuto/posts',
  },
  '32776-jcamp748': {
    url: 'http://www.jordancamp.net',
  },
  '32818-jordwest': {
    url: 'http://west.io/',
  },
  '18647-s0undt3ch': {
    url: 'https://github.com/s0undt3ch'
  },
  '25127-peter-edge': {
    url: 'https://github.com/peter-edge'
  },
  '20486-beau': {
    url: 'https://beaugunderson.com/'
  },
  '25255-mmikowski': {
    url: 'http://michaelmikowski.com'
  },
  '47915-wojtek-kruszewski': {
    url: 'http://www.kruszewski.com'
  },
  '49943-sleekwristbands-com': {
    url: 'https://www.sleekwristbands.com'
  },
  '66308-danmikita': {
    url: 'https://github.com/danmikita'
  },
  '65509-lukas-waymann-meribold': {
    url: 'https://meribold.xyz'
  },
  '68000-agence-web-maroc': {
    url: 'https://marozed.ma'
  }
};
<|endoftext|>


<commit_before><commit_msg>Formatted main.js so that properties and entries in objects and arrays are written on separate lines.<commit_after><|endoftext|>


<commit_before>
//define the key ordering for level-sublevelq

var join = '\x01', separate = '\x00'
var join = '#', separate = '!'

exports.encode = function (e) {
  return separate + e[0].join(join) + separate + e[1]
}

exports.decode = function (s) {
  var i = s.indexOf(separate, 1)
  return [s.substring(1, i).split(join).filter(Boolean), s.substring(++i)]
}

exports.buffer = false

exports.lowerBound = '\x00'
exports.upperBound = '\xff'

<commit_msg>don't declare it twice<commit_after>
//define the key ordering for level-sublevelq

//var join = '\x01', separate = '\x00'
var join = '#', separate = '!'

exports.encode = function (e) {
  return separate + e[0].join(join) + separate + e[1]
}

exports.decode = function (s) {
  var i = s.indexOf(separate, 1)
  return [s.substring(1, i).split(join).filter(Boolean), s.substring(++i)]
}

exports.buffer = false

exports.lowerBound = '\x00'
exports.upperBound = '\xff'

<|endoftext|>


<commit_before><commit_msg>guard against going beyond the first/last index<commit_after><|endoftext|>