<commit_before>/**
 * secStore.js - Encryption enabled browser storage
 *
 * https://www.github.com/jas-/secStore.js
 *
 * Author: Jason Gerfen <jason.gerfen@gmail.com>
 * License: GPL (see LICENSE)
 */
(function(window, undefined) {

  'use strict';

  /**
   * @function secStore
   * @abstract Namespace for saving/retrieving encrypted HTML5 storage engine
   * data
   */
  var secStore = secStore || function() {

    /**
     * @var {Object} defaults
     * @abstract Default set of options for plug-in
     *
     * @param {Boolean} encrypt Optionally encrypt stored data
     * @param {Object} data Data to be setd (JSON objects)
     * @param {String} passphrase Passphrase to use (optional)
     * @param {String} storage Storage mechanism (local, session or cookies)
     */
    var defaults = {
      encrypt: false,
      data: {},
      key: 'secStore.js',
      passphrase: '',
      storage: 'local'
    };

    /**
     * @method setup
     * @scope private
     * @abstract Initial setup routines
     */
    var setup = setup || {

      /**
       * @function set
       * @scope private
       * @abstract Initialization
       *
       * @param {Object} opts Plug-in option object
       */
      init: function(opts) {
        opts.passphrase = (opts.encrypt && opts.passphrase) ?
          opts.passphrase : (opts.encrypt && !opts.passphrase) ?
          crypto.key(opts) : false;
      }
    };

    /**
     * @method storage
     * @scope private
     * @abstract Interface to handle storage options
     */
    var storage = storage || {

      /**
       * @function quota
       * @scope private
       * @abstract Tests specified storage option for current amount of space available.
       *  - Cookies: 4K
       *  - localStorage: 5MB
       *  - sessionStorage: 5MB
       *  - default: 5MB
       *
       * @param {String} t Type of storage specified
       *
       * @returns {Boolean}
       */
      quota: function(storage) {
        var max = /local|session/.test(storage) ? 1024 * 1025 * 5 :
          1024 * 4,
          cur = libs.total(storage),
          total = max - cur;

        if (total <= 0) {
          return false;
        }

        return true;
      },

      /**
       * @function set
       * @scope private
       * @abstract Interface for saving to available storage mechanisms
       *
       * @param {Object} opts Default options
       * @param {Function} cb Callback function
       *
       * @returns {Boolean}
       */
      set: function(opts, cb) {
        var ret = false;

        if (!storage.quota(opts.storage))
          cb('Browser storage quota has been exceeded.');

        //        var existing = storage.get(opts, cb);

        //        if (libs.size(existing) > 0) {
        //          libs.merge(opts.data, existing);
        //        }

        opts.data = (opts.encrypt) ?
          sjcl.encrypt(opts.passphrase, storage.fromJSON(opts.data)) :
          storage.fromJSON(opts.data);

        switch (opts.storage) {
          case 'cookie':
            ret = this.cookie.set(opts);
            break;
          case 'local':
            ret = this.local.set(opts);
            break;
          case 'session':
            ret = this.session.set(opts);
            break;
          default:
            ret = this.local.set(opts);
            break;
        }
        if (!ret) {
          cb('Error occured saving data');
        } else {
          cb(null, 'Successfully set data');
        }
      },

      /**
       * @function get
       * @scope private
       * @abstract Interface for retrieving from available storage mechanisms
       *
       * @param {Object} opts Default options
       * @param {Function} cb Callback function
       *
       * @returns {Object}
       */
      get: function(opts, cb) {
        var ret = {};

        switch (opts.storage) {
          case 'cookie':
            ret = this.cookie.get(opts);
            break;
          case 'local':
            ret = this.local.get(opts);
            break;
          case 'session':
            ret = this.session.get(opts);
            break;
          default:
            ret = this.local.get(opts);
            break;
        }

        ret = sjcl.decrypt(opts.passphrase, ret);
        ret = storage.toJSON(ret);

        if (/object/.test(ret)) {
          cb(null, ret);
        } else {
          cb('Error occured retrieving storage data');
        }
      },

      /**
       * @function fromJSON
       * @scope private
       * @abstract Convert to JSON object to string
       *
       * @param {Object|Array|String} obj Object, Array or String to convert to JSON object
       *
       * @returns {String}
       */
      fromJSON: function(obj) {
        return (/object/.test(typeof(obj))) ? JSON.stringify(obj) : obj;
      },

      /**
       * @function toJSON
       * @scope private
       * @abstract Creates JSON object from formatted string
       *
       * @param {String} obj Object to convert to JSON object
       *
       * @returns {Object}
       */
      toJSON: function(obj) {
        return (/string/.test(typeof(obj))) ? JSON.parse(obj) : obj;
      },

      /**
       * @method cookie
       * @scope private
       * @abstract Method for handling setting & retrieving of cookie objects
       */
      cookie: {

        /**
         * @function set
         * @scope private
         * @abstract Handle setting of cookie objects
         *
         * @param {String} key Key to use for cookies
         * @param {String|Object} value String or object to place in cookie
         *
         * @returns {Boolean}
         */
        set: function(key, value) {
          var d = new Date();
          d.setTime(d.getTime() + (30 * 24 * 60 * 60 * 1000));
          document.cookie = key + '=' + value + ';expires=' + d.toGMTString() +
            ';path=/;domain=' + this.domain();
          return true;
        },

        /**
         * @function get
         * @scope private
         * @abstract Handle retrieval of cookie objects
         *
         * @param {String} key cookie key
         *
         * @returns {String|False}
         */
        get: function(key) {
          var i, x, y, z = document.cookie.split(";");
          for (i = 0; i < z.length; i++) {
            x = z[i].substr(0, z[i].indexOf('='));
            y = z[i].substr(z[i].indexOf('=') + 1);
            x = x.replace(/^\s+|\s+$/g, '');
            if (x == key) {
              return unescape(y);
            }
          }
          return false;
        },

        /**
         * @function domain
         * @scope private
         * @abstract Provides current domain of client for cookie realm
         *
         * @returns {String}
         */
        domain: function() {
          return location.hostname;
        }
      },

      /**
       * @method local
       * @scope private
       * @abstract Method for handling setting & retrieving of localStorage objects
       */
      local: {

        /**
         * @function set
         * @scope private
         * @abstract Handle setting & retrieving of localStorage objects
         *
         * @param {Object} opts Application defaults
         *
         * @returns {Boolean}
         */
        set: function(opts) {
          try {
            window.localStorage.setItem(opts.key, opts.data);
            return true;
          } catch (e) {
            return false;
          }
        },

        /**
         * @function get
         * @scope private
         * @abstract Handle retrieval of localStorage objects
         *
         * @param {Object} o Application defaults
         *
         * @returns {Object|String|Boolean}
         */
        get: function(opts) {
          return window.localStorage.getItem(opts.key);
        }
      },

      /**
       * @method session
       * @scope private
       * @abstract Method for handling setting & retrieving of sessionStorage objects
       */
      session: {

        /**
         * @function set
         * @scope private
         * @abstract Set session storage objects
         *
         * @param {Object} o Application defaults
         *
         * @returns {Boolean}
         */
        set: function(opts) {
          try {
            window.sessionStorage.setItem(opts.key, opts.data);
            return true;
          } catch (e) {
            return false;
          }
        },

        /**
         * @function get
         * @scope private
         * @abstract Retrieves sessionStorage objects
         *
         * @param {Object} opts Application defaults
         *
         * @returns {Object|String|Boolean}
         */
        get: function(opts) {
          return window.sessionStorage.getItem(opts.key);
        }
      }
    };

    /**
     * @method crypto
     * @scope private
     * @abstract Interface to handle encryption option
     */
    var crypto = crypto || {

      /**
       * @function key
       * @scope private
       * @abstract Prepares key for encryption/decryption routines
       *
       * @returns {String}
       */
      key: function() {
        var pass = crypto.uid(),
          salt = crypto.salt(pass);

        return sjcl.codec.hex.fromBits(sjcl.misc.pbkdf2(pass, salt,
          10000, 256));
      },

      /**
       * @function uid
       * @scope private
       * @abstract Generates a machine identifier
       *
       * @returns {String}
       */
      uid: function() {
        var ret = window.navigator.appName +
          window.navigator.appCodeName +
          window.navigator.product +
          window.navigator.productSub +
          window.navigator.appVersion +
          window.navigator.buildID +
          window.navigator.userAgent +
          window.navigator.language +
          window.navigator.platform +
          window.navigator.oscpu;
        return ret.replace(/\s/, '');
      },

      /**
       * @function salt
       * @scope private
       * @abstract Creates salt from string & iv
       *
       * @param {String} str Machine identification used as salt
       *
       * @returns {String}
       */
      salt: function(str) {
        var rec, ret, hash = [],
          slt = crypto.iv(str);

        hash[0] = sjcl.hash.sha256.hash(str), rec = [], rec = hash[0],
          ret;

        for (var i = 1; i < 3; i++) {
          hash[i] = sjcl.hash.sha256.hash(hash[i - 1].concat(slt));
          ret = rec.concat(hash[i]);
        }
        return JSON.stringify(sjcl.codec.hex.fromBits(ret));
      },

      /**
       * @function iv
       * @scope private
       * @abstract Creates IV based on UID
       *
       * @param {String} str Supplied string
       *
       * @returns {String}
       */
      iv: function(str) {
        return encodeURI(str.replace(/-/gi, '').substring(16, Math.ceil(
          16 * str.length) % str.length));
      }
    };

    /**
     * @method libs
     * @scope private
     * @abstract Miscellaneous helper libraries
     */
    var libs = libs || {

      /**
       * @function total
       * @scope private
       * @abstract Returns size of specified storage
       *
       * @param {String} engine Storage mechanism
       *
       * @returns {Insteger}
       */
      total: function(storage) {
        var current = '',
          engine = window.storage + 'Storage';

        for (var key in engine) {
          if (engine.hasOwnProperty(key)) {
            current += engine[key];
          }
        }

        return current ? 3 + ((current.length * 16) / (8 * 1024)) : 0;
      },

      /**
       * @function size
       * @scope private
       * @abstract Perform calculation on objects
       *
       * @param {Object|Array} obj The object/array to calculate
       *
       * @returns {Integer}
       */
      size: function(obj) {
        var n = 0;

        if (/object/.test(typeof(obj))) {
          for (var i in obj) {
            if (obj.hasOwnProperty(obj[i])) n++;
          }
        } else if (/array/.test(typeof(obj))) {
          n = obj.length;
        }
        return n;
      },

      /**
       * @function merge
       * @scope private
       * @abstract Perform preliminary option/default object merge
       *
       * @param {Object} defaults Application defaults
       * @param {Object} obj User supplied object
       *
       * @returns {Object}
       */
      merge: function(defaults, obj) {
        defaults = defaults || {};

        for (var item in defaults) {
          if (defaults.hasOwnProperty(item)) {
            obj[item] = (/object/.test(typeof(defaults[item]))) ?
              this.merge(obj[item], defaults[item]) : defaults[item];
          }
          obj[item] = defaults[item];
        }

        return obj;
      }
    };

    /**
     * @function get
     * @scope public
     * @abstract Retrieves storage engine data
     *
     * @param {Object} obj User supplied options
     * @param {Function} cb User supplied callback function
     */
    secStore.prototype.get = function(obj, cb) {
      cb = cb || obj;

      var opts = libs.merge(obj, defaults);

      setup.init(opts);

      storage.get(opts, cb);
    };

    /**
     * @function set
     * @scope public
     * @abstract Saves data to specified storage engine
     *
     * @param {Object} obj User supplied options
     * @param {Function} cb User supplied callback function
     */
    secStore.prototype.set = function(obj, cb) {
      cb = cb || obj;

      var opts = libs.merge(obj, defaults);

      setup.init(opts);

      storage.set(opts, cb);
    };

  };

  /* secStore.js, do work */
  window.secStore = secStore;

})(window);
<commit_msg>Catch all?<commit_after>/**
 * secStore.js - Encryption enabled browser storage
 *
 * https://www.github.com/jas-/secStore.js
 *
 * Author: Jason Gerfen <jason.gerfen@gmail.com>
 * License: GPL (see LICENSE)
 */
(function(window, undefined) {

  'use strict';

  /**
   * @function secStore
   * @abstract Namespace for saving/retrieving encrypted HTML5 storage engine
   * data
   */
  var secStore = secStore || function() {

    /**
     * @var {Object} defaults
     * @abstract Default set of options for plug-in
     *
     * @param {Boolean} encrypt Optionally encrypt stored data
     * @param {Object} data Data to be setd (JSON objects)
     * @param {String} passphrase Passphrase to use (optional)
     * @param {String} storage Storage mechanism (local, session or cookies)
     */
    var defaults = {
      encrypt: false,
      data: {},
      key: 'secStore.js',
      passphrase: '',
      storage: 'local'
    };

    /**
     * @method setup
     * @scope private
     * @abstract Initial setup routines
     */
    var setup = setup || {

      /**
       * @function set
       * @scope private
       * @abstract Initialization
       *
       * @param {Object} opts Plug-in option object
       */
      init: function(opts) {
        opts.passphrase = (opts.encrypt && opts.passphrase) ?
          opts.passphrase : (opts.encrypt && !opts.passphrase) ?
          crypto.key(opts) : false;
      }
    };

    /**
     * @method storage
     * @scope private
     * @abstract Interface to handle storage options
     */
    var storage = storage || {

      /**
       * @function quota
       * @scope private
       * @abstract Tests specified storage option for current amount of space available.
       *  - Cookies: 4K
       *  - localStorage: 5MB
       *  - sessionStorage: 5MB
       *  - default: 5MB
       *
       * @param {String} t Type of storage specified
       *
       * @returns {Boolean}
       */
      quota: function(storage) {
        var max = /local|session/.test(storage) ? 1024 * 1025 * 5 :
          1024 * 4,
          cur = libs.total(storage),
          total = max - cur;

        if (total <= 0) {
          return false;
        }

        return true;
      },

      /**
       * @function set
       * @scope private
       * @abstract Interface for saving to available storage mechanisms
       *
       * @param {Object} opts Default options
       * @param {Function} cb Callback function
       *
       * @returns {Boolean}
       */
      set: function(opts, cb) {
        var ret = false;

        if (!storage.quota(opts.storage))
          cb('Browser storage quota has been exceeded.');

        opts.data = (opts.encrypt) ?
          sjcl.encrypt(opts.passphrase, storage.fromJSON(opts.data)) :
          storage.fromJSON(opts.data);

        switch (opts.storage) {
          case 'cookie':
            ret = this.cookie.set(opts);
            break;
          case 'local':
            ret = this.local.set(opts);
            break;
          case 'session':
            ret = this.session.set(opts);
            break;
          default:
            ret = this.local.set(opts);
            break;
        }
        if (!ret) {
          cb('Error occured saving data');
        } else {
          cb(null, 'Successfully set data');
        }
      },

      /**
       * @function get
       * @scope private
       * @abstract Interface for retrieving from available storage mechanisms
       *
       * @param {Object} opts Default options
       * @param {Function} cb Callback function
       *
       * @returns {Object}
       */
      get: function(opts, cb) {
        var ret = {};

        switch (opts.storage) {
          case 'cookie':
            ret = this.cookie.get(opts);
            break;
          case 'local':
            ret = this.local.get(opts);
            break;
          case 'session':
            ret = this.session.get(opts);
            break;
          default:
            ret = this.local.get(opts);
            break;
        }

        ret = sjcl.decrypt(opts.passphrase, ret);
        ret = storage.toJSON(ret);

        if (/object/.test(ret)) {
          cb(null, ret);
        } else {
          cb('Error occured retrieving storage data');
        }
      },

      /**
       * @function fromJSON
       * @scope private
       * @abstract Convert to JSON object to string
       *
       * @param {Object|Array|String} obj Object, Array or String to convert to JSON object
       *
       * @returns {String}
       */
      fromJSON: function(obj) {
        return (/object/.test(typeof(obj))) ? JSON.stringify(obj) : obj;
      },

      /**
       * @function toJSON
       * @scope private
       * @abstract Creates JSON object from formatted string
       *
       * @param {String} obj Object to convert to JSON object
       *
       * @returns {Object}
       */
      toJSON: function(obj) {
        return (/string/.test(typeof(obj))) ? JSON.parse(obj) : obj;
      },

      /**
       * @method cookie
       * @scope private
       * @abstract Method for handling setting & retrieving of cookie objects
       */
      cookie: {

        /**
         * @function set
         * @scope private
         * @abstract Handle setting of cookie objects
         *
         * @param {String} key Key to use for cookies
         * @param {String|Object} value String or object to place in cookie
         *
         * @returns {Boolean}
         */
        set: function(key, value) {
          var d = new Date();
          d.setTime(d.getTime() + (30 * 24 * 60 * 60 * 1000));
          document.cookie = key + '=' + value + ';expires=' + d.toGMTString() +
            ';path=/;domain=' + this.domain();
          return true;
        },

        /**
         * @function get
         * @scope private
         * @abstract Handle retrieval of cookie objects
         *
         * @param {String} key cookie key
         *
         * @returns {String|False}
         */
        get: function(key) {
          var i, x, y, z = document.cookie.split(";");
          for (i = 0; i < z.length; i++) {
            x = z[i].substr(0, z[i].indexOf('='));
            y = z[i].substr(z[i].indexOf('=') + 1);
            x = x.replace(/^\s+|\s+$/g, '');
            if (x == key) {
              return unescape(y);
            }
          }
          return false;
        },

        /**
         * @function domain
         * @scope private
         * @abstract Provides current domain of client for cookie realm
         *
         * @returns {String}
         */
        domain: function() {
          return location.hostname;
        }
      },

      /**
       * @method local
       * @scope private
       * @abstract Method for handling setting & retrieving of localStorage objects
       */
      local: {

        /**
         * @function set
         * @scope private
         * @abstract Handle setting & retrieving of localStorage objects
         *
         * @param {Object} opts Application defaults
         *
         * @returns {Boolean}
         */
        set: function(opts) {
          try {
            window.localStorage.setItem(opts.key, opts.data);
            return true;
          } catch (e) {
            return false;
          }
        },

        /**
         * @function get
         * @scope private
         * @abstract Handle retrieval of localStorage objects
         *
         * @param {Object} o Application defaults
         *
         * @returns {Object|String|Boolean}
         */
        get: function(opts) {
          return window.localStorage.getItem(opts.key);
        }
      },

      /**
       * @method session
       * @scope private
       * @abstract Method for handling setting & retrieving of sessionStorage objects
       */
      session: {

        /**
         * @function set
         * @scope private
         * @abstract Set session storage objects
         *
         * @param {Object} o Application defaults
         *
         * @returns {Boolean}
         */
        set: function(opts) {
          try {
            window.sessionStorage.setItem(opts.key, opts.data);
            return true;
          } catch (e) {
            return false;
          }
        },

        /**
         * @function get
         * @scope private
         * @abstract Retrieves sessionStorage objects
         *
         * @param {Object} opts Application defaults
         *
         * @returns {Object|String|Boolean}
         */
        get: function(opts) {
          return window.sessionStorage.getItem(opts.key);
        }
      }
    };

    /**
     * @method crypto
     * @scope private
     * @abstract Interface to handle encryption option
     */
    var crypto = crypto || {

      /**
       * @function key
       * @scope private
       * @abstract Prepares key for encryption/decryption routines
       *
       * @returns {String}
       */
      key: function() {
        var pass = crypto.uid(),
          salt = crypto.salt(pass);

        return sjcl.codec.hex.fromBits(sjcl.misc.pbkdf2(pass, salt,
          10000, 256));
      },

      /**
       * @function uid
       * @scope private
       * @abstract Generates a machine identifier
       *
       * @returns {String}
       */
      uid: function() {
        var ret = window.navigator.appName +
          window.navigator.appCodeName +
          window.navigator.product +
          window.navigator.productSub +
          window.navigator.appVersion +
          window.navigator.buildID +
          window.navigator.userAgent +
          window.navigator.language +
          window.navigator.platform +
          window.navigator.oscpu;
        return ret.replace(/\s/, '');
      },

      /**
       * @function salt
       * @scope private
       * @abstract Creates salt from string & iv
       *
       * @param {String} str Machine identification used as salt
       *
       * @returns {String}
       */
      salt: function(str) {
        var rec, ret, hash = [],
          slt = crypto.iv(str);

        hash[0] = sjcl.hash.sha256.hash(str), rec = [], rec = hash[0],
          ret;

        for (var i = 1; i < 3; i++) {
          hash[i] = sjcl.hash.sha256.hash(hash[i - 1].concat(slt));
          ret = rec.concat(hash[i]);
        }
        return JSON.stringify(sjcl.codec.hex.fromBits(ret));
      },

      /**
       * @function iv
       * @scope private
       * @abstract Creates IV based on UID
       *
       * @param {String} str Supplied string
       *
       * @returns {String}
       */
      iv: function(str) {
        return encodeURI(str.replace(/-/gi, '').substring(16, Math.ceil(
          16 * str.length) % str.length));
      }
    };

    /**
     * @method libs
     * @scope private
     * @abstract Miscellaneous helper libraries
     */
    var libs = libs || {

      /**
       * @function total
       * @scope private
       * @abstract Returns size of specified storage
       *
       * @param {String} engine Storage mechanism
       *
       * @returns {Insteger}
       */
      total: function(storage) {
        var current = '',
          engine = window.storage + 'Storage';

        for (var key in engine) {
          if (engine.hasOwnProperty(key)) {
            current += engine[key];
          }
        }

        return current ? 3 + ((current.length * 16) / (8 * 1024)) : 0;
      },

      /**
       * @function size
       * @scope private
       * @abstract Perform calculation on objects
       *
       * @param {Object|Array} obj The object/array to calculate
       *
       * @returns {Integer}
       */
      size: function(obj) {
        var n = 0;

        if (/object/.test(typeof(obj))) {
          for (var i in obj) {
            if (obj.hasOwnProperty(obj[i])) n++;
          }
        } else if (/array/.test(typeof(obj))) {
          n = obj.length;
        }
        return n;
      },

      /**
       * @function merge
       * @scope private
       * @abstract Perform preliminary option/default object merge
       *
       * @param {Object} defaults Application defaults
       * @param {Object} obj User supplied object
       *
       * @returns {Object}
       */
      merge: function(defaults, obj) {
        defaults = defaults || {};

        for (var item in defaults) {
          if (defaults.hasOwnProperty(item)) {
            obj[item] = (/object/.test(typeof(defaults[item]))) ?
              this.merge(obj[item], defaults[item]) : defaults[item];
          }
          obj[item] = defaults[item];
        }

        return obj;
      }
    };

    /**
     * @function get
     * @scope public
     * @abstract Retrieves storage engine data
     *
     * @param {Object} obj User supplied options
     * @param {Function} cb User supplied callback function
     */
    secStore.prototype.get = function(obj, cb) {
      cb = cb || obj;

      var opts = libs.merge(obj, defaults);

      setup.init(opts);

      storage.get(opts, cb);
    };

    /**
     * @function set
     * @scope public
     * @abstract Saves data to specified storage engine
     *
     * @param {Object} obj User supplied options
     * @param {Function} cb User supplied callback function
     */
    secStore.prototype.set = function(obj, cb) {
      cb = cb || obj;

      var opts = libs.merge(obj, defaults);

      setup.init(opts);

      storage.set(opts, cb);
    };

  };

  /* secStore.js, do work */
  window.secStore = secStore;

})(window);
<|endoftext|>


<commit_before>/**!
 * RedRaphael Triangle shape definition
 */
/* global window */
window.Raphael && (window.Raphael.define && function (R) {
    var win = R._g.win,

        M = 'M',
        L = 'L',
        Z = 'Z',
        Q = 'Q',
        isNaN = win.isNaN,

        sqrt = win.Math.sqrt,
        pow = win.Math.pow,
        acos = win.Math.acos,
        tan = win.Math.tan,

        p2pdistance = R._cacher(function (x1, y1, x2, y2) {
            // Returns distance between two points
            return sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2));
        }),

        pointAtLength = R._cacher(function (x1, y1, x2, y2, d) {
            /* Returns the coordinates of the point at distance 'd' from point (x1, y1)
             * on the line between point (x1, y1) and point (x2, y2).
             */

            // Calculate vectors along path
            var vx = x2 - x1,
                vy = y2 - y1;

            // Calculate total length of the path
            var l = p2pdistance(x1, y1, x2, y2);

            // Normalize the vectors
            vx /= l;
            vy /= l;

            // Calculate required point coordinates
            var px = x1 + vx * d,
                py = y1 + vy * d;

            return {
                x: px,
                y: py
            }
        });

    R.define({
        // Name of the component goes here.
        name: 'trianglepath',

        // Constructor of the component goes here. Must be same name as the name of the component.
        trianglepath: function () { // args: [x1, y1, x2, y2, x3, y3, r]
            var paper = this,
                args = arguments,
                group = R._lastArgIfGroup(args),
                face = paper.path(group);

            return face.attr("trianglepath", [
                args[0], args[1],
                args[2], args[3],
                args[4], args[5], args[6]
            ]);
        },

        fn: {
            sides: function (points) {
                // Use p2pdistance library function to compute sides. Return from cache when available
                return [
                    p2pdistance(points[0], points[1], points[2], points[3]), // p1, p2
                    p2pdistance(points[2], points[3], points[4], points[5]), // p2, p3
                    p2pdistance(points[4], points[5], points[0], points[1])  // p3, p1
                ];
            },

            enclosedAngles: function () {
                // Returns the three angles of a triangle formed by the given sides
                var edges = this._sides;
                return [
                    acos((pow(edges[0], 2) + pow(edges[2], 2) - pow(edges[1], 2)) / (2 * edges[0] * edges[2])),
                    acos((pow(edges[0], 2) + pow(edges[1], 2) - pow(edges[2], 2)) / (2 * edges[0] * edges[1])),
                    acos((pow(edges[2], 2) + pow(edges[1], 2) - pow(edges[0], 2)) / (2 * edges[2] * edges[1]))
                ];
            }
        },

        ca: {
            trianglepath: function (x1, y1, x2, y2, x3, y3, r) {
                /* Create the triangle path with the provided vertices.
                 * Make rounded triangle corners if radius is provided. */
                if (r) {
                    // Calculate length of all sides of the triangle
                    this._sides = this.sides(arguments);

                    // Get all the angles of the triangle
                    var angles = this.enclosedAngles();

                    // Get distance of points of curves from corresponding vertices
                    var curveDistance = [
                        r / tan(angles[0]/2),
                        r / tan(angles[1]/2),
                        r / tan(angles[2]/2)
                    ];

                    // Get coordinates of the points of curve on the triangle
                    var curvePoints = [
                        pointAtLength(x1, y1, x3, y3, curveDistance[0]),
                        pointAtLength(x1, y1, x2, y2, curveDistance[0]),

                        pointAtLength(x2, y2, x1, y1, curveDistance[1]),
                        pointAtLength(x2, y2, x3, y3, curveDistance[1]),

                        pointAtLength(x3, y3, x2, y2, curveDistance[2]),
                        pointAtLength(x3, y3, x1, y1, curveDistance[2])
                    ];

                    // Draw the triangle path with rounded corners
                    this.attr({
                        path: [
                            M, curvePoints[0].x, curvePoints[0].y, Q, x1, y1, curvePoints[1].x, curvePoints[1].y,
                            L, curvePoints[2].x, curvePoints[2].y, Q, x2, y2, curvePoints[3].x, curvePoints[3].y,
                            L, curvePoints[4].x, curvePoints[4].y, Q, x3, y3, curvePoints[5].x, curvePoints[5].y,
                            L, curvePoints[0].x, curvePoints[0].y
                        ]
                    });
                } else {
                    this.attr({
                        path: [M, x1, y1, L, x2, y2, x3, y3, Z]
                    });
                }
            },

            "rotate": function (deg, x, y) {
                /* Rotate the trianglepath about a given point. */
            },

            "drop-shadow": function (dx, dy, spread, color) {
                // Show a shadow effect for the trianglepath
            }
        }
    });
}) (window.Raphael);
<commit_msg>Made corrections suggested in pull request review, including fixing jslint errors and removing blank functions<commit_after>/**!
 * RedRaphael Triangle shape definition
 */
/* global window */
window.Raphael && (window.Raphael.define && function (R) {
    var win = R._g.win,

        M = 'M',
        L = 'L',
        Z = 'Z',
        Q = 'Q',

        sqrt = win.Math.sqrt,
        pow = win.Math.pow,
        acos = win.Math.acos,
        tan = win.Math.tan,

        p2pdistance = R._cacher(function (x1, y1, x2, y2) {
            // Returns distance between two points
            return sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2));
        }),

        pointAtLength = R._cacher(function (x1, y1, x2, y2, d) {
            /* Returns the coordinates of the point at distance 'd' from point (x1, y1)
             * on the line between point (x1, y1) and point (x2, y2).
             */

            // Calculate vectors along path
            var vx = x2 - x1,
                vy = y2 - y1,
                l, px, py;

            // Calculate total length of the path
            l = p2pdistance(x1, y1, x2, y2);

            // Normalize the vectors
            vx /= l;
            vy /= l;

            // Calculate required point coordinates
            px = x1 + vx * d;
            py = y1 + vy * d;

            return {
                x: px,
                y: py
            };
        });

    R.define({
        // Name of the component goes here.
        name: 'trianglepath',

        // Constructor of the component goes here. Must be same name as the name of the component.
        trianglepath: function () { // args: [x1, y1, x2, y2, x3, y3, r]
            var paper = this,
                args = arguments,
                group = R._lastArgIfGroup(args),
                face = paper.path(group);

            return face.attr("trianglepath", [
                args[0], args[1],
                args[2], args[3],
                args[4], args[5], args[6]
            ]);
        },

        fn: {
            sides: function () {
                // Use p2pdistance library function to compute sides of a triangle.
                var points = this._args;
                return [
                    p2pdistance(points[0], points[1], points[2], points[3]), // p1, p2
                    p2pdistance(points[2], points[3], points[4], points[5]), // p2, p3
                    p2pdistance(points[4], points[5], points[0], points[1])  // p3, p1
                ];
            },

            enclosedAngles: function () {
                // Returns the three angles of a triangle formed by the given sides
                var edges = this._sides;
                return [
                    acos((pow(edges[0], 2) + pow(edges[2], 2) - pow(edges[1], 2)) / (2 * edges[0] * edges[2])),
                    acos((pow(edges[0], 2) + pow(edges[1], 2) - pow(edges[2], 2)) / (2 * edges[0] * edges[1])),
                    acos((pow(edges[2], 2) + pow(edges[1], 2) - pow(edges[0], 2)) / (2 * edges[2] * edges[1]))
                ];
            }
        },

        ca: {
            trianglepath: function (x1, y1, x2, y2, x3, y3, r) {
                /* Create the triangle path with the provided vertices.
                 * Make rounded triangle corners if radius is provided. */
                if (r) {
                    // Store arguments in trianglepath element
                    this._args = arguments;

                    // Calculate length of all sides of the triangle
                    this._sides = this.sides();

                    // Get all the angles of the triangle
                    var angles = this.enclosedAngles(),
                        curveDistance,
                        curvePoints;

                    // Get distance of points of curves from corresponding vertices
                    curveDistance = [
                        r / tan(angles[0] / 2),
                        r / tan(angles[1] / 2),
                        r / tan(angles[2] / 2)
                    ];

                    // Get coordinates of the points of curve on the triangle
                    curvePoints = [
                        pointAtLength(x1, y1, x3, y3, curveDistance[0]),
                        pointAtLength(x1, y1, x2, y2, curveDistance[0]),

                        pointAtLength(x2, y2, x1, y1, curveDistance[1]),
                        pointAtLength(x2, y2, x3, y3, curveDistance[1]),

                        pointAtLength(x3, y3, x2, y2, curveDistance[2]),
                        pointAtLength(x3, y3, x1, y1, curveDistance[2])
                    ];

                    // Draw the triangle path with rounded corners
                    this.attr({
                        path: [
                            M, curvePoints[0].x, curvePoints[0].y, Q, x1, y1, curvePoints[1].x, curvePoints[1].y,
                            L, curvePoints[2].x, curvePoints[2].y, Q, x2, y2, curvePoints[3].x, curvePoints[3].y,
                            L, curvePoints[4].x, curvePoints[4].y, Q, x3, y3, curvePoints[5].x, curvePoints[5].y,
                            L, curvePoints[0].x, curvePoints[0].y
                        ]
                    });
                } else {
                    this.attr({
                        path: [M, x1, y1, L, x2, y2, x3, y3, Z]
                    });
                }
            }
        }
    });
})(window.Raphael);
<|endoftext|>


<commit_before>module("create");

test("simple class creation", function() {
	var test = Create({
		a : 1,
		b : function() {
			return this.a;
		},
		c : function() {
			return this.b();
		},
		toString : function() {
			return "a";
		},
		valueOf : function() {
			return 2;
		}
	});

	equals(typeof test, "function", "defined class is an object");
	equals(typeof new test(), "object", "instantiated class is an object");
	equals(new test().a, 1, "member variable is as defined");
	equals(new test().b(), 1, "call to member variable within context");
	equals(new test().c(), 1, "call to member function within context");

	// valueOf is always called ahead of toString when it is defined
	equals(new test() + "", "2", "implicit toString() called explicitly");
	equals((new test()).toString(), "a", "explicit toString() called explicitly");
	equals(+new test(), 2, "implicit valueOf() called explicitly");
	equals((new test()).valueOf(), 2, "explicit valueOf() called explicitly");
});

test("invocation and constructors", function() {
	// testing class creation without a constructor
	var test = Create({
		a : 1,
		b : function() {
			return this.a;
		}
	});
	equals(typeof new test(), "object", "instantiated class with no constructor is an object");
	ok(new test() instanceof test, "instantiated class with no constructor is an an proper instance");
	equals(new test().b(), 1, "call to member variable within context with no constructor");

	// testing class creation with a basic constructor
	test = Create({
		a : 1,
		_construct_ : function() {
			this.a = 2;
		},
		b : function() {
			return this.a;
		}
	});
	// testing class creation with a basic constructor
	equals(typeof new test(), "object", "instantiated class with basic constructor is an object");
	ok(new test() instanceof test, "instantiated class with basic constructor is an an proper instance");
	equals(new test().b(), 2, "call to member variable within context with basic constructor");

	// test creating a constructor with parameters
	test = Create({
		a : 1,
		_construct_ : function(a) {
			this.a = a;
		},
		b : function() {
			return this.a;
		}
	});
	// testing class creation with a basic constructor
	equals(typeof new test(3), "object", "instantiated class with simple constructor is an object");
	ok(new test(3) instanceof test, "instantiated class with simple constructor is an an proper instance");
	equals(new test(3).b(), 3, "call to member variable within context with simple constructor");

	// test creating a instances with invocation
	test = Create({
		a : 1,
		_construct_ : function(a) {
			this.a = a;
		},
		b : function() {
			return this.a;
		}
	});
	// testing class creation with a basic constructor
	equals(typeof test(3), "object", "instantiated class invocation is an object");
	ok(test(3) instanceof test, "instantiated class with invocation is an an proper instance");
	equals(test(3).b(), 3, "call to member variable within context with invocation");

	// test overriding invocation function to not generate a class instance
	test = Create({
		a : 1,
		_invoke_ : function() {
			return "x";
		},
		_construct_ : function(a) {
			this.a = a;
		}
	});
	equals(test(), "x", "override invocation functionality to execute functionality");
});

test("known properties", function() {
	// testing class for known properties in every defined class
	var test = Create({});

	equals(test.__isclass_, true, "flag indicating this object was created using the Create method");
	equals((new test()).constructor, test, "assert that we have a internal reference to the constructor via 'constructor'");
	equals((new test())._self_, test, "assert that we have a internal reference to the constructor via '_self_'");
	equals(typeof test.superclass, "function", "assert that there is an internal reference to the parent class");
	equals(test.superclass, base, "assert that the reference to the superclass is the parent");
	equals(typeof test.subclass, "object", "assert that an array is created holding child classes");
	equals(test.subclass.length, 0, "assert that there are no child classes extending this object");
	ok(new test() instanceof test, "assert that a new object of this class is an instance of it's constructor");
	ok(new test() instanceof base, "assert that a new object of this class is an instance of it's parent");
});

test("static properties", function() {
	// testing class creation with static properties
	var test = Create({
		a : 1,
		__static_a : 2,
		b : function() {
			return this.a;
		},
		__static_b : function() {
			// the internal "this" reference should always point to the class definition in a static context
			return this.a;
		},
		c : function() {
			return test.a;
		},
		d : function() {
			return this._self_;
		},
		e : function() {
			return this._self_.a;
		}
	});

	equals(test.a, 2, "Reading static property of an class");
	equals((new test()).a, 1, "Reading non static property of an class");
	equals(test.b(), 2, "Invoking static function of a class");
	equals((new test()).b(), 1, "Invoking dynamic function of a class");
	equals((new test()).c(), 2, "Reading static property by name within a class");
	equals((new test()).d(), test, "Reading static definition within a class");
	equals((new test()).e(), 2, "Reading static property by using _self_ within a class");
});

test("adding new properties", function() {
	// testing class for known properties in every defined class
	var test = Create({});

	// adding properties to the prototype
	test.prototype.b = function() {
		return 1;
	};
	equals((new test()).b(), 1, "invoking a method added using prototype method");
	test.addProperty("c", function() {
		return 1;
	});
	equals((new test()).c(), 1, "invoking a method added using addProperty method");

	// adding properties to the object
	test.b = function() {
		return 1;
	};
	equals(test.b(), 1, "invoking a method added using classical method");
	test.addStaticProperty("c", function() {
		return 1;
	});
	equals(test.c(), 1, "invoking a method added using addStaticProperty method");

	// test that references is proper
	test.addStaticProperty("d", function() {
		equals(this, test, "assuring the 'this' reference of a method added using addStaticProperty method is the constructor");
		return 1;
	});
	test.c();
});

test("extending classes using inheritance", function() {
	// testing class for known properties in every defined class
	var test = Create({
		a : function() {
			return 1;
		},
		b : function() {
			return 2;
		},
		d : function() {
			return 4;
		},
		e : function() {
			return this.constructor;
		}
	});
	var subclass = Create(test, {
		c : function() {
			return 3;
		},
		d : function() {
			return this._parent_();
		},
		f : function() {
			return this.constructor;
		}
	});
	var subclass_a = Create(test, {
		b : function() {
			// invoking the parent version of this function
			return this._parent_() + 4;
		}
	});
	var subsubclass = Create(subclass, {
		c : function() {
			return 4;
		},
		d : function() {
			return this._parent_();
		},
		e : function() {
			return this._parent_();
		}
	});

	// test instance inheritance functionality
	ok((new test()) instanceof test, "assert that instantiated classes are instances of itself");
	ok((new subclass()) instanceof test, "assert that inherited classes are instances of it's parent");
	ok((new subsubclass()) instanceof test, "assert that inherited classes are instances of it's parent (multi level)");
	ok((new subsubclass()) instanceof subclass, "assert that inherited classes are instances of it's parent (single level)");

	// test prototype inheritance functionality
	equals((new subclass()).a(), 1, "inherited function in child class is executed");
	equals((new subclass()).c(), 3, "new function in child class is executed");
	equals((new subsubclass()).c(), 4, "overriden function in child class is executed");

	// test 'this' reference integrity
	equals((new subclass()).e(), subclass, "reference to this within inherited function is to itself");

	// test calling parent functions
	equals((new subclass()).d(), 4, "parent method in overriden method is executed");
	equals((new subclass_a()).b(), 6, "parent method in overriden method is executed with additional logic");
	equals((new subsubclass()).d(), 4, "parent method in overriden method is executed (multi level)");
	equals((new subsubclass()).e(), subsubclass, "parent method's 'this' is still referencing proper object");

	// testing inherited properties
});

// implements
<commit_msg>completed unit test for class extension<commit_after>module("create");

test("simple class creation", function() {
	var test = Create({
		a : 1,
		b : function() {
			return this.a;
		},
		c : function() {
			return this.b();
		},
		toString : function() {
			return "a";
		},
		valueOf : function() {
			return 2;
		}
	});

	equals(typeof test, "function", "defined class is an object");
	equals(typeof new test(), "object", "instantiated class is an object");
	equals(new test().a, 1, "member variable is as defined");
	equals(new test().b(), 1, "call to member variable within context");
	equals(new test().c(), 1, "call to member function within context");

	// valueOf is always called ahead of toString when it is defined
	equals(new test() + "", "2", "implicit toString() called explicitly");
	equals((new test()).toString(), "a", "explicit toString() called explicitly");
	equals(+new test(), 2, "implicit valueOf() called explicitly");
	equals((new test()).valueOf(), 2, "explicit valueOf() called explicitly");
});

test("invocation and constructors", function() {
	// testing class creation without a constructor
	var test = Create({
		a : 1,
		b : function() {
			return this.a;
		}
	});
	equals(typeof new test(), "object", "instantiated class with no constructor is an object");
	ok(new test() instanceof test, "instantiated class with no constructor is an an proper instance");
	equals(new test().b(), 1, "call to member variable within context with no constructor");

	// testing class creation with a basic constructor
	test = Create({
		a : 1,
		_construct_ : function() {
			this.a = 2;
		},
		b : function() {
			return this.a;
		}
	});
	// testing class creation with a basic constructor
	equals(typeof new test(), "object", "instantiated class with basic constructor is an object");
	ok(new test() instanceof test, "instantiated class with basic constructor is an an proper instance");
	equals(new test().b(), 2, "call to member variable within context with basic constructor");

	// test creating a constructor with parameters
	test = Create({
		a : 1,
		_construct_ : function(a) {
			this.a = a;
		},
		b : function() {
			return this.a;
		}
	});
	// testing class creation with a basic constructor
	equals(typeof new test(3), "object", "instantiated class with simple constructor is an object");
	ok(new test(3) instanceof test, "instantiated class with simple constructor is an an proper instance");
	equals(new test(3).b(), 3, "call to member variable within context with simple constructor");

	// test creating a instances with invocation
	test = Create({
		a : 1,
		_construct_ : function(a) {
			this.a = a;
		},
		b : function() {
			return this.a;
		}
	});
	// testing class creation with a basic constructor
	equals(typeof test(3), "object", "instantiated class invocation is an object");
	ok(test(3) instanceof test, "instantiated class with invocation is an an proper instance");
	equals(test(3).b(), 3, "call to member variable within context with invocation");

	// test overriding invocation function to not generate a class instance
	test = Create({
		a : 1,
		_invoke_ : function() {
			return "x";
		},
		_construct_ : function(a) {
			this.a = a;
		}
	});
	equals(test(), "x", "override invocation functionality to execute functionality");
});

test("known properties", function() {
	// testing class for known properties in every defined class
	var test = Create({});

	equals(test.__isclass_, true, "flag indicating this object was created using the Create method");
	equals((new test()).constructor, test, "assert that we have a internal reference to the constructor via 'constructor'");
	equals((new test())._self_, test, "assert that we have a internal reference to the constructor via '_self_'");
	equals(typeof test.superclass, "function", "assert that there is an internal reference to the parent class");
	equals(test.superclass, base, "assert that the reference to the superclass is the parent");
	equals(typeof test.subclass, "object", "assert that an array is created holding child classes");
	equals(test.subclass.length, 0, "assert that there are no child classes extending this object");
	ok(new test() instanceof test, "assert that a new object of this class is an instance of it's constructor");
	ok(new test() instanceof base, "assert that a new object of this class is an instance of it's parent");
});

test("static properties", function() {
	// testing class creation with static properties
	var test = Create({
		a : 1,
		__static_a : 2,
		b : function() {
			return this.a;
		},
		__static_b : function() {
			// the internal "this" reference should always point to the class definition in a static context
			return this.a;
		},
		c : function() {
			return test.a;
		},
		d : function() {
			return this._self_;
		},
		e : function() {
			return this._self_.a;
		}
	});

	equals(test.a, 2, "Reading static property of an class");
	equals((new test()).a, 1, "Reading non static property of an class");
	equals(test.b(), 2, "Invoking static function of a class");
	equals((new test()).b(), 1, "Invoking dynamic function of a class");
	equals((new test()).c(), 2, "Reading static property by name within a class");
	equals((new test()).d(), test, "Reading static definition within a class");
	equals((new test()).e(), 2, "Reading static property by using _self_ within a class");
});

test("adding new properties", function() {
	// testing class for known properties in every defined class
	var test = Create({});

	// adding properties to the prototype
	test.prototype.b = function() {
		return 1;
	};
	equals((new test()).b(), 1, "invoking a method added using prototype method");
	test.addProperty("c", function() {
		return 1;
	});
	equals((new test()).c(), 1, "invoking a method added using addProperty method");

	// adding properties to the object
	test.b = function() {
		return 1;
	};
	equals(test.b(), 1, "invoking a method added using classical method");
	test.addStaticProperty("c", function() {
		return 1;
	});
	equals(test.c(), 1, "invoking a method added using addStaticProperty method");

	// test that references is proper
	test.addStaticProperty("d", function() {
		equals(this, test, "assuring the 'this' reference of a method added using addStaticProperty method is the constructor");
		return 1;
	});
	test.c();
});

test("extending classes using inheritance", function() {
	// testing class for known properties in every defined class
	var test = Create({
		a : function() {
			return 1;
		},
		b : function() {
			return 2;
		},
		d : function() {
			return 4;
		},
		e : function() {
			return this.constructor;
		}
	});
	var subclass = Create(test, {
		c : function() {
			return 3;
		},
		d : function() {
			return this._parent_();
		},
		f : function() {
			return this.constructor;
		}
	});
	var subclass_a = Create(test, {
		b : function() {
			// invoking the parent version of this function
			return this._parent_() + 4;
		}
	});
	var subsubclass = Create(subclass, {
		c : function() {
			return 4;
		},
		d : function() {
			return this._parent_();
		},
		e : function() {
			return this._parent_();
		}
	});

	// test instance inheritance functionality
	ok((new test()) instanceof test, "assert that instantiated classes are instances of itself");
	ok((new subclass()) instanceof test, "assert that inherited classes are instances of it's parent");
	ok((new subsubclass()) instanceof test, "assert that inherited classes are instances of it's parent (multi level)");
	ok((new subsubclass()) instanceof subclass, "assert that inherited classes are instances of it's parent (single level)");

	// test prototype inheritance functionality
	equals((new subclass()).a(), 1, "inherited function in child class is executed");
	equals((new subclass()).c(), 3, "new function in child class is executed");
	equals((new subsubclass()).c(), 4, "overriden function in child class is executed");

	// test 'this' reference integrity
	equals((new subclass()).e(), subclass, "reference to this within inherited function is to itself");

	// test calling parent functions
	equals((new subclass()).d(), 4, "parent method in overriden method is executed");
	equals((new subclass_a()).b(), 6, "parent method in overriden method is executed with additional logic");
	equals((new subsubclass()).d(), 4, "parent method in overriden method is executed (multi level)");
	equals((new subsubclass()).e(), subsubclass, "parent method's 'this' is still referencing proper object");

	// testing inherited properties
	test_a = Create({
		a : 1,
		b : 2,
		c : []
	});
	subclass_a = Create(test_a, {
		b : 3,
		d : {}
	});
	subsubclass_a = Create(subclass_a, {
		e : function() {
			this.c.push(1);
			return this.c;
		}
	});
	var x = new test_a(), y = new subclass_a(), z = new subsubclass_a();
	equals(y.a, 1, "Reusing a property from an inherited function");
	equals(y.b, 3, "Overriding a existing property from a parent class");
	equals(z.e(), x.c, "Using a object as a property causes property to be a pointer");

	// testing parent calling functions in newly added methods
	subsubclass.addProperty("f", function() {
		// function with parent version
		equals(typeof this._parent_, "function", "method with override has a parent method");
		equals(this._parent_(), this.constructor, "parent method context is current class' context");
	});
	subsubclass.addProperty("g", function() {
		// function without parent version
		equals(typeof this._parent_, "undefined", "method with no override has no parent method");
	});
	(new subsubclass()).f();
	(new subsubclass()).g();
});

test("implementing methods in classes from other objects", function() {

});<|endoftext|>


<commit_before>// Script to find regressions
//
// It should use as few liberator methods as possible, but fall back to standard mozilla/DOM methods
// The reason it, we don't want to find regressions in the regressions script, and it should survive
// massive changes in the internal liberator API, but just test for functionality of
// user-visible commands/mappings
//
// NOTE: It is preferable to run this script in a clean profile or at least do NOT use
// :mkvimperatorrc afterwards, as it can remove commands/mappings, etc.
//
// Usage: :[count]regr[essions]
// When [count] is given, just run this test. TODO: move to :regressions [spec]?

// all tests
var skipTests = [":bmarks", "gg"];

/////////////////////////////////////////////////////////////////////////////////////////
// Put definitions here which might change due to internal liberator refactoring
/////////////////////////////////////////////////////////////////////////////////////////

var doc; // document where we output status messages
var multilineOutput  = document.getElementById("liberator-multiline-output")
var singlelineOutput = document.getElementById("liberator-commandline-command")

/////////////////////////////////////////////////////////////////////////////////////////
// TESTS
//
// They are run in order, so you can specify commands which expect side effects of a
// previous command
/////////////////////////////////////////////////////////////////////////////////////////

// A series of Ex commands or mappings, each with a
// function checking whether the command succeeded
// If the string starts with a ":" it is executed as an Ex command, otherwise as a mapping
// You can also mix commands and mappings
let tests = [
    { cmds: [":!dir"],
      verify: function () getMultilineOutput().length > 10 },
    { cmds: [":abbr VIMP vimperator labs", ":abbr"],
      verify: function () getMultilineOutput().indexOf("vimperator labs") >= 0 },
    { cmds: [":unabbr VIMP", ":abbr"],
      verify: function () getMultilineOutput().indexOf("vimperator labs") == -1 },
    { cmds: [":bmarks"],
      verify: function () getMultilineOutput().length > 100 },
    { cmds: [":echo \"test\""],
      verify: function () getSinglelineOutput() == "test" },
    { cmds: [":qmark V http://test.vimperator.org", ":qmarks"],
      verify: function () getMultilineOutput().indexOf("test.vimperator.org") >= 0 },
    { cmds: [":javascript liberator.echo('test', commandline.FORCE_MULTILINE)"],
      verify: function () getMultilineOutput() == "test" },
    // { cmds: [":echomsg \"testmsg\""],
    //   verify: function () getOutput() == "testmsg" },
    // { cmds: [":echoerr \"testerr\""],
    //   verify: function () getOutput() == "testerr" },
    { cmds: ["gg", "<C-f>"], // NOTE: does not work when there is no page to scroll, we should load a large page before doing these tests
      verify: function () this._initialPos.y != getBufferPosition().y,
      init: function () this._initialPos = getBufferPosition() }

    // testing tab behavior
];

// these functions highly depend on the liberator API, so use Ex command tests whenever possible
let functions = [
    function () { return bookmarks.get("").length > 0 }, // will fail for people without bookmarks :( Might want to add one before
    function () { return history.get("").length > 0 }
];

/////////////////////////////////////////////////////////////////////////////////////////
// functions below should be as generic as possible, and not require being rewritten
// even after doing major Vimperator refactoring
/////////////////////////////////////////////////////////////////////////////////////////

function resetEnvironment()
{
    multilineOutput.contentDocument.body.innerHTML = "";
    singlelineOutput.value = "";
    commandline.close();
    modes.reset();
}

function getOutput()            multilineOutput.contentDocument.body.textContent || singlelineOutput.value;
function getMultilineOutput()   multilineOutput.contentDocument.body.textContent;
function getSinglelineOutput()  singlelineOutput.value;

function getTabIndex() getBrowser().mTabContainer.selectedIndex;
function getTabCount() getBrowser().mTabs.length;

function getBufferPosition()
{
    let win = window.content;
    return { x: win.scrollMaxX ? win.pageXOffset / win.scrollMaxX : 0,
             y: win.scrollMaxY ? win.pageYOffset / win.scrollMaxY : 0 }
};

function getLocation() window.content.document.location.href;

function echoLine(str, group)
{
    if (!doc)
        return;

    doc.body.appendChild(util.xmlToDom(

{str}
,
            doc));
}
function echoMulti(str, group)
{
    if (!doc)
        return;

    doc.body.appendChild(util.xmlToDom(
{template.maybeXML(str)}
,
            doc));
}

commands.addUserCommand(["regr[essions]"],
    "Run regression tests",
    function (args)
    {
        // TODO: might need to increase the 'messages' option temporarily
        // TODO: count (better even range) support to just run test 34 of 102
        // TODO: bang support to either: a) run commands like deleting bookmarks which
        //       should only be done in a clean profile or b) run functions and not
        //       just Ex command tests; Yet to be decided

        let updateOutputHeight = null;
        function init()
        {
            liberator.registerObserver("echoLine", echoLine);
            liberator.registerObserver("echoMultiline", echoMulti);
            liberator.open("chrome://liberator/content/buffer.xhtml", liberator.NEW_TAB);
            events.waitForPageLoad();
            doc = content.document;
            doc.body.setAttributeNS(NS.uri, "highlight", "CmdLine");

            updateOutputHeight = commandline.updateOutputHeight;
            commandline.updateOutputHeight = function (open)
            {
                let elem = document.getElementById("liberator-multiline-output");
                if (open)
                    elem.collapsed = false;
                elem.height = 0;
            };
        }
        function cleanup()
        {
            liberator.unregisterObserver("echoLine", echoLine);
            liberator.unregisterObserver("echoMultiline", echoMulti);
            commandline.updateOutputHeight = updateOutputHeight;
        }

        function run ()
        {
            let now = Date.now();
            let totalTests = tests.length + functions.length;
            let successfulTests = 0;
            let skippedTests = 0;
            let currentTest = 0;

            init();

            // TODO: might want to unify 'tests' and 'functions' handling
            // 1.) run commands and mappings tests
            outer:
            for (let [, test] in Iterator(tests))
            {
                currentTest++;
                if (args.count >= 1 && currentTest != args.count)
                    continue;

                let testDescription = util.clip(test.cmds.join(" -> "), 80);
                for (let [,cmd] in Iterator(test.cmds))
                {
                    if (skipTests.indexOf(cmd) != -1)
                    {
                        skippedTests++;
                        liberator.echomsg("Skipping test " + currentTest + " of " + totalTests + ": " + testDescription, 0);
                        continue outer;
                    }
                };

                commandline.echo("Running test " + currentTest + " of " + totalTests + ": " + testDescription, "Filter", commandline.APPEND_TO_MESSAGES);
                resetEnvironment();
                if ("init" in test)
                    test.init();

                test.cmds.forEach(function (cmd) {
                    if (cmd[0] == ":")
                        liberator.execute(cmd);
                    else
                        events.feedkeys(cmd);
                });

                if (!test.verify())
                    liberator.echoerr("Test " + currentTest + " failed: " + testDescription);
                else
                    successfulTests++;
            }

            // 2.) Run function tests
            for (let [, func] in Iterator(functions))
            {
                currentTest++;
                if (args.count >= 1 && currentTest != args.count)
                    continue;

                commandline.echo("Running test " + currentTest + " of " + totalTests + ": " + util.clip(func.toString().replace(/[\s\n]+/gm, " "), 80), "Filter", commandline.APPEND_TO_MESSAGES);
                resetEnvironment();

                if (!func())
                    liberator.echoerr("Test " + currentTest + " failed!");
                else
                    successfulTests++;
            }

            cleanup();

            let runTests = (args.count >= 1 ? 1 : totalTests) - skippedTests;
            XML.ignoreWhitespace = false;
            liberator.echomsg(<e4x>
                          {successfulTests} of {runTests}
                          tests successfully completed ({skippedTests} tests skipped) in
                          {((Date.now() - now) / 1000.0)} msec
                      </e4x>.*);
            liberator.execute(":messages");
        }

        if (!args.bang)
        {
            liberator.echo(<e4x>
                Running tests should always be done in a new profile.

                It should not do any harm to your profile, but your current settings like options,
                abbreviations or mappings might not be in the same state as before running the tests.
                Just make sure, you don't :mkvimperatorrc, after running the tests.

                Use :regressions! to skip this prompt.
            </e4x>.*);
            commandline.input("Type 'yes' to run the tests: ", function (res) { if (res == "yes") run(); } );
            return;
        }
        run();
    },
    {
        bang: true,
        argCount: "0",
        count: true
    });

// vimperator: set et sts=4 sw=4 :
<commit_msg>Fix regressions#getSinglelineOutput() (Luo Chunlei).<commit_after>// Script to find regressions
//
// It should use as few liberator methods as possible, but fall back to standard mozilla/DOM methods
// The reason it, we don't want to find regressions in the regressions script, and it should survive
// massive changes in the internal liberator API, but just test for functionality of
// user-visible commands/mappings
//
// NOTE: It is preferable to run this script in a clean profile or at least do NOT use
// :mkvimperatorrc afterwards, as it can remove commands/mappings, etc.
//
// Usage: :[count]regr[essions]
// When [count] is given, just run this test. TODO: move to :regressions [spec]?

// all tests
var skipTests = [":bmarks", "gg"];

/////////////////////////////////////////////////////////////////////////////////////////
// Put definitions here which might change due to internal liberator refactoring
/////////////////////////////////////////////////////////////////////////////////////////

var doc; // document where we output status messages
var multilineOutput  = document.getElementById("liberator-multiline-output");
var singlelineOutput = document.getElementById("liberator-message");

/////////////////////////////////////////////////////////////////////////////////////////
// TESTS
//
// They are run in order, so you can specify commands which expect side effects of a
// previous command
/////////////////////////////////////////////////////////////////////////////////////////

// A series of Ex commands or mappings, each with a
// function checking whether the command succeeded
// If the string starts with a ":" it is executed as an Ex command, otherwise as a mapping
// You can also mix commands and mappings
let tests = [
    { cmds: [":!dir"],
      verify: function () getMultilineOutput().length > 10 },
    { cmds: [":abbr VIMP vimperator labs", ":abbr"],
      verify: function () getMultilineOutput().indexOf("vimperator labs") >= 0 },
    { cmds: [":unabbr VIMP", ":abbr"],
      verify: function () getMultilineOutput().indexOf("vimperator labs") == -1 },
    { cmds: [":bmarks"],
      verify: function () getMultilineOutput().length > 100 },
    { cmds: [":echo \"test\""],
      verify: function () getSinglelineOutput() == "test" },
    { cmds: [":qmark V http://test.vimperator.org", ":qmarks"],
      verify: function () getMultilineOutput().indexOf("test.vimperator.org") >= 0 },
    { cmds: [":javascript liberator.echo('test', commandline.FORCE_MULTILINE)"],
      verify: function () getMultilineOutput() == "test" },
    // { cmds: [":echomsg \"testmsg\""],
    //   verify: function () getOutput() == "testmsg" },
    // { cmds: [":echoerr \"testerr\""],
    //   verify: function () getOutput() == "testerr" },
    { cmds: ["gg", "<C-f>"], // NOTE: does not work when there is no page to scroll, we should load a large page before doing these tests
      verify: function () this._initialPos.y != getBufferPosition().y,
      init: function () this._initialPos = getBufferPosition() }

    // testing tab behavior
];

// these functions highly depend on the liberator API, so use Ex command tests whenever possible
let functions = [
    function () { return bookmarks.get("").length > 0 }, // will fail for people without bookmarks :( Might want to add one before
    function () { return history.get("").length > 0 }
];

/////////////////////////////////////////////////////////////////////////////////////////
// functions below should be as generic as possible, and not require being rewritten
// even after doing major Vimperator refactoring
/////////////////////////////////////////////////////////////////////////////////////////

function resetEnvironment()
{
    multilineOutput.contentDocument.body.innerHTML = "";
    singlelineOutput.value = "";
    commandline.close();
    modes.reset();
}

function getOutput()            multilineOutput.contentDocument.body.textContent || singlelineOutput.value;
function getMultilineOutput()   multilineOutput.contentDocument.body.textContent;
function getSinglelineOutput()  singlelineOutput.value;

function getTabIndex() getBrowser().mTabContainer.selectedIndex;
function getTabCount() getBrowser().mTabs.length;

function getBufferPosition()
{
    let win = window.content;
    return { x: win.scrollMaxX ? win.pageXOffset / win.scrollMaxX : 0,
             y: win.scrollMaxY ? win.pageYOffset / win.scrollMaxY : 0 }
};

function getLocation() window.content.document.location.href;

function echoLine(str, group)
{
    if (!doc)
        return;

    doc.body.appendChild(util.xmlToDom(

{str}
,
            doc));
}
function echoMulti(str, group)
{
    if (!doc)
        return;

    doc.body.appendChild(util.xmlToDom(
{template.maybeXML(str)}
,
            doc));
}

commands.addUserCommand(["regr[essions]"],
    "Run regression tests",
    function (args)
    {
        // TODO: might need to increase the 'messages' option temporarily
        // TODO: count (better even range) support to just run test 34 of 102
        // TODO: bang support to either: a) run commands like deleting bookmarks which
        //       should only be done in a clean profile or b) run functions and not
        //       just Ex command tests; Yet to be decided

        let updateOutputHeight = null;
        function init()
        {
            liberator.registerObserver("echoLine", echoLine);
            liberator.registerObserver("echoMultiline", echoMulti);
            liberator.open("chrome://liberator/content/buffer.xhtml", liberator.NEW_TAB);
            events.waitForPageLoad();
            doc = content.document;
            doc.body.setAttributeNS(NS.uri, "highlight", "CmdLine");

            updateOutputHeight = commandline.updateOutputHeight;
            commandline.updateOutputHeight = function (open)
            {
                let elem = document.getElementById("liberator-multiline-output");
                if (open)
                    elem.collapsed = false;
                elem.height = 0;
            };
        }
        function cleanup()
        {
            liberator.unregisterObserver("echoLine", echoLine);
            liberator.unregisterObserver("echoMultiline", echoMulti);
            commandline.updateOutputHeight = updateOutputHeight;
        }

        function run ()
        {
            let now = Date.now();
            let totalTests = tests.length + functions.length;
            let successfulTests = 0;
            let skippedTests = 0;
            let currentTest = 0;

            init();

            // TODO: might want to unify 'tests' and 'functions' handling
            // 1.) run commands and mappings tests
            outer:
            for (let [, test] in Iterator(tests))
            {
                currentTest++;
                if (args.count >= 1 && currentTest != args.count)
                    continue;

                let testDescription = util.clip(test.cmds.join(" -> "), 80);
                for (let [,cmd] in Iterator(test.cmds))
                {
                    if (skipTests.indexOf(cmd) != -1)
                    {
                        skippedTests++;
                        liberator.echomsg("Skipping test " + currentTest + " of " + totalTests + ": " + testDescription, 0);
                        continue outer;
                    }
                };

                commandline.echo("Running test " + currentTest + " of " + totalTests + ": " + testDescription, "Filter", commandline.APPEND_TO_MESSAGES);
                resetEnvironment();
                if ("init" in test)
                    test.init();

                test.cmds.forEach(function (cmd) {
                    if (cmd[0] == ":")
                        liberator.execute(cmd);
                    else
                        events.feedkeys(cmd);
                });

                if (!test.verify())
                    liberator.echoerr("Test " + currentTest + " failed: " + testDescription);
                else
                    successfulTests++;
            }

            // 2.) Run function tests
            for (let [, func] in Iterator(functions))
            {
                currentTest++;
                if (args.count >= 1 && currentTest != args.count)
                    continue;

                commandline.echo("Running test " + currentTest + " of " + totalTests + ": " + util.clip(func.toString().replace(/[\s\n]+/gm, " "), 80), "Filter", commandline.APPEND_TO_MESSAGES);
                resetEnvironment();

                if (!func())
                    liberator.echoerr("Test " + currentTest + " failed!");
                else
                    successfulTests++;
            }

            cleanup();

            let runTests = (args.count >= 1 ? 1 : totalTests) - skippedTests;
            XML.ignoreWhitespace = false;
            liberator.echomsg(<e4x>
                          {successfulTests} of {runTests}
                          tests successfully completed ({skippedTests} tests skipped) in
                          {((Date.now() - now) / 1000.0)} msec
                      </e4x>.*);
            liberator.execute(":messages");
        }

        if (!args.bang)
        {
            liberator.echo(<e4x>
                Running tests should always be done in a new profile.

                It should not do any harm to your profile, but your current settings like options,
                abbreviations or mappings might not be in the same state as before running the tests.
                Just make sure, you don't :mkvimperatorrc, after running the tests.

                Use :regressions! to skip this prompt.
            </e4x>.*);
            commandline.input("Type 'yes' to run the tests: ", function (res) { if (res == "yes") run(); } );
            return;
        }
        run();
    },
    {
        bang: true,
        argCount: "0",
        count: true
    });

// vimperator: set et sts=4 sw=4 :
<|endoftext|>


<commit_before>/**
 * @preserve ChesterGL - Simple 2D WebGL demo/library
 *
 * Copyright (c) 2010-2011 Rolando Abarca
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/**
 * @fileoverview Externs for ChesterGL
 *
 * @see https://github.com/funkaster/ChesterGL
 * @externs
 */

/** @type {Object} */
var ChesterGL = {};

/**
 * creates a new block. Pass the rect if you want to set the frame at
 * creation time.
 *
 * @constructor
 * @param {Object.<string,number>|string=} rect
 * @param {number=} type
 * @param {ChesterGL.Block=} parent
 */
ChesterGL.Block = function (rect, type, parent) {};

/**
 * creates a new block group
 *
 * @constructor
 * @extends ChesterGL.Block
 * @param {string} texture An optional texture that will be shared with all children
 * @param {number=} noChildren The optional initial number of maxChidlren. Defaults to 10
 */
ChesterGL.BlockGroup = function (texture, noChildren) {};

/**
 * @namespace
 */
ChesterGL.BlockFrames;

/**
 * @typedef {{frame, texture}}
 */
ChesterGL.BlockFrames.frameType;

/**
 * @constructor
 * @extends ChesterGL.Block
 * @param {string} tmxFile
 */
ChesterGL.TMXBlock = function (tmxFile) {};

/**
 * @constructor
 * @extends ChesterGL.Block
 * @param {Object} properties
 */
ChesterGL.ParticleSystem = function (properties) {};

/**
 * @constructor
 * @param {ChesterGL.Block} block
 * @param {number=} totalTime
 */
ChesterGL.Action = function (block, totalTime) {};

/**
 * @constructor
 * @extends ChesterGL.Action
 * @param {ChesterGL.Block} block
 * @param {number} totalTime
 * @param {vec3} finalPosition
 */
ChesterGL.MoveToAction = function (block, totalTime, finalPosition) {};

// external - request animation frame for different browsers and base64

/**
 * @param {function()} callback
 * @param {Element=} element
 */
window.requestAnimationFrame = function (callback, element) {};

/**
 * @param {function()} callback
 * @param {Element=} element
 */
window.webkitRequestAnimationFrame = function (callback, element) {};

/**
 * @param {function()} callback
 * @param {Element=} element
 */
window.mozRequestAnimationFrame = function (callback, element) {};

/**
 * @param {function()} callback
 * @param {Element=} element
 */
window.oRequestAnimationFrame = function (callback, element) {};

/**
 * @param {function()} callback
 * @param {Element=} element
 */
window.msRequestAnimationFrame = function (callback, element) {};
<commit_msg>externs for debug<commit_after>/**
 * @preserve ChesterGL - Simple 2D WebGL demo/library
 *
 * Copyright (c) 2010-2011 Rolando Abarca
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/**
 * @fileoverview Externs for ChesterGL
 *
 * @see https://github.com/funkaster/ChesterGL
 * @externs
 */

/** @type {Object} */
var ChesterGL = {};

/**
 * creates a new block. Pass the rect if you want to set the frame at
 * creation time.
 *
 * @constructor
 * @param {Object.<string,number>|string=} rect
 * @param {number=} type
 * @param {ChesterGL.Block=} parent
 */
ChesterGL.Block = function (rect, type, parent) {};

/**
 * creates a new block group
 *
 * @constructor
 * @extends ChesterGL.Block
 * @param {string} texture An optional texture that will be shared with all children
 * @param {number=} noChildren The optional initial number of maxChidlren. Defaults to 10
 */
ChesterGL.BlockGroup = function (texture, noChildren) {};

/**
 * @namespace
 */
ChesterGL.BlockFrames;

/**
 * @typedef {{frame, texture}}
 */
ChesterGL.BlockFrames.frameType;

/**
 * @constructor
 * @extends ChesterGL.Block
 * @param {string} tmxFile
 */
ChesterGL.TMXBlock = function (tmxFile) {};

/**
 * @constructor
 * @extends ChesterGL.Block
 * @param {Object} properties
 */
ChesterGL.ParticleSystem = function (properties) {};

/**
 * @constructor
 * @param {ChesterGL.Block} block
 * @param {number=} totalTime
 */
ChesterGL.Action = function (block, totalTime) {};

/**
 * @constructor
 * @extends ChesterGL.Action
 * @param {ChesterGL.Block} block
 * @param {number} totalTime
 * @param {vec3} finalPosition
 */
ChesterGL.MoveToAction = function (block, totalTime, finalPosition) {};

// external - request animation frame for different browsers and window.WebGLDebugUtils

/**
 * @param {function()} callback
 * @param {Element=} element
 */
window.requestAnimationFrame = function (callback, element) {};

/**
 * @param {function()} callback
 * @param {Element=} element
 */
window.webkitRequestAnimationFrame = function (callback, element) {};

/**
 * @param {function()} callback
 * @param {Element=} element
 */
window.mozRequestAnimationFrame = function (callback, element) {};

/**
 * @param {function()} callback
 * @param {Element=} element
 */
window.oRequestAnimationFrame = function (callback, element) {};

/**
 * @param {function()} callback
 * @param {Element=} element
 */
window.msRequestAnimationFrame = function (callback, element) {};

/**
 * @namespace
 */
window.WebGLDebugUtils;

/**
 * @param {WebGLRenderingContext} ctx
 */
window.WebGLDebugUtils.makeDebugContext = function (ctx) {};
<|endoftext|>


<commit_before>(function() {
  scripts = [
    'components/lodash/index.js',
    'components/jquery/index.js',
    'components/iscroll/index.js',
    'components/iscroll-sticky/index.js',
    'components/angular/index.js',
    'components/angular-ui-router/index.js',
    'dist/bradypodion.js'
  ];

  if (typeof module !== 'undefined' && module.exports) {
    module.exports.scripts = scripts;
  } else {

    scripts = scripts.map(function (script) {
      return '../../../../'+script;
    });

    if (!/phantom/i.test(navigator.userAgent) && document.location.protocol !== 'file:') {
      scripts.push(window.location.protocol + '//' + window.location.hostname + ':35729/livereload.js');
    } else {
      console.warn('Bradypodion: "Serve this site from a webserver to enable livereload."');
    }

    (function load(i){
      var s  = document.createElement('script');
      s.type = 'text/javascript';
      s.src  = scripts[i];
      s.addEventListener('load', function(e){
        i++;
        if (scripts[i]) {
          load(i);
        } else if (typeof finalLoad === 'function'){
          finalLoad();
        }
      });
      if (/livereload/.test(scripts[i])) {
        s.addEventListener('error', function(e){
          console.warn('Bradypodion: "Run `grunt dev` in your terminal to enable livereload."');
          if (typeof finalLoad === 'function'){
            finalLoad();
          }
        });
      }
      document.body.appendChild(s);
    })(0);

  }

}).call(this);
<commit_msg>chore(deps): extract path from document<commit_after>(function() {
  scripts = [
    'components/lodash/index.js',
    'components/jquery/index.js',
    'components/iscroll/index.js',
    'components/iscroll-sticky/index.js',
    'components/angular/index.js',
    'components/angular-ui-router/index.js',
    'dist/bradypodion.js'
  ];

  if (typeof module !== 'undefined' && module.exports) {
    module.exports.scripts = scripts;
  } else {

    var pathDeepness = document.querySelector('script').attributes.src.nodeValue.replace('deps.js','');
    scripts = scripts.map(function (script) {
      return pathDeepness+script;
    });

    if (!/phantom/i.test(navigator.userAgent) && document.location.protocol !== 'file:') {
      scripts.push(window.location.protocol + '//' + window.location.hostname + ':35729/livereload.js');
    } else {
      console.warn('Bradypodion: "Serve this site from a webserver to enable livereload."');
    }

    (function load(i){
      var s  = document.createElement('script');
      s.type = 'text/javascript';
      s.src  = scripts[i];
      s.addEventListener('load', function(e){
        i++;
        if (scripts[i]) {
          load(i);
        } else if (typeof finalLoad === 'function'){
          finalLoad();
        }
      });
      if (/livereload/.test(scripts[i])) {
        s.addEventListener('error', function(e){
          console.warn('Bradypodion: "Run `grunt dev` in your terminal to enable livereload."');
          if (typeof finalLoad === 'function'){
            finalLoad();
          }
        });
      }
      document.body.appendChild(s);
    })(0);

  }

}).call(this);
<|endoftext|>


<commit_before>var DEBUG = 1;

function round(x) {
	const lowestPlate = 2.5;
	var roundTo = lowestPlate * 2;
	return Math.round(x / roundTo) * roundTo;
}

function log() {
	console.log(...arguments);
}

function warn() {
	debugger;
	console.warn(...arguments);
}
<commit_msg>improve some utility functions<commit_after>var DEBUG = 1;

/* ====================
     General utils
   ==================== */
function log() {
	console.log(...arguments);
	return arguments.length === 1 ? arguments[0] : _.toArray(arguments);
}

function warn() {
	debugger;
	console.warn(...arguments);
	return arguments.length === 1 ? arguments[0] : _.toArray(arguments);
}

/* ====================
      Workout utils
   ==================== */

/**
 * Round num to nearestY
 * @param {Number} nearestNum
 * @param {Number} num
 * @return {Number}
 */
function roundTo(nearestNum, num) {
	return Math.round(num / nearestNum) * nearestNum;
}

const lowestPlate = 2.5; // TODO: get from cfg
var round = _.curry(roundTo)(lowestPlate * 2);
<|endoftext|>


<commit_before>const INPUT_FOCUSED = 'INPUT_FOCUSED';
const INPUT_BLURRED = 'INPUT_BLURRED';
const INPUT_CHANGED = 'INPUT_CHANGED';
const UPDATE_FOCUSED_SUGGESTION = 'UPDATE_FOCUSED_SUGGESTION';
const REVEAL_SUGGESTIONS = 'REVEAL_SUGGESTIONS';
const CLOSE_SUGGESTIONS = 'CLOSE_SUGGESTIONS';

export function inputFocused(shouldRenderSuggestions) {
  return {
    type: INPUT_FOCUSED,
    shouldRenderSuggestions
  };
}

export function inputBlurred() {
  return {
    type: INPUT_BLURRED
  };
}

export function inputChanged(shouldRenderSuggestions, lastAction) {
  return {
    type: INPUT_CHANGED,
    shouldRenderSuggestions,
    lastAction
  };
}

export function updateFocusedSuggestion(sectionIndex, suggestionIndex, value) {
  return {
    type: UPDATE_FOCUSED_SUGGESTION,
    sectionIndex,
    suggestionIndex,
    value
  };
}

export function revealSuggestions() {
  return {
    type: REVEAL_SUGGESTIONS
  };
}

export function closeSuggestions(lastAction) {
  return {
    type: CLOSE_SUGGESTIONS,
    lastAction
  };
}

export default function reducer(state, action) {
  switch (action.type) {
    case INPUT_FOCUSED:
      return {
        ...state,
        isFocused: true,
        isCollapsed: !action.shouldRenderSuggestions
      };

    case INPUT_BLURRED:
      return {
        ...state,
        isFocused: false,
        focusedSectionIndex: null,
        focusedSuggestionIndex: null,
        isCollapsed: true
      };

    case INPUT_CHANGED:
      return {
        ...state,
        focusedSectionIndex: null,
        focusedSuggestionIndex: null,
        valueBeforeUpDown: null,
        isCollapsed: !action.shouldRenderSuggestions,
        lastAction: action.lastAction
      };

    case UPDATE_FOCUSED_SUGGESTION: {
      const { value, sectionIndex, suggestionIndex } = action;
      const valueBeforeUpDown =
        state.valueBeforeUpDown === null && typeof value !== 'undefined'
          ? value
          : state.valueBeforeUpDown;

      return {
        ...state,
        focusedSectionIndex: sectionIndex,
        focusedSuggestionIndex: suggestionIndex,
        valueBeforeUpDown
      };
    }

    case REVEAL_SUGGESTIONS:
      return {
        ...state,
        isCollapsed: false
      };

    case CLOSE_SUGGESTIONS:
      return {
        ...state,
        focusedSectionIndex: null,
        focusedSuggestionIndex: null,
        valueBeforeUpDown: null,
        isCollapsed: true,
        lastAction: action.lastAction
      };

    default:
      return state;
  }
}
<commit_msg>Set valueBeforeUpDown to null onBlur<commit_after>const INPUT_FOCUSED = 'INPUT_FOCUSED';
const INPUT_BLURRED = 'INPUT_BLURRED';
const INPUT_CHANGED = 'INPUT_CHANGED';
const UPDATE_FOCUSED_SUGGESTION = 'UPDATE_FOCUSED_SUGGESTION';
const REVEAL_SUGGESTIONS = 'REVEAL_SUGGESTIONS';
const CLOSE_SUGGESTIONS = 'CLOSE_SUGGESTIONS';

export function inputFocused(shouldRenderSuggestions) {
  return {
    type: INPUT_FOCUSED,
    shouldRenderSuggestions
  };
}

export function inputBlurred() {
  return {
    type: INPUT_BLURRED
  };
}

export function inputChanged(shouldRenderSuggestions, lastAction) {
  return {
    type: INPUT_CHANGED,
    shouldRenderSuggestions,
    lastAction
  };
}

export function updateFocusedSuggestion(sectionIndex, suggestionIndex, value) {
  return {
    type: UPDATE_FOCUSED_SUGGESTION,
    sectionIndex,
    suggestionIndex,
    value
  };
}

export function revealSuggestions() {
  return {
    type: REVEAL_SUGGESTIONS
  };
}

export function closeSuggestions(lastAction) {
  return {
    type: CLOSE_SUGGESTIONS,
    lastAction
  };
}

export default function reducer(state, action) {
  switch (action.type) {
    case INPUT_FOCUSED:
      return {
        ...state,
        isFocused: true,
        isCollapsed: !action.shouldRenderSuggestions
      };

    case INPUT_BLURRED:
      return {
        ...state,
        isFocused: false,
        focusedSectionIndex: null,
        focusedSuggestionIndex: null,
        valueBeforeUpDown: null,
        isCollapsed: true
      };

    case INPUT_CHANGED:
      return {
        ...state,
        focusedSectionIndex: null,
        focusedSuggestionIndex: null,
        valueBeforeUpDown: null,
        isCollapsed: !action.shouldRenderSuggestions,
        lastAction: action.lastAction
      };

    case UPDATE_FOCUSED_SUGGESTION: {
      const { value, sectionIndex, suggestionIndex } = action;
      const valueBeforeUpDown =
        state.valueBeforeUpDown === null && typeof value !== 'undefined'
          ? value
          : state.valueBeforeUpDown;

      return {
        ...state,
        focusedSectionIndex: sectionIndex,
        focusedSuggestionIndex: suggestionIndex,
        valueBeforeUpDown
      };
    }

    case REVEAL_SUGGESTIONS:
      return {
        ...state,
        isCollapsed: false
      };

    case CLOSE_SUGGESTIONS:
      return {
        ...state,
        focusedSectionIndex: null,
        focusedSuggestionIndex: null,
        valueBeforeUpDown: null,
        isCollapsed: true,
        lastAction: action.lastAction
      };

    default:
      return state;
  }
}
<|endoftext|>


<commit_before>'use strict';

var _ = require('underscore');
var expect = require('chai').expect;

var ProxyVerifier = require('../../');
var helpers = require('../helpers');

describe('testTunnel(proxy[, options], cb)', function() {

	var appServer;

	before(function() {

		appServer = helpers.createAppServer(3001, '127.0.0.1');

		ProxyVerifier._tunnelTestUrl = 'https://127.0.0.1:3002/check';
	});

	after(function() {

		appServer.http.close();
		appServer.https.close();
	});

	var proxyServers = {};

	before(function() {

		proxyServers.withTunneling = helpers.createProxyServer(5050, '127.0.0.2');
		proxyServers.withoutTunneling = helpers.createProxyServer(5051, '127.0.0.3', { tunnel: false });
	});

	after(function() {

		_.each(_.values(proxyServers), function(proxyServer) {
			proxyServer.close();
			proxyServer.http.close();
			proxyServer.https.close();
		});
	});

	it('should be a function', function() {

		expect(ProxyVerifier.testTunnel).to.be.a('function');
	});

	it('proxy with tunneling', function(done) {

		var proxyServer = proxyServers.withTunneling;
		var proxyProtocol = 'http';

		var proxy = {
			ip_address: proxyServer[proxyProtocol].address().address,
			port: proxyServer[proxyProtocol].address().port,
			protocols: [proxyProtocol]
		};

		var requestOptions = {
			strictSSL: false,
			proxyOptions: {
				rejectUnauthorized: false
			},
			timeout: 100
		};

		ProxyVerifier.testTunnel(proxy, requestOptions, function(error, result) {

			if (error) {
				return done(error);
			}

			try {
				expect(result).to.be.an('object');
				expect(result.ok).to.equal(true);
				expect(result.error).to.equal(undefined);
			} catch (error) {
				return done(error);
			}

			done();
		});
	});

	it('proxy without tunneling', function(done) {

		var proxyServer = proxyServers.withoutTunneling;
		var proxyProtocol = 'http';

		var proxy = {
			ip_address: proxyServer[proxyProtocol].address().address,
			port: proxyServer[proxyProtocol].address().port,
			protocols: [proxyProtocol]
		};

		var requestOptions = {
			strictSSL: false,
			proxyOptions: {
				rejectUnauthorized: false
			},
			timeout: 100
		};

		ProxyVerifier.testTunnel(proxy, requestOptions, function(error, result) {

			if (error) {
				return done(error);
			}

			try {
				expect(result).to.be.an('object');
				expect(result.ok).to.equal(false);
				expect(result.error).to.not.equal(undefined);
				expect(result.error).to.be.an('object');
			} catch (error) {
				return done(error);
			}

			done();
		});
	});
});
<commit_msg>Minor changes for uniformity<commit_after>'use strict';

var _ = require('underscore');
var expect = require('chai').expect;

var ProxyVerifier = require('../../');
var helpers = require('../helpers');

describe('testTunnel(proxy[, options], cb)', function() {

	var appServer;

	before(function() {

		appServer = helpers.createAppServer(3001, '127.0.0.1');

		ProxyVerifier._tunnelTestUrl = 'https://127.0.0.1:3002/check';
	});

	after(function() {

		appServer.http.close();
		appServer.https.close();
	});

	var proxyServers = {};

	before(function() {

		proxyServers.withTunneling = helpers.createProxyServer(5050, '127.0.0.2');
		proxyServers.withoutTunneling = helpers.createProxyServer(5051, '127.0.0.3', { tunnel: false });
	});

	after(function() {

		_.each(_.values(proxyServers), function(proxyServer) {
			proxyServer.close();
			proxyServer.http.close();
			proxyServer.https.close();
		});
	});

	it('should be a function', function() {

		expect(ProxyVerifier.testTunnel).to.be.a('function');
	});

	it('proxy with tunneling', function(done) {

		var proxyServer = proxyServers.withTunneling;
		var proxyProtocol = 'http';

		var proxy = {
			ip_address: proxyServer[proxyProtocol].address().address,
			port: proxyServer[proxyProtocol].address().port,
			protocols: [proxyProtocol]
		};

		var requestOptions = {
			strictSSL: false,
			proxyOptions: {
				rejectUnauthorized: false
			},
			timeout: 100
		};

		ProxyVerifier.testTunnel(proxy, requestOptions, function(error, result) {

			try {
				expect(error).to.equal(null);
				expect(result).to.be.an('object');
				expect(result.ok).to.equal(true);
				expect(result.error).to.equal(undefined);
			} catch (error) {
				return done(error);
			}

			done();
		});
	});

	it('proxy without tunneling', function(done) {

		var proxyServer = proxyServers.withoutTunneling;
		var proxyProtocol = 'http';

		var proxy = {
			ip_address: proxyServer[proxyProtocol].address().address,
			port: proxyServer[proxyProtocol].address().port,
			protocols: [proxyProtocol]
		};

		var requestOptions = {
			strictSSL: false,
			proxyOptions: {
				rejectUnauthorized: false
			},
			timeout: 100
		};

		ProxyVerifier.testTunnel(proxy, requestOptions, function(error, result) {

			try {
				expect(error).to.equal(null);
				expect(result).to.be.an('object');
				expect(result.ok).to.equal(false);
				expect(result.error).to.not.equal(undefined);
				expect(result.error).to.be.an('object');
			} catch (error) {
				return done(error);
			}

			done();
		});
	});
});
<|endoftext|>


<commit_before>var chai = require("chai");
chai.Should();

describe('Unknown pgn', function () {
  it('return undefined', function () {
    var tree = require("../n2kMapper.js").toDelta(
      JSON.parse('{"timestamp":"2013-10-08-16:04:06.044","prio":"3","src":"1","dst":"255","pgn":"999999","description":"System Time","fields":{"SID":"222","Date":"2013.10.08", "Time": "16:04:00"}}'));

  });
});

<commit_msg>fix: fix test to actually test something<commit_after>const chai = require("chai");
chai.Should();
const assert = require('assert')

describe('Unknown pgn', function () {
  it('returns delta with one update that has no values', function () {
    var delta = require("../n2kMapper.js").toDelta(JSON.parse('{"timestamp":"2013-10-08-16:04:06.044","prio":"3","src":"1","dst":"255","pgn":"999999","description":"System Time","fields":{"SID":"222","Date":"2013.10.08", "Time": "16:04:00"}}'));
    assert.equal(delta.updates[0].values.length, 0)
  });
});
<|endoftext|>


<commit_before>import _ from "lodash";
import React from "react";
import * as globals from "./globals";

class Curate extends React.Component {

  constructor(props) {
    super(props);
    this.hullElems = [];
    this.Viewer = null;

    this.state = {
      selectedComment: null,
    };
  }

  render () {
    return (

        <button>All comments</button>
        <button>My votes</button>

 Group:

        <button>A</button>
        <button>B</button>
        <button>C</button>
        <button>D</button>
        <button>Majority Opinion</button>

    )
  }
}

export default Curate;
<commit_msg>curate buttons<commit_after>import _ from "lodash";
import React from "react";
import * as globals from "./globals";

class Curate extends React.Component {

  constructor(props) {
    super(props);

    this.state = {

    };
  }

  render () {
    return (

        <button>X</button>
        <button>Y</button>

 Group:

        <button>A</button>
        <button>B</button>
        <button>C</button>
        <button>D</button>
        <button>Majority Opinion</button>
        <button>My votes</button>
        <button>All comments</button>

    )
  }
}

export default Curate;
<|endoftext|>