<commit_before>/**
 * The HTML5 Canvas map layer module.
 *
 * @return CanvasLayer class (extends Class).
 */
define([
  'underscore',
  'mps',
  '_string',
  'abstract/layer/OverlayLayerClass'
], function(_, mps, _string, OverlayLayerClass) {

  'use strict';

  var MAX_MONTHS = 200;
  var BASE_MONTH = 72;

  var CanvasJSONLayerClass = OverlayLayerClass.extend({

    defaults: {
      cartodbUserName: 'wri-01',
      dataMaxZoom: 17,
    },

    init: function(layer, options, map) {
      this.tiles = {};
      this.layer = layer;
      this.top_date = (((moment(this.layer.maxdate).year()  - moment(this.layer.mindate).year()) * 12) + moment(this.layer.maxdate).month()) - 2;
      this._super(layer, options, map);
      this.getDates();
      this.cartoSQL = new cartodb.SQL({
        user: this.options.cartodbUserName
      });
    },

    _getLayer: function() {
      var deferred = new $.Deferred();
      deferred.resolve(this);
      mps.publish('Map/loading', [false]);
      return deferred.promise();
    },

    _getCanvas: function(coord, zoom, ownerDocument) {
      // create canvas and reset style
      var canvas = ownerDocument.createElement('canvas');
      canvas.className = this.layer.slug;
      canvas.style.border = 'none';
      canvas.style.margin = '0';
      canvas.style.padding = '0';

      // prepare canvas and context sizes
      var ctx = canvas.getContext('2d');
      ctx.width = canvas.width = this.tileSize.width;
      ctx.height = canvas.height = this.tileSize.height;

      canvas.ctx = ctx;
      return canvas;
    },

    /**
     * Called whenever the Google Maps API determines that the map needs to
     * display new tiles for the given viewport.
     *
     * @param  {obj}     coord         coordenades {x ,y}
     * @param  {integer} zoom          current map zoom
     * @param  {object}  ownerDocument
     *
     * @return {canvas}  canvas        tile canvas
     */
    getTile: function(coord, zoom, ownerDocument) {
      var canvas = this._getCanvas(coord, zoom, ownerDocument);
      var sql = this._getSQL(coord.x, coord.y, zoom);
      var zoomDiff = zoom + 8 - Math.min(zoom + 8, 16);

      this.cartoSQL.execute(sql, _.bind(function(data) {
        if (!data) {return;}

        var tile = {
          canvas: canvas,
          ctx: canvas.ctx,
          width: this.tileSize.width,
          coord: coord,
          zoom: zoom,
          height: this.tileSize.height,
          cells: this.preCacheMonths(data.rows, coord, zoom,
            zoomDiff),
          top_date : data.top_date
        };

        //set unique id
        var tileId = '{0}_{1}_{2}'.format(coord.x, coord.y, zoom);
        canvas.setAttribute('id', tileId);

        if (tileId in this.tiles) {
          delete this.tiles[tileId];
        }

        this.tiles[tileId] = tile;

        this._render(tile);
      }, this));

      return canvas;
    },

    _getSQL: function(x, y, z) {
      // zoom + 8 is get because a tile in 'zoom' zoom level is a pixel in 'zoom + 8'
      // level. Remember, it is a quadtree, 1^8 = 256 and tile size is 256px
      var pixel_zoom = Math.min(z + 8, 16);
      var zoom_diff = z + 8 - pixel_zoom;

      // get x, y for cells and sd, se for deforestation changes
      // sd contains the months
      // se contains the deforestation for each entry in sd
      // take se and sd as a matrix [se|sd]
      var sql = _.str.sprintf(
        'SELECT cartodb_id, x, y, sd, se FROM %(tableName)s WHERE z = %(z)s  AND x >= %(cx)s AND x < %(cx1)s AND y >= %(cy)s AND y < %(cy1)s', {
          tableName: this.layer.table_name,
          cx: (x * 256) >> zoom_diff,
          cx1: ((x + 1) * 256) >> zoom_diff,
          cy: (y * 256) >> zoom_diff,
          cy1: ((y + 1) * 256) >> zoom_diff,
          z: pixel_zoom
        });
      return sql;
    },

    _render: function(tile) {
      var month = this.endMonth || -BASE_MONTH + MAX_MONTHS;
      var month_start = this.startMonth || 0;
      var month_change = this.top_date;
      var w = tile.canvas.width;
      var ctx = tile.ctx;
      var cells = tile.cells;
      if (!cells || cells.length === 0) {
        return;
      }

      // clear canvas
      tile.canvas.width = w;
      var xc = cells.xcoords;
      var yc = cells.ycoords;

      // render cells
      var len = cells.length;
      var pixel_size = cells.size;
      var index, index0, index1,mul;
      var previous = [];
      for (var i = 0; i < len; ++i) {
        mul = MAX_MONTHS * i;
        index  = mul + month;
        index0 = mul + month_start;
        index1 = mul + month_change;
        // set pixel by hand faster than doing fill rect (below)
        if (cells.deforestation[index] - cells.deforestation[index0] > 0) {
          ctx.fillStyle = '#F69';
          ctx.fillRect(xc[i], yc[i], pixel_size, pixel_size);
        }
        if (month >= month_change && cells.deforestation[index] - cells.deforestation[index1] > 0) {
          ctx.fillStyle = 'rgb(233, 189, 21)';
          ctx.fillRect(xc[i], yc[i], pixel_size, pixel_size);
        }
      }
    },

    preCacheMonths: function(rows, coord, zoom, zoom_diff) {
      var row,
          xcoords,
          ycoords,
          deforestation;

      if (typeof(ArrayBuffer) !== 'undefined') {
        xcoords       = new Uint8Array(new ArrayBuffer(rows.length));
        ycoords       = new Uint8Array(new ArrayBuffer(rows.length));
        deforestation = new Uint8Array(new ArrayBuffer(rows.length * MAX_MONTHS)); // 256 months
      } else {
        // fallback
        xcoords = [];
        ycoords = [];
        deforestation = [];

        // array buffer set by default to 0
        // fucking javascript arrays are not
        for (var r = 0; r < rows.length * MAX_MONTHS; ++r) {
          deforestation[r] = 0;
        }
      }

      // base tile x, y
      var tile_base_x = coord.x * 256;
      var tile_base_y = coord.y * 256;
      for (var i in rows) {
        row = rows[i];
        xcoords[i] = (row.x - tile_base_x) << zoom_diff;
        ycoords[i] = (row.y - tile_base_y) << zoom_diff;
        var base_idx = i * MAX_MONTHS;

        if (row.sd !== null) {
          for (var j = 0; j < row.sd.length; ++j) {
            var base = base_idx + row.sd[j] - BASE_MONTH;
            deforestation[base] = row.se[j];
          }
        }

        // add to the deforestation array each previous value, thus we have the whole picture at the end
        for (var j = 1; j < MAX_MONTHS; ++j) {
          deforestation[base_idx + j] += deforestation[base_idx + j - 1];
        }
      }

      return {
        length: rows.length,
        xcoords: xcoords,
        ycoords: ycoords,
        deforestation: deforestation,
        size: 1 << zoom_diff
      };
    },

    updateTiles: function() {
      this.getDates();
      _.each(this.tiles, _.bind(function(tile) {
        this._render(tile);
      }, this));
    },

    getDates: function() {
      this.startMonth = Math.abs(moment(this.layer.mindate).diff(this.currentDate[0], 'months'));
      this.endMonth = Math.abs(moment(this.layer.mindate).diff(this.currentDate[1], 'months'));
    }

  });

  return CanvasJSONLayerClass;

});
<commit_msg>Fix: Canvas JSON - Added missing moment<commit_after>/**
 * The HTML5 Canvas map layer module.
 *
 * @return CanvasLayer class (extends Class).
 */
define([
  'underscore',
  'moment',
  'mps',
  '_string',
  'abstract/layer/OverlayLayerClass'
], function(
  _,
  moment,
  mps,
  _string,
  OverlayLayerClass
) {

  'use strict';

  var MAX_MONTHS = 200;
  var BASE_MONTH = 72;

  var CanvasJSONLayerClass = OverlayLayerClass.extend({

    defaults: {
      cartodbUserName: 'wri-01',
      dataMaxZoom: 17,
    },

    init: function(layer, options, map) {
      this.tiles = {};
      this.layer = layer;
      this.top_date = (((moment(this.layer.maxdate).year() - moment(this.layer.mindate).year()) * 12) + moment(this.layer.maxdate).month()) - 2;
      this._super(layer, options, map);
      this.getDates();
      this.cartoSQL = new cartodb.SQL({
        user: this.options.cartodbUserName
      });
    },

    _getLayer: function() {
      var deferred = new $.Deferred();
      deferred.resolve(this);
      mps.publish('Map/loading', [false]);
      return deferred.promise();
    },

    _getCanvas: function(coord, zoom, ownerDocument) {
      // create canvas and reset style
      var canvas = ownerDocument.createElement('canvas');
      canvas.className = this.layer.slug;
      canvas.style.border = 'none';
      canvas.style.margin = '0';
      canvas.style.padding = '0';

      // prepare canvas and context sizes
      var ctx = canvas.getContext('2d');
      ctx.width = canvas.width = this.tileSize.width;
      ctx.height = canvas.height = this.tileSize.height;

      canvas.ctx = ctx;
      return canvas;
    },

    /**
     * Called whenever the Google Maps API determines that the map needs to
     * display new tiles for the given viewport.
     *
     * @param  {obj}     coord         coordenades {x ,y}
     * @param  {integer} zoom          current map zoom
     * @param  {object}  ownerDocument
     *
     * @return {canvas}  canvas        tile canvas
     */
    getTile: function(coord, zoom, ownerDocument) {
      var canvas = this._getCanvas(coord, zoom, ownerDocument);
      var sql = this._getSQL(coord.x, coord.y, zoom);
      var zoomDiff = zoom + 8 - Math.min(zoom + 8, 16);

      this.cartoSQL.execute(sql, _.bind(function(data) {
        if (!data) {return;}

        var tile = {
          canvas: canvas,
          ctx: canvas.ctx,
          width: this.tileSize.width,
          coord: coord,
          zoom: zoom,
          height: this.tileSize.height,
          cells: this.preCacheMonths(data.rows, coord, zoom,
            zoomDiff),
          top_date : data.top_date
        };

        //set unique id
        var tileId = '{0}_{1}_{2}'.format(coord.x, coord.y, zoom);
        canvas.setAttribute('id', tileId);

        if (tileId in this.tiles) {
          delete this.tiles[tileId];
        }

        this.tiles[tileId] = tile;

        this._render(tile);
      }, this));

      return canvas;
    },

    _getSQL: function(x, y, z) {
      // zoom + 8 is get because a tile in 'zoom' zoom level is a pixel in 'zoom + 8'
      // level. Remember, it is a quadtree, 1^8 = 256 and tile size is 256px
      var pixel_zoom = Math.min(z + 8, 16);
      var zoom_diff = z + 8 - pixel_zoom;

      // get x, y for cells and sd, se for deforestation changes
      // sd contains the months
      // se contains the deforestation for each entry in sd
      // take se and sd as a matrix [se|sd]
      var sql = _.str.sprintf(
        'SELECT cartodb_id, x, y, sd, se FROM %(tableName)s WHERE z = %(z)s  AND x >= %(cx)s AND x < %(cx1)s AND y >= %(cy)s AND y < %(cy1)s', {
          tableName: this.layer.table_name,
          cx: (x * 256) >> zoom_diff,
          cx1: ((x + 1) * 256) >> zoom_diff,
          cy: (y * 256) >> zoom_diff,
          cy1: ((y + 1) * 256) >> zoom_diff,
          z: pixel_zoom
        });
      return sql;
    },

    _render: function(tile) {
      var month = this.endMonth || -BASE_MONTH + MAX_MONTHS;
      var month_start = this.startMonth || 0;
      var month_change = this.top_date;
      var w = tile.canvas.width;
      var ctx = tile.ctx;
      var cells = tile.cells;
      if (!cells || cells.length === 0) {
        return;
      }

      // clear canvas
      tile.canvas.width = w;
      var xc = cells.xcoords;
      var yc = cells.ycoords;

      // render cells
      var len = cells.length;
      var pixel_size = cells.size;
      var index, index0, index1,mul;
      var previous = [];
      for (var i = 0; i < len; ++i) {
        mul = MAX_MONTHS * i;
        index  = mul + month;
        index0 = mul + month_start;
        index1 = mul + month_change;
        // set pixel by hand faster than doing fill rect (below)
        if (cells.deforestation[index] - cells.deforestation[index0] > 0) {
          ctx.fillStyle = '#F69';
          ctx.fillRect(xc[i], yc[i], pixel_size, pixel_size);
        }
        if (month >= month_change && cells.deforestation[index] - cells.deforestation[index1] > 0) {
          ctx.fillStyle = 'rgb(233, 189, 21)';
          ctx.fillRect(xc[i], yc[i], pixel_size, pixel_size);
        }
      }
    },

    preCacheMonths: function(rows, coord, zoom, zoom_diff) {
      var row,
          xcoords,
          ycoords,
          deforestation;

      if (typeof(ArrayBuffer) !== 'undefined') {
        xcoords       = new Uint8Array(new ArrayBuffer(rows.length));
        ycoords       = new Uint8Array(new ArrayBuffer(rows.length));
        deforestation = new Uint8Array(new ArrayBuffer(rows.length * MAX_MONTHS)); // 256 months
      } else {
        // fallback
        xcoords = [];
        ycoords = [];
        deforestation = [];

        // array buffer set by default to 0
        // fucking javascript arrays are not
        for (var r = 0; r < rows.length * MAX_MONTHS; ++r) {
          deforestation[r] = 0;
        }
      }

      // base tile x, y
      var tile_base_x = coord.x * 256;
      var tile_base_y = coord.y * 256;
      for (var i in rows) {
        row = rows[i];
        xcoords[i] = (row.x - tile_base_x) << zoom_diff;
        ycoords[i] = (row.y - tile_base_y) << zoom_diff;
        var base_idx = i * MAX_MONTHS;

        if (row.sd !== null) {
          for (var j = 0; j < row.sd.length; ++j) {
            var base = base_idx + row.sd[j] - BASE_MONTH;
            deforestation[base] = row.se[j];
          }
        }

        // add to the deforestation array each previous value, thus we have the whole picture at the end
        for (var j = 1; j < MAX_MONTHS; ++j) {
          deforestation[base_idx + j] += deforestation[base_idx + j - 1];
        }
      }

      return {
        length: rows.length,
        xcoords: xcoords,
        ycoords: ycoords,
        deforestation: deforestation,
        size: 1 << zoom_diff
      };
    },

    updateTiles: function() {
      this.getDates();
      _.each(this.tiles, _.bind(function(tile) {
        this._render(tile);
      }, this));
    },

    getDates: function() {
      this.startMonth = Math.abs(moment(this.layer.mindate).diff(this.currentDate[0], 'months'));
      this.endMonth = Math.abs(moment(this.layer.mindate).diff(this.currentDate[1], 'months'));
    }

  });

  return CanvasJSONLayerClass;

});
<|endoftext|>


<commit_before>(function(){function b(a){if(!(this instanceof b))return new b(a);if(!a)throw Error("No DOM elements passed into Touche");this.nodes=a;return this}var e="ontouchstart"in window||"onmsgesturechange"in window;b.prototype.on=function(a,b){e&&(a="click"==a?"touchend":a);var c=this.nodes,d=c.length;if(d)for(;d--;)c[d].addEventListener(a,b,!1);else c.addEventListener(a,b,!1);return this};window.Touche=b;if(window.jQuery&&e){var f=jQuery.fn.on;jQuery.fn.on=function(){var a=arguments[0];arguments[0]="click"===
a?"touchend":a;f.apply(this,arguments)}}})();
<commit_msg>Delete touche.min.js<commit_after><|endoftext|>


<commit_before>/**
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

goog.provide('org.apache.flex.core.Application');

goog.require('org.apache.flex.core.HTMLElementWrapper');
goog.require('org.apache.flex.core.IValuesImpl');
goog.require('org.apache.flex.core.ValuesManager');
goog.require('org.apache.flex.utils.MXMLDataInterpreter');

/**
 * @constructor
 * @extends {org.apache.flex.core.HTMLElementWrapper}
 */
org.apache.flex.core.Application = function() {
  org.apache.flex.core.Application.base(this, 'constructor');
};
goog.inherits(org.apache.flex.core.Application,
    org.apache.flex.core.HTMLElementWrapper);

/**
 * Metadata
 *
 * @type {Object.<string, Array.<Object>>}
 */
org.apache.flex.core.Application.prototype.FLEXJS_CLASS_INFO =
    { names: [{ name: 'Application',
                qName: 'org.apache.flex.core.Application' }] };

/**
 * @expose
 * @type {Object}
 */
org.apache.flex.core.Application.prototype.controller = null;

/**
 * @expose
 * @type {Object}
 */
org.apache.flex.core.Application.prototype.initialView = null;

/**
 * @expose
 * @type {org.apache.flex.events.EventDispatcher}
 */
org.apache.flex.core.Application.prototype.model = null;

/**
 * @expose
 * @param {org.apache.flex.core.IValuesImpl} value The IValuesImpl.
 */
org.apache.flex.core.Application.prototype.set_valuesImpl =
    function(value) {
  org.apache.flex.core.ValuesManager.valuesImpl = value;
  if (value.init) {
    value.init(this);
  }
};

/**
 * @expose
 */
org.apache.flex.core.Application.prototype.start = function() {
  this.element = document.getElementsByTagName('body')[0];
  this.element.flexjs_wrapper = this;
  this.element.className = 'Application';

  org.apache.flex.utils.MXMLDataInterpreter.generateMXMLInstances(this, null, this.get_MXMLDescriptor());

  this.dispatchEvent('initialize');

  this.initialView.applicationModel = this.model;
  this.addElement(this.initialView);

  this.dispatchEvent('viewChanged');
};

/**
 * @expose
 * @param {Array} data The data for the attributes.
 */
org.apache.flex.core.Application.prototype.generateMXMLAttributes = function(data) {
  org.apache.flex.utils.MXMLDataInterpreter.generateMXMLProperties(this, data);
};

/**
 * @param {Object} c The child element.
 */
org.apache.flex.core.Application.prototype.addElement =
    function(c) {
  this.element.appendChild(c.element);
  c.addedToParent();
};

<commit_msg>AS version implements IParent<commit_after>/**
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

goog.provide('org.apache.flex.core.Application');

goog.require('org.apache.flex.core.HTMLElementWrapper');
goog.require('org.apache.flex.core.IParent');
goog.require('org.apache.flex.core.IValuesImpl');
goog.require('org.apache.flex.core.ValuesManager');
goog.require('org.apache.flex.utils.MXMLDataInterpreter');

/**
 * @constructor
 * @extends {org.apache.flex.core.HTMLElementWrapper}
 */
org.apache.flex.core.Application = function() {
  org.apache.flex.core.Application.base(this, 'constructor');
};
goog.inherits(org.apache.flex.core.Application,
    org.apache.flex.core.HTMLElementWrapper);

/**
 * Metadata
 *
 * @type {Object.<string, Array.<Object>>}
 */
org.apache.flex.core.Application.prototype.FLEXJS_CLASS_INFO =
    { names: [{ name: 'Application',
                qName: 'org.apache.flex.core.Application' }],
      interfaces: [org.apache.flex.core.IParent] };

/**
 * @expose
 * @type {Object}
 */
org.apache.flex.core.Application.prototype.controller = null;

/**
 * @expose
 * @type {Object}
 */
org.apache.flex.core.Application.prototype.initialView = null;

/**
 * @expose
 * @type {org.apache.flex.events.EventDispatcher}
 */
org.apache.flex.core.Application.prototype.model = null;

/**
 * @expose
 * @param {org.apache.flex.core.IValuesImpl} value The IValuesImpl.
 */
org.apache.flex.core.Application.prototype.set_valuesImpl =
    function(value) {
  org.apache.flex.core.ValuesManager.valuesImpl = value;
  if (value.init) {
    value.init(this);
  }
};

/**
 * @expose
 */
org.apache.flex.core.Application.prototype.start = function() {
  this.element = document.getElementsByTagName('body')[0];
  this.element.flexjs_wrapper = this;
  this.element.className = 'Application';

  org.apache.flex.utils.MXMLDataInterpreter.generateMXMLInstances(this, null, this.get_MXMLDescriptor());

  this.dispatchEvent('initialize');

  this.initialView.applicationModel = this.model;
  this.addElement(this.initialView);

  this.dispatchEvent('viewChanged');
};

/**
 * @expose
 * @param {Array} data The data for the attributes.
 */
org.apache.flex.core.Application.prototype.generateMXMLAttributes = function(data) {
  org.apache.flex.utils.MXMLDataInterpreter.generateMXMLProperties(this, data);
};

/**
 * @param {Object} c The child element.
 */
org.apache.flex.core.Application.prototype.addElement =
    function(c) {
  this.element.appendChild(c.element);
  c.addedToParent();
};

<|endoftext|>


<commit_before>var memdb = require('memdb')
var tape = require('tape')
var bayes = require('./../')
var q = require('bluebird')

tape('postive / negative', function (t) {
  var nb = bayes(memdb())

  nb.train('positive', 'amazing, awesome movie!! Yeah!! Oh boy.', function (err) {
    t.notOk(err, 'no err')
    nb.train('positive', 'Sweet, this is incredibly, amazing, perfect, great!!', function (err) {
      t.notOk(err, 'no err')
      nb.train('negative', 'terrible, shitty thing. Damn. Sucks!!', function (err) {
        t.notOk(err, 'no err')
        nb.classify('awesome, cool, amazing!! Yay.', function (err, category) {
          t.same(category, 'positive', 'should be positive')
          t.end()
        })
      })
    })
  })
})

tape('spam / not spam', function (t) {
  var nb = bayes(memdb())

  nb.train('spam', 'Great viagra for you!', function (err) {
    t.notOk(err, 'no err')
    nb.train('not spam', 'UTOSC is the best conference ever!', function (err) {
      t.notOk(err, 'no err')
      nb.train('not spam', 'Some more strings that are not spam!', function (err) {
        t.notOk(err, 'no err')
        nb.classify('Great opportunity in Nigeria!', function (err, category) {
          t.same(category, 'spam', 'should be spam')
          t.end()
        })
      })
    })
  })
})

tape('train with promise', function (t) {
  var nb = bayes(memdb())

  nb.trainAsync('positive', 'amazing, awesome movie!! Yeah!! Oh boy.')
    .then(function () {
      return nb.trainAsync('positive', 'Sweet, this is incredibly, amazing, perfect, great!!')
    })
    .then(function () {
      return nb.trainAsync('negative', 'terrible, shitty thing. Damn. Sucks!!');
    })
    .then(function () {
      return nb.classify('awesome, cool, amazing!! Yay.', function (err, category) {
        t.same('positive', category, 'should be positive')
        t.end()
      })
    })
})

tape('que all train promises', function (t) {
  var nb = bayes(memdb())

  var thingsToDo = [
    nb.trainAsync('positive', 'Sweet, this is incredibly, amazing, perfect, great!!'),
    nb.trainAsync('positive', 'amazing, awesome movie!! Yeah!! Oh boy.'),
    nb.trainAsync('negative', 'terrible, shitty thing. Damn. Sucks!!')
  ];

  q.all(thingsToDo).then(function () {
    return nb.classify('awesome, cool, amazing!! Yay.', function (err, category) {
      t.same('positive', category, 'should be positive')
      t.end()
    })
  })
})

tape('classify can be used as promise', function (t) {
  var nb = bayes(memdb())

  var thingsToDo = [
    nb.trainAsync('positive', 'Sweet, this is incredibly, amazing, perfect, great!!'),
    nb.trainAsync('positive', 'amazing, awesome movie!! Yeah!! Oh boy.'),
    nb.trainAsync('negative', 'terrible, shitty thing. Damn. Sucks!!')
  ];

  q.all(thingsToDo)
    .then(function () {
      return nb.classifyAsync('awesome, cool, amazing!! Yay.')
    })
    .then(function (category) {
      t.same('positive', category, 'should be positive')
      t.end()
    })
})
<commit_msg>tests<commit_after>var memdb = require('memdb')
var tape = require('tape')
var bayes = require('./../')
var q = require('bluebird')

tape('postive / negative', function (t) {
  var nb = bayes(memdb())

  nb.train('positive', 'amazing, awesome movie!! Yeah!! Oh boy.', function (err) {
    t.notOk(err, 'no err')
    nb.train('positive', 'Sweet, this is incredibly, amazing, perfect, great!!', function (err) {
      t.notOk(err, 'no err')
      nb.train('negative', 'terrible, shitty thing. Damn. Sucks!!', function (err) {
        t.notOk(err, 'no err')
        nb.classify('awesome, cool, amazing!! Yay.', function (err, category) {
          t.same(category, 'positive', 'should be positive')
          t.end()
        })
      })
    })
  })
})

tape('spam / not spam', function (t) {
  var nb = bayes(memdb())

  nb.train('spam', 'Great viagra for you!', function (err) {
    t.notOk(err, 'no err')
    nb.train('not spam', 'UTOSC is the best conference ever!', function (err) {
      t.notOk(err, 'no err')
      nb.train('not spam', 'Some more strings that are not spam!', function (err) {
        t.notOk(err, 'no err')
        nb.classify('Great opportunity in Nigeria!', function (err, category) {
          t.same(category, 'spam', 'should be spam')
          t.end()
        })
      })
    })
  })
})

tape('train with promise', function (t) {
  var nb = bayes(memdb())

  nb.trainAsync('positive', 'amazing, awesome movie!! Yeah!! Oh boy.')
    .then(function () {
      return nb.trainAsync('positive', 'Sweet, this is incredibly, amazing, perfect, great!!')
    })
    .then(function () {
      return nb.trainAsync('negative', 'terrible, shitty thing. Damn. Sucks!!');
    })
    .then(function () {
      return nb.classify('awesome, cool, amazing!! Yay.', function (err, category) {
        t.same('positive', category, 'should be positive')
        t.end()
      })
    })
})

tape('que all train promises', function (t) {
  var nb = bayes(memdb())

  var thingsToDo = [
    nb.trainAsync('positive', 'Sweet, this is incredibly, amazing, perfect, great!!'),
    nb.trainAsync('positive', 'amazing, awesome movie!! Yeah!! Oh boy.'),
    nb.trainAsync('negative', 'terrible, shitty thing. Damn. Sucks!!')
  ];

  q.all(thingsToDo).then(function () {
    return nb.classify('awesome, cool, amazing!! Yay.', function (err, category) {
      t.same('positive', category, 'should be positive')
      t.end()
    })
  })
})

tape('classify can be used as promise', function (t) {
  var nb = bayes(memdb())

  var thingsToDo = [
    nb.trainAsync('positive', 'Sweet, this is incredibly, amazing, perfect, great!!'),
    nb.trainAsync('positive', 'amazing, awesome movie!! Yeah!! Oh boy.'),
    nb.trainAsync('negative', 'terrible, shitty thing. Damn. Sucks!!')
  ];

  q.all(thingsToDo)
    .then(function () {
      return nb.classifyAsync('awesome, cool, amazing!! Yay.')
    })
    .then(function (category) {
      t.same('positive', category, 'should be positive')
      t.end()
    })
})

tape('classifyLabels with three labels', function (t) {
  var nb = bayes(memdb())

  nb.train('spam', 'Great viagra for you!', function (err) {
    t.notOk(err, 'no err')
    nb.train('not spam', 'UTOSC is the best conference ever!', function (err) {
      t.notOk(err, 'no err')
      nb.train('dont know', 'It might be good opportunity.', function (err) {
        t.notOk(err, 'no err')
        nb.train('not spam', 'Some more strings that are not spam!', function (err) {
          t.notOk(err, 'no err')
          nb.classifyLabels('Great opportunity in Nigeria!', function (err, categories) {
            t.same(categories[0].label, 'spam', 'should be spam')
            t.same(categories[1].label, 'dont know', 'dont know is second guess')
            t.same(categories[2].label, 'not spam', 'last possible guess')
            t.end()
          })
        })
      })
    })
  })
})

tape('classifyLabels with promises', testClasifyLabels)

function testClasifyLabels(t) {
  var nb = bayes(memdb())

  var thingsToDo = [
    nb.trainAsync('positive', 'Sweet, this is incredibly, amazing, perfect, great!!'),
    nb.trainAsync('neutral', 'Additionally, the cost of computing the addition can be avoided in some situations'),
    nb.trainAsync('neutral', 'many applications a multiplication of probabilities'),
    nb.trainAsync('positive', 'amazing, awesome movie!! Yeah!! Oh boy.'),
    nb.trainAsync('negative', 'terrible, shitty thing. Damn. Sucks!!'),
    nb.trainAsync('neutral', 'probabilities in this way has two main advantages')
  ];

  q.all(thingsToDo)
    .then(() => {
      return nb.classifyLabelsAsync('awesome, cool, amazing!! Yay.')
    })
    .then(labels => t.same('positive', labels[0].label, 'should be positive'))
    .then(() => nb.classifyLabelsAsync('probabilities are this gives a lower bound'))
    .then(labels => {
      t.same('neutral', labels[0].label, 'should be neutral')
      t.end()
    })
}<|endoftext|>


<commit_before>/* global
    describe it beforeAll beforeEach afterEach expect
*/

import * as THREE from 'three';
import MeshBVH from '../src/MeshBVH.js';
import { acceleratedRaycast, computeBoundsTree, disposeBoundsTree } from '../src/index.js';

THREE.Mesh.prototype.raycast = acceleratedRaycast;
THREE.BufferGeometry.prototype.computeBoundsTree = computeBoundsTree;
THREE.BufferGeometry.prototype.disposeBoundsTree = disposeBoundsTree;

describe( 'Bounds Tree', () => {

	it( 'should be generated when calling BufferGeometry.computeBoundsTree', () => {

		const geom = new THREE.SphereBufferGeometry( 1, 1, 1 );
		expect( geom.boundsTree ).not.toBeDefined();

		geom.computeBoundsTree();
		expect( geom.boundsTree ).toBeDefined();

	} );

	it( 'should use the boundsTree when raycasting if available', () => {

		const geom = new THREE.SphereBufferGeometry( 1, 1, 1 );
		const mesh = new THREE.Mesh( geom, new THREE.MeshBasicMaterial() );
		const raycaster = new THREE.Raycaster();

		raycaster.ray.origin.set( 0, 0, 10 );
		raycaster.ray.direction.set( 0, 0, - 1 );

		let calledRaycast = false;
		let calledRaycastFirst = false;
		geom.boundsTree = {

			raycast: () => calledRaycast = true,
			raycastFirst: () => calledRaycastFirst = true

		};

		mesh.raycast( raycaster, [] );
		expect( calledRaycast ).toBeTruthy();

		raycaster.firstHitOnly = true;
		mesh.raycast( raycaster, [] );
		expect( calledRaycastFirst ).toBeTruthy();

	} );

} );

describe( 'Options', () => {

	let mesh = null;
	beforeAll( () => {

		const geometry = new THREE.TorusBufferGeometry( 5, 5, 400, 100 );
		mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );

	} );

	describe( 'maxDepth', () => {

		// Returns the max tree depth of the BVH
		function getMaxDepth( node, depth = 0 ) {

			if ( ! node.children ) return depth;

			return node.children.reduce( ( acc, n ) => {

				return Math.max( getMaxDepth( n, depth + 1 ), acc );

			}, depth );

		}

		it( 'should not be limited by default', () => {

			mesh.geometry.computeBoundsTree();

			const depth = getMaxDepth( mesh.geometry.boundsTree );
			expect( depth ).toBeGreaterThan( 10 );

		} );

		it( 'should cap the depth of the bounds tree', () => {

			mesh.geometry.computeBoundsTree( { maxDepth: 10 } );

			const depth = getMaxDepth( mesh.geometry.boundsTree );
			expect( depth ).toEqual( 10 );

		} );

	} );

	describe( 'strategy', () => {

		it.skip( 'should set the split strategy', () => {} );

	} );

	afterEach( () => {

		mesh.geometry.boundsTree = null;

	} );

} );

describe( 'Raycaster', () => {

	let geometry = null;
	let mesh = null;
	let scene = null;
	let raycaster = null;
	beforeEach( () => {

		raycaster = new THREE.Raycaster();
		raycaster.ray.origin.set( 0, 0, - 10 );
		raycaster.ray.direction.set( 0, 0, 1 );

		scene = new THREE.Scene();
		geometry = new THREE.TorusBufferGeometry( 5, 5, 40, 10 );
		mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );

		scene.add( mesh );

		for ( let i = 0; i < 10; i ++ ) {

			scene.add( mesh.clone() );

		}

	} );

	describe( 'firstHitOnly = false', () => {

		beforeEach( () => {

			raycaster.firstHitOnly = false;

		} );

		it( 'should yield all hits on an a mesh without a bounds tree', () => {

			const arr = [];
			mesh.raycast( raycaster, arr );
			expect( arr.length ).toBe( 10 );

		} );

		it( 'should yield all hits on an a mesh with a bounds tree', () => {

			geometry.computeBoundsTree();

			const arr = [];
			mesh.raycast( raycaster, arr );
			expect( arr.length ).toBe( 10 );

		} );

		it( 'should yield all hits in a scene', () => {

			const res = raycaster.intersectObject( scene, true );
			expect( res.length ).toBe( 110 );

		} );

	} );

	describe( 'firstHitOnly = true', () => {

		it( 'should yield closest hit only with a bounds tree', () => {

			const bvh = new MeshBVH( geometry );
			geometry.setIndex( bvh.index );

			raycaster.firstHitOnly = false;
			const allHits = raycaster.intersectObject( mesh, true );

			geometry.boundsTree = bvh;
			raycaster.firstHitOnly = true;
			const bvhHits = raycaster.intersectObject( mesh, true );

			expect( allHits.length ).toEqual( 10 );
			expect( bvhHits.length ).toEqual( 1 );

			expect( bvhHits[ 0 ] ).toEqual( allHits[ 0 ] );

		} );

	} );

} );

describe( 'BoundsTree API', () => {

	it.skip( 'test bounds tree and node apis directly', () => {} );

} );

describe( 'Random intersections comparison', () => {

	let scene = null;
	let raycaster = null;
	let geometry = null;
	let boundsTree = null;
	beforeAll( () => {

		geometry = new THREE.TorusBufferGeometry( 1, 1, 40, 10 );
		geometry.computeBoundsTree();
		boundsTree = geometry.boundsTree;
		geometry.boundsTree = null;

		scene = new THREE.Scene();
		raycaster = new THREE.Raycaster();

		for ( var i = 0; i < 10; i ++ ) {

			let mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );
			mesh.rotation.x = Math.random() * 10;
			mesh.rotation.y = Math.random() * 10;
			mesh.rotation.z = Math.random() * 10;

			mesh.position.x = Math.random() * 1;
			mesh.position.y = Math.random() * 1;
			mesh.position.z = Math.random() * 1;

			scene.add( mesh );
			mesh.updateMatrix( true );
			mesh.updateMatrixWorld( true );

		}

	} );

	for ( let i = 0; i < 100; i ++ ) {

		it( 'cast ' + i, () => {

			raycaster.firstHitOnly = false;
			raycaster.ray.origin.set( Math.random() * 10, Math.random() * 10, Math.random() * 10 );
			raycaster.ray.direction.copy( raycaster.ray.origin ).multiplyScalar( - 1 ).normalize();

			geometry.boundsTree = null;
			const ogHits = raycaster.intersectObject( scene, true );

			geometry.boundsTree = boundsTree;
			const bvhHits = raycaster.intersectObject( scene, true );

			raycaster.firstHitOnly = true;
			const firstHit = raycaster.intersectObject( scene, true );

			expect( ogHits ).toEqual( bvhHits );
			expect( firstHit[ 0 ] ).toEqual( ogHits[ 0 ] );

		} );

	}

} );
<commit_msg>Add test for maxDepth raycasting<commit_after>/* global
    describe it beforeAll beforeEach afterEach expect
*/

import * as THREE from 'three';
import MeshBVH from '../src/MeshBVH.js';
import { acceleratedRaycast, computeBoundsTree, disposeBoundsTree } from '../src/index.js';

THREE.Mesh.prototype.raycast = acceleratedRaycast;
THREE.BufferGeometry.prototype.computeBoundsTree = computeBoundsTree;
THREE.BufferGeometry.prototype.disposeBoundsTree = disposeBoundsTree;

describe( 'Bounds Tree', () => {

	it( 'should be generated when calling BufferGeometry.computeBoundsTree', () => {

		const geom = new THREE.SphereBufferGeometry( 1, 1, 1 );
		expect( geom.boundsTree ).not.toBeDefined();

		geom.computeBoundsTree();
		expect( geom.boundsTree ).toBeDefined();

	} );

	it( 'should use the boundsTree when raycasting if available', () => {

		const geom = new THREE.SphereBufferGeometry( 1, 1, 1 );
		const mesh = new THREE.Mesh( geom, new THREE.MeshBasicMaterial() );
		const raycaster = new THREE.Raycaster();

		raycaster.ray.origin.set( 0, 0, 10 );
		raycaster.ray.direction.set( 0, 0, - 1 );

		let calledRaycast = false;
		let calledRaycastFirst = false;
		geom.boundsTree = {

			raycast: () => calledRaycast = true,
			raycastFirst: () => calledRaycastFirst = true

		};

		mesh.raycast( raycaster, [] );
		expect( calledRaycast ).toBeTruthy();

		raycaster.firstHitOnly = true;
		mesh.raycast( raycaster, [] );
		expect( calledRaycastFirst ).toBeTruthy();

	} );

} );

describe( 'Options', () => {

	let mesh = null;
	beforeAll( () => {

		const geometry = new THREE.TorusBufferGeometry( 5, 5, 400, 100 );
		mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );

	} );

	describe( 'maxDepth', () => {

		// Returns the max tree depth of the BVH
		function getMaxDepth( node, depth = 0 ) {

			if ( ! node.children ) return depth;

			return node.children.reduce( ( acc, n ) => {

				return Math.max( getMaxDepth( n, depth + 1 ), acc );

			}, depth );

		}

		it( 'should not be limited by default', () => {

			mesh.geometry.computeBoundsTree();

			const depth = getMaxDepth( mesh.geometry.boundsTree );
			expect( depth ).toBeGreaterThan( 10 );

		} );

		it( 'should cap the depth of the bounds tree', () => {

			mesh.geometry.computeBoundsTree( { maxDepth: 10 } );

			const depth = getMaxDepth( mesh.geometry.boundsTree );
			expect( depth ).toEqual( 10 );

		} );

		it.only( 'successfully raycast', () => {

			const raycaster = new THREE.Raycaster();
			raycaster.ray.origin.set( 0, 0, 10 );
			raycaster.ray.direction.copy( raycaster.ray.origin ).multiplyScalar( - 1 );

			const ogHits = raycaster.intersectObject( mesh, [] );

			mesh.geometry.computeBoundsTree( { maxDepth: 3 } );
			const bvhHits = raycaster.intersectObject( mesh, [] );

			raycaster.raycastFirst = true;
			const firstHit = raycaster.intersectObject( mesh, [] );

			expect( ogHits ).toEqual( bvhHits );
			expect( firstHit[ 0 ] ).toEqual( ogHits[ 0 ] );

		} );

	} );

	describe( 'strategy', () => {

		it.skip( 'should set the split strategy', () => {} );

	} );

	afterEach( () => {

		mesh.geometry.boundsTree = null;

	} );

} );

describe( 'Raycaster', () => {

	let geometry = null;
	let mesh = null;
	let scene = null;
	let raycaster = null;
	beforeEach( () => {

		raycaster = new THREE.Raycaster();
		raycaster.ray.origin.set( 0, 0, - 10 );
		raycaster.ray.direction.set( 0, 0, 1 );

		scene = new THREE.Scene();
		geometry = new THREE.TorusBufferGeometry( 5, 5, 40, 10 );
		mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );

		scene.add( mesh );

		for ( let i = 0; i < 10; i ++ ) {

			scene.add( mesh.clone() );

		}

	} );

	describe( 'firstHitOnly = false', () => {

		beforeEach( () => {

			raycaster.firstHitOnly = false;

		} );

		it( 'should yield all hits on an a mesh without a bounds tree', () => {

			const arr = [];
			mesh.raycast( raycaster, arr );
			expect( arr.length ).toBe( 10 );

		} );

		it( 'should yield all hits on an a mesh with a bounds tree', () => {

			geometry.computeBoundsTree();

			const arr = [];
			mesh.raycast( raycaster, arr );
			expect( arr.length ).toBe( 10 );

		} );

		it( 'should yield all hits in a scene', () => {

			const res = raycaster.intersectObject( scene, true );
			expect( res.length ).toBe( 110 );

		} );

	} );

	describe( 'firstHitOnly = true', () => {

		it( 'should yield closest hit only with a bounds tree', () => {

			const bvh = new MeshBVH( geometry );
			geometry.setIndex( bvh.index );

			raycaster.firstHitOnly = false;
			const allHits = raycaster.intersectObject( mesh, true );

			geometry.boundsTree = bvh;
			raycaster.firstHitOnly = true;
			const bvhHits = raycaster.intersectObject( mesh, true );

			expect( allHits.length ).toEqual( 10 );
			expect( bvhHits.length ).toEqual( 1 );

			expect( bvhHits[ 0 ] ).toEqual( allHits[ 0 ] );

		} );

	} );

} );

describe( 'BoundsTree API', () => {

	it.skip( 'test bounds tree and node apis directly', () => {} );

} );

describe( 'Random intersections comparison', () => {

	let scene = null;
	let raycaster = null;
	let geometry = null;
	let boundsTree = null;
	beforeAll( () => {

		geometry = new THREE.TorusBufferGeometry( 1, 1, 40, 10 );
		geometry.computeBoundsTree();
		boundsTree = geometry.boundsTree;
		geometry.boundsTree = null;

		scene = new THREE.Scene();
		raycaster = new THREE.Raycaster();

		for ( var i = 0; i < 10; i ++ ) {

			let mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );
			mesh.rotation.x = Math.random() * 10;
			mesh.rotation.y = Math.random() * 10;
			mesh.rotation.z = Math.random() * 10;

			mesh.position.x = Math.random() * 1;
			mesh.position.y = Math.random() * 1;
			mesh.position.z = Math.random() * 1;

			scene.add( mesh );
			mesh.updateMatrix( true );
			mesh.updateMatrixWorld( true );

		}

	} );

	for ( let i = 0; i < 100; i ++ ) {

		it( 'cast ' + i, () => {

			raycaster.firstHitOnly = false;
			raycaster.ray.origin.set( Math.random() * 10, Math.random() * 10, Math.random() * 10 );
			raycaster.ray.direction.copy( raycaster.ray.origin ).multiplyScalar( - 1 ).normalize();

			geometry.boundsTree = null;
			const ogHits = raycaster.intersectObject( scene, true );

			geometry.boundsTree = boundsTree;
			const bvhHits = raycaster.intersectObject( scene, true );

			raycaster.firstHitOnly = true;
			const firstHit = raycaster.intersectObject( scene, true );

			expect( ogHits ).toEqual( bvhHits );
			expect( firstHit[ 0 ] ).toEqual( ogHits[ 0 ] );

		} );

	}

} );
<|endoftext|>


<commit_before>'use strict';

var htmlreplace = require('../lib/index');
var gutil = require('gulp-util');
var fs = require('fs');
var path = require('path');
var should = require('should');

function getFile(file_path) {
    return new gutil.File({
        path: file_path,
        base: path.dirname(file_path),
        contents: fs.readFileSync(file_path)
    });
}

function getFixture(name) {
    return getFile(path.join('test', 'fixtures', name));
}

function getExpected(name) {
    return getFile(path.join('test', 'expected', name));
}

function compare(name, stream, done) {
    stream.on('data', function (new_file) {
        if (path.basename(new_file.path) === name) {
            should(getExpected(name).contents.toString()).eql(new_file.contents.toString());
        }
    });

    stream.on('end', function () {
        done();
    });

    stream.write(getFixture(name));
    stream.end();
}

describe('gulp-html-replace', function () {
    it('should pass file through', function (done) {
        var a = 0;

        var fake_file = new gutil.File({
            path: './test/fixtures/file.js',
            cwd: './test/',
            base: './test/fixtures/',
            contents: new Buffer('wadup();')
        });

        var stream = htmlreplace();

        stream.on('data', function (newFile) {
            should.exist(newFile);
            should.exist(newFile.path);
            should.exist(newFile.relative);
            should.exist(newFile.contents);
            newFile.path.should.equal('./test/fixtures/file.js');
            newFile.relative.should.equal('file.js');
            ++a;
        });

        stream.once('end', function () {
            a.should.equal(1);
            done();
        });

        stream.write(fake_file);
        stream.end();
    });

    it('should work with single task name and single file', function (done) {
        var stream = htmlreplace('css', '/css/combined.css');
        compare('01.html', stream, done);
    });

    it('should work with single task name and multiple files', function (done) {
        var stream = htmlreplace('js', ['hero.js', 'monster.js']);
        compare('02.html', stream, done);
    });

    it('should work with multiple task names, multiple AND single files', function (done) {
        var stream = htmlreplace({
            'css': ['css/normalize.css', 'css/main.css'],
            'js': 'js/bundle.js'
        });
        compare('03.html', stream, done);
    });

    it('should remove blocks with orphaned names', function (done) {
        var stream = htmlreplace('css', 'css/main.css');
        compare('04.html', stream, done);
    });

    it('should keep the indentation', function (done) {
        var stream = htmlreplace({
            'css': 'style.css',
            'js': 'main.js'
        });
        compare('05.html', stream, done);
    });

    it('should accept hyphen', function (done) {
        var stream = htmlreplace({
            'css-hyphen': 'style.css',
            'js-with-three-hyphens': 'main.js'
        });
        compare('06.html', stream, done);
    });

    it('should work with custom templates', function (done) {
        var stream = htmlreplace({
            'css-template': {
                'files': 'style.min.css',
                'tpl': '<link href="%s" rel="stylesheet">'
            },
            'js-template': {
                'files': 'bundle.min.js',
                'tpl': '<script src="%s" async="true" />'
            }
        });
        compare('07.html', stream, done);
    });
});<commit_msg>fixed test<commit_after>'use strict';

var htmlreplace = require('../lib/index');
var gutil = require('gulp-util');
var fs = require('fs');
var path = require('path');
var should = require('should');

function getFile(file_path) {
    return new gutil.File({
        path: file_path,
        base: path.dirname(file_path),
        contents: fs.readFileSync(file_path)
    });
}

function getFixture(name) {
    return getFile(path.join('test', 'fixtures', name));
}

function getExpected(name) {
    return getFile(path.join('test', 'expected', name));
}

function compare(name, stream, done) {
    stream.on('data', function (new_file) {
        if (path.basename(new_file.path) === name) {
            should(getExpected(name).contents.toString()).eql(new_file.contents.toString());
        }
    });

    stream.on('end', function () {
        done();
    });

    stream.write(getFixture(name));
    stream.end();
}

describe('gulp-html-replace', function () {
    it('should pass file through', function (done) {
        var a = 0;

        var fake_file = new gutil.File({
            path: './test/fixtures/file.js',
            cwd: './test/',
            base: './test/fixtures/',
            contents: new Buffer('wadup();')
        });

        var stream = htmlreplace();

        stream.on('data', function (newFile) {
            should.exist(newFile);
            should.exist(newFile.path);
            should.exist(newFile.relative);
            should.exist(newFile.contents);
            newFile.path.should.equal('./test/fixtures/file.js');
            newFile.relative.should.equal('file.js');
            ++a;
        });

        stream.once('end', function () {
            a.should.equal(1);
            done();
        });

        stream.write(fake_file);
        stream.end();
    });

    it('should work with single task name and single file', function (done) {
        var stream = htmlreplace('css', '/css/combined.css');
        compare('01.html', stream, done);
    });

    it('should work with single task name and multiple files', function (done) {
        var stream = htmlreplace('js', ['hero.js', 'monster.js']);
        compare('02.html', stream, done);
    });

    it('should work with multiple task names, multiple AND single files', function (done) {
        var stream = htmlreplace({
            'css': ['css/normalize.css', 'css/main.css'],
            'js': 'js/bundle.js'
        });
        compare('03.html', stream, done);
    });

    it('should remove blocks with orphaned names', function (done) {
        var stream = htmlreplace('css', 'css/main.css');
        compare('04.html', stream, done);
    });

    it('should keep the indentation', function (done) {
        var stream = htmlreplace({
            'css': 'style.css',
            'js': 'main.js'
        });
        compare('05.html', stream, done);
    });

    it('should accept hyphen', function (done) {
        var stream = htmlreplace({
            'css-hyphen': 'style.css',
            'js-with-three-hyphens': 'main.js'
        });
        compare('06.html', stream, done);
    });

    it('should work with custom templates', function (done) {
        var stream = htmlreplace({
            'css-template': {
                'files': 'style.min.css',
                'tpl': '<link href="%s" rel="stylesheet">'
            },
            'js-template': {
                'files': 'bundle.min.js',
                'tpl': '<script src="%s" async="true"/>'
            }
        });
        compare('07.html', stream, done);
    });
});<|endoftext|>


<commit_before>'use strict';

var assert = require( 'assert' );
var randMod = require( '../lib/index.js' );

var toyRandFunc = randMod.makeRandWithAM(3,31,9);
var toyRandList = randMod.genRandList( 30, toyRandFunc );
var toyRandExpectedList =
	[27,19,26,16,17,20,29,25,13,8,24,10,30,28,22,
	4,12,5,15,14,11,2,6,18,23,7,21,1,3,9];

var randFunc = randMod.makeRand(1);
var randList = randMod.genRandList(10000, randFunc);
randList.reverse();
var randList16 = randList.slice(0,16);

var expectedResult = [1043618065,
1484786315, 925166085, 1614852353, 721631166,
173942219, 1229443779, 789328014, 570809709,
1760109362, 270600523, 2108528931, 16480421,
519782231, 162430624, 372212905];

//var i;
//for( i = 0; i < 16; i++) {
//	console.log( i + ') ' + randList[ i ] );
//}
//console.log(randList16);

// console.log('toyRandList = ' + toyRandList);
// console.log('toyRandExpectedList = ' + toyRandExpectedList);

//assert.deepEqual(randList16, expectedResult);

describe( 'htfrand', function() {
	describe( 'randList16 test', function() {
		it( 'should be equal to expectedResult', function() {
			assert.deepEqual(randList16, expectedResult);
		});
	});
	describe('toyRandList test', function() {
		it( 'should be equal to toyRandExpectedList', function() {
			assert.deepEqual( toyRandList, toyRandExpectedList );
		});
	});
});

// MODULES //

//var // Expectation library:
//	chai = require( 'chai' ),

	// Module to be tested:
//	lib = require( './../lib' );

// VARIABLES //

//var expect = chai.expect,
//	assert = chai.assert;

// TESTS //

/*
describe( 'compute-htfrand', function tests() {

	it( 'should export a function', function test() {
		expect( lib ).to.be.a( 'function' );
	});

	it( 'should do something' );

});
*/

<commit_msg>Add tests for Bays-Durham shuffle.  Add basis for further tests.  TODO: running tests is ugly right now and need to clean up.<commit_after>'use strict';

var assert = require( 'assert' );
var randMod = require( '../lib/index.js' );

var toyRandFunc = randMod.makeRandWithAM(3,31,9);
var toyRandList = randMod.genRandList( 30, toyRandFunc );
var toyRandExpectedList =
	[27,19,26,16,17,20,29,25,13,8,24,10,30,28,22,
	4,12,5,15,14,11,2,6,18,23,7,21,1,3,9];

var htfRandFunc = randMod.makeHtfRand( 1 );
var randList = randMod.genRandList( 10000, htfRandFunc );

// START Temp code
var itemp;
var Ntemp = 33;
for(itemp = 0; itemp < Ntemp; itemp++) {
	console.log( randList[ itemp ] );
}

var randFunc2d = randMod.makeHtfRand( 1 );
var shuffRand = randMod.mkHtfShuff( randFunc2d );

console.log( "first call to shuffRand = " + shuffRand() );

// END Temp code

randList.reverse();
var randList16 = randList.slice(0,16);

var expectedResult = [1043618065,
1484786315, 925166085, 1614852353, 721631166,
173942219, 1229443779, 789328014, 570809709,
1760109362, 270600523, 2108528931, 16480421,
519782231, 162430624, 372212905];

var Ktoy = 8;
var shuffTabToy = new Array( Ktoy );
var itoy;
var htfShuffToy;

// Make another toyRandFun
var toyRandFunc2 = randMod.makeRandWithAM(3,31,9);

for(itoy = 0; itoy < Ktoy; itoy++) {
	shuffTabToy[ itoy ] = toyRandFunc2();
}

htfShuffToy = randMod.mkHtfShuffWithK(toyRandFunc2, shuffTabToy, Ktoy);

describe( 'htfrand module tests', function() {
	describe( 'randList16 test', function() {
		it( 'should be equal to expectedResult', function() {
			assert.deepEqual(randList16, expectedResult);
		});
	});
	describe('toyRandList test', function() {
		it( 'should be equal to toyRandExpectedList', function() {
			assert.deepEqual( toyRandList, toyRandExpectedList );
		});
	});
	describe('htfShuffToy test', function() {
		it( 'should be equal to 29', function() {
			assert.equal( htfShuffToy(), 29 );
		});
		it( 'should be equal to 19', function() {
			assert.equal( htfShuffToy(), 19 );
		});
		it( 'should be equal to 8', function() {
			assert.equal( htfShuffToy(), 8 );
		});
		it( 'should be equal to 16', function() {
			assert.equal( htfShuffToy(), 16 );
		});
		it( 'should be equal to 25', function() {
			assert.equal( htfShuffToy(), 25 );
		});
		it( 'should be equal to 20', function() {
			assert.equal( htfShuffToy(), 20 );
		});
	});
});

// MODULES //

//var // Expectation library:
//	chai = require( 'chai' ),

	// Module to be tested:
//	lib = require( './../lib' );

// VARIABLES //

//var expect = chai.expect,
//	assert = chai.assert;

// TESTS //

/*
describe( 'compute-htfrand', function tests() {

	it( 'should export a function', function test() {
		expect( lib ).to.be.a( 'function' );
	});

	it( 'should do something' );

});
*/

<|endoftext|>


<commit_before>var assert = require('assert');
var WebCrypto = require("../src/webcrypto.js").default;
var config = require("./config.js")

describe("test", function () {
    var webcrypto;

    before(function () {
    })

    after(function () {
    })

    it("generate RSA PKCS1 1.5", function () {
		webcrypto = new WebCrypto(config);

		webcrypto.subtle.generateKey({
            name:"RSASSA-PKCS1-v1_5",
            modulusLength: 1024,
            publicExponent: new Uint8Array([1, 0, 1]),
            hash: {
                name: "SHA-1"
            }},
            false,
            ["sign", "verify"]
        )
        .then(function(k){
            console.log(k);
        })
        .catch(function(e){
            console.error('Error:', e.message, e.stack);
        })
    })
})<commit_msg>Change test<commit_after>var assert = require('assert');
var WebCrypto = require("../src/webcrypto.js").default;
var config = require("./config.js")

describe("test", function () {
    var webcrypto;

    before(function () {
    })

    after(function () {
    })

    it("generate RSA PKCS1 1.5", function (done) {
		webcrypto = new WebCrypto(config);

		webcrypto.subtle.generateKey({
            name:"RSASSA-PKCS1-v1_5",
            modulusLength: 1024,
            publicExponent: new Uint8Array([1, 0, 1]),
            hash: {
                name: "SHA-1"
            }},
            false,
            ["sign", "verify"]
        )
        .then(function(k){
            assert.equal(k.privateKey !== null, true, "Has no private key");
            assert.equal(k.publicKey !== null, true, "Has no public key");
        })
        .then(done, done);
    })
})<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import _ from 'lodash';

export const SEE_AS_READER_SEARCH = [
  '+reading +books',
  'readaloud',
  'story',
  'stories',
  'motivated',
  'identity'
  // not 'engagement', other social, behavioral, etc?
];
export const ORAL_LANGUAGE_SEARCH = [
  '+oral +language',
  '+expressive +language',
  '+receptive +language',
  '+verbal +comprehension',
  'vocabulary',
  'listening',
  'prepositions',
  '+wh +questions',
  '+speech +language',
  '+speech +therapy',
  '+speech +language +evaluation',
  '+Primary +Disability +Communication'
];
export const ENGLISH_SEARCH = [
  'WIDA',
  '+ACCESS +level',
  '+English +proficiency'
];
export const SOUNDS_IN_WORDS_SEARCH = [
  'phonological',
  'phonemic',
  'phoneme',
  'PSF',
  '+phonemic +segmentation +fluency',
  'FSF',
  '+first +sound +fluency',
  'segment',
  'blend',
  'delete',
  '+phoneme +substitution',
  '+sound +substitution'
];
export const SOUNDS_AND_LETTERS_SEARCH = [
  '+reading -books',
  '+reading +intervention',
  'correspondence', // 1-1
  'letter -attendance -tardy', // not "attendance letter"
  '-sent letter', // "sent a letter"
  '+letter +sounds',
  '+Lively +Letters',
  'LNF',
  '+letter +naming +fluency',
  'NWF',
  '+nonsense +word +fluency',
  'ORF',
  'DORF',
  '+oral +reading +fluency',
  'phonics',
  'decoding',
  'orthography',
  'spelling'
];

// highlighting a search result, using lunr position data
export function Highlight(props) {
  const {text, start, length, onlyMatches} = props;
  const highlight = text.slice(start, start + length);
  const beforeIndex = Math.max(start - 30, 0);
  const beforeContext = text.slice(beforeIndex, start);
  const afterIndex = Math.min(start + 30, text.length);
  const afterContext = text.slice(start + length, afterIndex);

  const matchEl = {highlight};
  if (onlyMatches) return matchEl;

  return ...{beforeContext}{matchEl}{afterContext}...;
}
Highlight.propTypes = {
  text: PropTypes.string.isRequired,
  start: PropTypes.number.isRequired,
  length: PropTypes.number.isRequired,
  onlyMatches: PropTypes.bool
};

// unroll all the words matched across all the search buckets
// agnostic to the rest of the results
export function unrollAndSortPositions(searchResults) {
  const positions = _.flatMap(searchResults, result => {
    return _.flatMap(_.values(result.matchData.metadata), meta => meta.text.position);
  });
  return _.sortBy(_.uniqWith(positions, _.isEqual), position => position[0]);
}<commit_msg>Adjust text search terms<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import _ from 'lodash';

export const SEE_AS_READER_SEARCH = [
  '+reading +books',
  'readaloud',
  'story',
  'stories',
  'motivated',
  'identity'
  // not 'engagement', other social, behavioral, etc?
];
export const ORAL_LANGUAGE_SEARCH = [
  '+oral +language',
  '+expressive +language',
  '+receptive +language',
  '+verbal +comprehension',
  'CELF',
  'vocabulary',
  'listening',
  'prepositions',
  '+wh +questions',
  '+speech +language',
  '+speech +therapy',
  'SLP',
  '+speech +language +evaluation',
  '+Primary +Disability +Communication'
];
export const ENGLISH_SEARCH = [
  'WIDA',
  '+English +proficiency'
];
export const SOUNDS_IN_WORDS_SEARCH = [
  'phonological',
  'phonemic',
  'phoneme',
  'PSF',
  '+phonemic +segmentation +fluency',
  'FSF',
  '+first +sound +fluency',
  'segment',
  'blend',
  'delete'
];
export const SOUNDS_AND_LETTERS_SEARCH = [
  '+reading -books',
  '+reading +intervention',
  'correspondence', // 1-1
  'letter -attendance -tardy', // not "attendance letter"
  '-sent letter', // "sent a letter"
  '+letter +sounds',
  '+Lively +Letters',
  'LNF',
  '+letter +naming +fluency',
  'NWF',
  '+nonsense +word +fluency',
  'ORF',
  'DORF',
  '+oral +reading +fluency',
  'phonics',
  'decoding',
  'orthography',
  'spelling'
];

// highlighting a search result, using lunr position data
export function Highlight(props) {
  const {text, start, length, onlyMatches} = props;
  const highlight = text.slice(start, start + length);
  const beforeIndex = Math.max(start - 30, 0);
  const beforeContext = text.slice(beforeIndex, start);
  const afterIndex = Math.min(start + 30, text.length);
  const afterContext = text.slice(start + length, afterIndex);

  const matchEl = {highlight};
  if (onlyMatches) return matchEl;

  return ...{beforeContext}{matchEl}{afterContext}...;
}
Highlight.propTypes = {
  text: PropTypes.string.isRequired,
  start: PropTypes.number.isRequired,
  length: PropTypes.number.isRequired,
  onlyMatches: PropTypes.bool
};

// unroll all the words matched across all the search buckets
// agnostic to the rest of the results
export function unrollAndSortPositions(searchResults) {
  const positions = _.flatMap(searchResults, result => {
    return _.flatMap(_.values(result.matchData.metadata), meta => meta.text.position);
  });
  return _.sortBy(_.uniqWith(positions, _.isEqual), position => position[0]);
}<|endoftext|>


<commit_before>const Nightmare = require('nightmare');
const assert = require('assert');
const fs = require('fs');
const path = require('path');
const test_url = "file:///"+path.resolve(__dirname,"../examples/vanilla.html");
const hash_url = test_url + "#group=nogroup&photo=rhinoceros";

const nightmare = Nightmare({
    webPreferences  : {
    partition : 'nopersist',
    preload: path.resolve(__dirname,'./preload.js')
  },
  show: true
});

describe('test',() => {
  it('caption', (done) => {
    nightmare.goto(test_url)
      .click('[data-caption="lion"]')
      .wait(1000)
      .click('.smartphoto-arrow-right a')
      .wait(1000)
      .evaluate(() => {
        return document.querySelector('.smartphoto-caption').innerText;
      })
      .then((result) => {
        assert.equal(result,'camel');
        done();
      })
      .catch((error) => {
        done(error);
      });
  });

  it('hash', (done) => {
    nightmare.goto(hash_url)
      .wait(1000)
      .evaluate(() => {
          return document.querySelector('.smartphoto-caption').innerText;
      })
      .then(result => {
        assert.equal(result,'rhinoceros');
        done();
      })
      .catch(error => {
        done(error);
      });
  });
});<commit_msg>Fix data-caption text<commit_after>const Nightmare = require('nightmare');
const assert = require('assert');
const fs = require('fs');
const path = require('path');
const test_url = "file:///"+path.resolve(__dirname,"../examples/vanilla.html");
const hash_url = test_url + "#group=nogroup&photo=rhino";

const nightmare = Nightmare({
    webPreferences  : {
    partition : 'nopersist',
    preload: path.resolve(__dirname,'./preload.js')
  },
  show: true
});

describe('test',() => {
  it('caption', (done) => {
    nightmare.goto(test_url)
      .click('[data-caption="Lion"]')
      .wait(1000)
      .click('.smartphoto-arrow-right a')
      .wait(1000)
      .evaluate(() => {
        return document.querySelector('.smartphoto-caption').innerText;
      })
      .then((result) => {
        assert.equal(result,'Camel');
        done();
      })
      .catch((error) => {
        done(error);
      });
  });

  it('hash', (done) => {
    nightmare.goto(hash_url)
      .wait(1000)
      .evaluate(() => {
          return document.querySelector('.smartphoto-caption').innerText;
      })
      .then(result => {
        assert.equal(result,'Rhino');
        done();
      })
      .catch(error => {
        done(error);
      });
  });
});
<|endoftext|>


<commit_before>/**
 * @header updoc
 * @description the flexible javascript documentation generator
 */

/**
 * @module 1info
 * @header About
 * @description
 *

 * updoc doesn't tell you what to document about your code. You
 * just specify whatever properties you care about, then updoc generates
 * nice-looking documentation for it.
 *

 *

 * It's suitable both for internal developer documentation and external
 * api documentation.
 *

 */

/**
 * @module 2features
 * @header Features
 * @flexible so you can use whatever properties you want
 * @aware of function and var names
 * @code is organized by modules
 * @templates are easy to create and modify
 * @html allowed in comments
 * @json output if you want it
 */

/**
 * @module 3example
 * @header Example
 * @demo example.js creates
 * example.html
 * @bonus this site was created by this file
 */

/**
 * @module 4download
 * @header Download
 * @description on github
 */

/**
 * @module 5using
 * @header Using updoc
 * @description Install updoc like this:
 * sudo npm install updoc -g
 * Use updoc like this:
 * updoc input.js output.html
 * An optional 3rd argument specifies the template.
 */

/**
 * not documented
 * @module 6rules
 * @header Rules
 * @start updoc comments with /** on new line
 * @close updoc comments with */ on new line
 * @leading *s are stripped
 * @@ indicates a property (escape with &#64;)
 * @lines following a property
 * are included in that property
 * @text before any properties is not documented
 */

/**
 * @module 7modules
 * @header Modules
 * @description updoc organizes your documentation by modules. Each comment
 * block can have a @module property. It looks like this:
 * @module app.util.foobar
 * The function or var name is added to the end of the module if appropriate.
 * Code of this form has its module set automatically:
 * foo.bar.bat = function() {} // my module is foo.bar.bat
 * Sections are nested by
 * the module's depth and sorted by name. The sort order follows:
 *

 *
alphabetical by module

 *
alphabetical by name (for functions and vars)

 *
order of appearance in source

 *

 * If the module property is omitted and isn't detected it is a top-level
 * section.
 */

/**
 * @module 8templates
 * @header Templates
 * @description
 *

 * Templates consume a json file. This json file is just the
 * properties provided in the updoc comments, with a few bonus properties.
 *

{
 version: '0.0.1', // updoc version
 sections: [ // each updoc comment is a section
  {
    name: 'foo' // var name or function name. may be absent
    type: 'function', // function or var or other
    prop: 'val', // @prop val
    module: 'example.util.foo', // @module example.util
    depth: 3 // module depth. @module foo.bar.bat is depth 3
  }
 ]
}
 *

 * No other properties are special, but the template can decide to make them
 * special. For example, the default template has special formatting for
 * @header and @description. These are not treated specially by
 * the updoc code itself.
 *

 *

 * updoc currently uses
 * underscore
 * templates.
 *

 *

 * You can view the raw json output by specifying "json" as the output file
 *

 */

/**
 * @module 90highlighting
 * @header Highlighting
 * @description
 * The default template uses
 * prettify.
 * To get code highlighting, just put prettify.js and prettify.css in the same
 * directory as your output. Then put code in a code element like this:
 * <code>function() {}</code>
 *

 */

/**
 * @module 91footer
 * @description Created by Greg Smith
 * at Bocoup
 */<commit_msg>fix to site<commit_after>/**
 * @header updoc
 * @description the flexible javascript documentation generator
 */

/**
 * @module 1info
 * @header About
 * @description
 *

 * updoc doesn't tell you what to document about your code. You
 * just specify whatever properties you care about, then updoc generates
 * nice-looking documentation for it.
 *

 *

 * It's suitable both for internal developer documentation and external
 * api documentation.
 *

 */

/**
 * @module 2features
 * @header Features
 * @flexible so you can use whatever properties you want
 * @aware of function and var names
 * @code is organized by modules
 * @templates are easy to create and modify
 * @html allowed in comments
 * @json output if you want it
 */

/**
 * @module 3example
 * @header Example
 * @demo example.js creates
 * example.html
 * @bonus this site was created by this file
 */

/**
 * @module 4contribute
 * @header Contribute
 * @description on github
 */

/**
 * @module 5using
 * @header Using updoc
 * @description Install updoc like this:
 * sudo npm install updoc -g
 * Use updoc like this:
 * updoc input.js output.html
 * An optional 3rd argument specifies the template.
 */

/**
 * not documented
 * @module 6rules
 * @header Rules
 * @start updoc comments with /** on new line
 * @close updoc comments with */ on new line
 * @leading *s are stripped
 * @@ indicates a property (escape with &#64;)
 * @lines following a property
 * are included in that property
 * @text before any properties is not documented
 */

/**
 * @module 7modules
 * @header Modules
 * @description updoc organizes your documentation by modules. Each comment
 * block can have a @module property. It looks like this:
 * @module app.util.foobar
 * The function or var name is added to the end of the module if appropriate.
 * Code of this form has its module set automatically:
 * foo.bar.bat = function() {} // my module is foo.bar.bat
 * Sections are nested by
 * the module's depth and sorted by name. The sort order follows:
 *

 *
alphabetical by module

 *
alphabetical by name (for functions and vars)

 *
order of appearance in source

 *

 * If the module property is omitted and isn't detected it is a top-level
 * section.
 */

/**
 * @module 8templates
 * @header Templates
 * @description
 *

 * Templates consume a json file. This json file is just the
 * properties provided in the updoc comments, with a few bonus properties.
 *

{
 version: '0.0.1', // updoc version
 sections: [ // each updoc comment is a section
  {
    name: 'foo' // var name or function name. may be absent
    type: 'function', // function or var or other
    prop: 'val', // @prop val
    module: 'example.util.foo', // @module example.util
    depth: 3 // module depth. @module foo.bar.bat is depth 3
  }
 ]
}
 *

 * No other properties are special, but the template can decide to make them
 * special. For example, the default template has special formatting for
 * @header and @description. These are not treated specially by
 * the updoc code itself.
 *

 *

 * updoc currently uses
 * underscore
 * templates.
 *

 *

 * You can view the raw json output by specifying "json" as the output file
 *

 */

/**
 * @module 90highlighting
 * @header Highlighting
 * @description
 * The default template uses
 * prettify.
 * To get code highlighting, just put prettify.js and prettify.css in the same
 * directory as your output. Then put code in a code element like this:
 * <code>function() {}</code>
 *

 */

/**
 * @module 91footer
 * @description Created by Greg Smith
 * at Bocoup
 */<|endoftext|>


<commit_before>var path = require( 'path' );
var fs = require( 'fs' );
var rimraf = require( 'rimraf' );
var child_process = require( 'child_process' );
var assert = require( 'assert' );
var glob = require( 'glob' );
var SourceMapConsumer = require( 'source-map' ).SourceMapConsumer;
var getLocation = require( './utils/getLocation.js' );
var buble = require( '../dist/buble.umd.js' );

require( 'source-map-support' ).install();
require( 'console-group' ).install();

function equal ( a, b ) {
	assert.equal( showInvisibles( a ), showInvisibles( b ) );
}

function showInvisibles ( str ) {
	return str
		.replace( /^ +/gm, spaces => repeat( '•', spaces.length ) )
		.replace( / +$/gm, spaces => repeat( '•', spaces.length ) )
		.replace( /^\t+/gm, tabs => repeat( '›   ', tabs.length ) )
		.replace( /\t+$/gm, tabs => repeat( '›   ', tabs.length ) );
}

function repeat ( str, times ) {
	var result = '';
	while ( times-- ) result += str;
	return result;
}

describe( 'buble', () => {
	fs.readdirSync( 'test/samples' ).forEach( file => {
		var samples = require( './samples/' + file );

		describe( path.basename( file ), () => {
			samples.forEach( sample => {
				( sample.solo ? it.only : sample.skip ? it.skip : it )( sample.description, () => {
					if ( sample.error ) {
						assert.throws( () => {
							buble.transform( sample.input, sample.options );
						}, sample.error );
					}

					else {
						equal( buble.transform( sample.input, sample.options  ).code, sample.output );
					}
				});
			});
		});
	});

	describe( 'cli', () => {
		fs.readdirSync( 'test/cli' ).forEach( dir => {
			if ( dir[0] === '.' ) return; // .DS_Store

			it( dir, done => {
				dir = path.resolve( 'test/cli', dir );
				rimraf.sync( path.resolve( dir, 'actual' ) );
				fs.mkdirSync( path.resolve( dir, 'actual' ) );

				var binFile = path.resolve(__dirname, '../bin/buble');
				var commandFile = path.resolve( dir, 'command.sh' );

				var command = fs.readFileSync( commandFile, 'utf-8' )
					.replace( 'buble', 'node ' + binFile );
				child_process.exec( command, {
					cwd: dir
				}, ( err, stdout, stderr ) => {
					if ( err ) return done( err );

					if ( stdout ) console.log( stdout );
					if ( stderr ) console.error( stderr );

					function catalogue ( subdir ) {
						subdir = path.resolve( dir, subdir );

						return glob.sync( '**/*.js?(.map)', { cwd: subdir })
							.sort()
							.map( name => {
								var contents = fs.readFileSync( path.resolve( subdir, name ), 'utf-8' ).trim();

								if ( path.extname( name ) === '.map' ) {
									contents = JSON.parse( contents );
								}

								return {
									name: name,
									contents: contents
								};
							});
					}

					var expected = catalogue( 'expected' );
					var actual = catalogue( 'actual' );

					try {
						assert.deepEqual( actual, expected );
						done();
					} catch ( err ) {
						done( err );
					}
				});
			});
		});
	});

	describe( 'errors', () => {
		it( 'reports the location of a syntax error', () => {
			var source = `var 42 = nope;`;

			try {
				buble.transform( source );
			} catch ( err ) {
				assert.equal( err.name, 'SyntaxError' );
				assert.deepEqual( err.loc, { line: 1, column: 4 });
				assert.equal( err.message, 'Unexpected token (1:4)' );
				assert.equal( err.snippet, `1 : var 42 = nope;\n        ^` );
				assert.equal( err.toString(), `SyntaxError: Unexpected token (1:4)\n1 : var 42 = nope;\n        ^` );
			}
		});

		it( 'reports the location of a compile error', () => {
			var source = `const x = 1; x++;`;

			try {
				buble.transform( source );
			} catch ( err ) {
				assert.equal( err.name, 'CompileError' );
				assert.equal( err.loc.line, 1 );
				assert.equal( err.loc.column, 13 );
				assert.equal( err.message, 'x is read-only (1:13)' );
				assert.equal( err.snippet, `1 : const x = 1; x++;\n                 ^^^` );
				assert.equal( err.toString(), `CompileError: x is read-only (1:13)\n1 : const x = 1; x++;\n                 ^^^` );
			}
		});
	});

	describe( 'target', () => {
		it( 'determines necessary transforms for a target environment', () => {
			var transforms = buble.target({ chrome: 49 });

			assert.ok( transforms.moduleImport );
			assert.ok( !transforms.arrow );
		});

		it( 'returns lowest common denominator support info', () => {
			var transforms = buble.target({ chrome: 49, node: 5 });

			assert.ok( transforms.defaultParameter );
			assert.ok( !transforms.arrow );
		});

		it( 'only applies necessary transforms', () => {
			var source = `
				const power = ( base, exponent = 2 ) => Math.pow( base, exponent );`;

			var result = buble.transform( source, {
				target: { chrome: 49, node: 5 }
			}).code;

			assert.equal( result, `
				const power = ( base, exponent ) => {
					if ( exponent === void 0 ) exponent = 2;

					return Math.pow( base, exponent );
				};` );
		});
	});

	describe( 'sourcemaps', () => {
		it( 'generates a valid sourcemap', () => {
			var map = buble.transform( '' ).map;
			assert.equal( map.version, 3 );
		});

		it( 'uses provided file and source', () => {
			var map = buble.transform( '', {
				file: 'output.js',
				source: 'input.js'
			}).map;

			assert.equal( map.file, 'output.js' );
			assert.deepEqual( map.sources, [ 'input.js' ] );
		});

		it( 'includes content by default', () => {
			var source = `let { x, y } = foo();`;
			var map = buble.transform( source ).map;

			assert.deepEqual( map.sourcesContent, [ source ] );
		});

		it( 'excludes content if requested', () => {
			var source = `let { x, y } = foo();`;
			var map = buble.transform( source, {
				includeContent: false
			}).map;

			assert.deepEqual( map.sourcesContent, [ null ] );
		});

		it( 'locates original content', () => {
			var source = `const add = ( a, b ) => a + b;`;
			var result = buble.transform( source, {
				file: 'output.js',
				source: 'input.js'
			});

			var smc = new SourceMapConsumer( result.map );

			var location = getLocation( result.code, 'add' );
			var expected = getLocation( source, 'add' );

			var actual = smc.originalPositionFor( location );

			assert.deepEqual( actual, {
				line: expected.line,
				column: expected.column,
				source: 'input.js',
				name: null
			});

			location = getLocation( result.code, 'a +' );
			expected = getLocation( source, 'a +' );

			actual = smc.originalPositionFor( location );

			assert.deepEqual( actual, {
				line: expected.line,
				column: expected.column,
				source: 'input.js',
				name: null
			});
		});

		it( 'recovers names', () => {
			var source = `
				const foo = 1;
				if ( x ) {
					const foo = 2;
				}`;

			var result = buble.transform( source, {
				file: 'output.js',
				source: 'input.js'
			});
			var smc = new SourceMapConsumer( result.map );

			var location = getLocation( result.code, 'var' );
			var actual = smc.originalPositionFor( location );

			assert.equal( actual.name, 'const' );

			location = getLocation( result.code, 'var', location.char + 1 );
			actual = smc.originalPositionFor( location );

			assert.equal( actual.name, 'const' );

			location = getLocation( result.code, 'foo$1', location.char + 1 );
			actual = smc.originalPositionFor( location );

			assert.equal( actual.name, 'foo' );
		});

		it( 'handles moved content', () => {
			var source = `
				for ( let i = 0; i < 10; i += 1 ) {
					const square = i * i;
					setTimeout( function () {
						log( square );
					}, i * 100 );
				}`;

			var result = buble.transform( source, {
				file: 'output.js',
				source: 'input.js'
			});
			var smc = new SourceMapConsumer( result.map );

			var location = getLocation( result.code, 'i < 10' );
			var expected = getLocation( source, 'i < 10' );

			var actual = smc.originalPositionFor( location );

			assert.deepEqual( actual, {
				line: expected.line,
				column: expected.column,
				source: 'input.js',
				name: null
			});

			location = getLocation( result.code, 'setTimeout' );
			expected = getLocation( source, 'setTimeout' );

			actual = smc.originalPositionFor( location );

			assert.deepEqual( actual, {
				line: expected.line,
				column: expected.column,
				source: 'input.js',
				name: null
			});
		});
	});
});
<commit_msg>allow subset of tests to run with e.g. --subset jsx<commit_after>var path = require( 'path' );
var fs = require( 'fs' );
var rimraf = require( 'rimraf' );
var child_process = require( 'child_process' );
var assert = require( 'assert' );
var glob = require( 'glob' );
var SourceMapConsumer = require( 'source-map' ).SourceMapConsumer;
var getLocation = require( './utils/getLocation.js' );
var buble = require( '../dist/buble.umd.js' );

require( 'source-map-support' ).install();
require( 'console-group' ).install();

function equal ( a, b ) {
	assert.equal( showInvisibles( a ), showInvisibles( b ) );
}

function showInvisibles ( str ) {
	return str
		.replace( /^ +/gm, spaces => repeat( '•', spaces.length ) )
		.replace( / +$/gm, spaces => repeat( '•', spaces.length ) )
		.replace( /^\t+/gm, tabs => repeat( '›   ', tabs.length ) )
		.replace( /\t+$/gm, tabs => repeat( '›   ', tabs.length ) );
}

function repeat ( str, times ) {
	var result = '';
	while ( times-- ) result += str;
	return result;
}

const subsetIndex = process.argv.indexOf( '--subset' );
const subset = ~subsetIndex ? process.argv[ subsetIndex + 1 ].split( ',' ).map( file => `${file}.js` ) : null;
const subsetFilter = subset ? file => ~subset.indexOf( file ) : () => true;

describe( 'buble', () => {
	fs.readdirSync( 'test/samples' ).filter( subsetFilter ).forEach( file => {
		var samples = require( './samples/' + file );

		describe( path.basename( file ), () => {
			samples.forEach( sample => {
				( sample.solo ? it.only : sample.skip ? it.skip : it )( sample.description, () => {
					if ( sample.error ) {
						assert.throws( () => {
							buble.transform( sample.input, sample.options );
						}, sample.error );
					}

					else {
						equal( buble.transform( sample.input, sample.options  ).code, sample.output );
					}
				});
			});
		});
	});

	if ( subset ) return;

	describe( 'cli', () => {
		fs.readdirSync( 'test/cli' ).forEach( dir => {
			if ( dir[0] === '.' ) return; // .DS_Store

			it( dir, done => {
				dir = path.resolve( 'test/cli', dir );
				rimraf.sync( path.resolve( dir, 'actual' ) );
				fs.mkdirSync( path.resolve( dir, 'actual' ) );

				var binFile = path.resolve(__dirname, '../bin/buble');
				var commandFile = path.resolve( dir, 'command.sh' );

				var command = fs.readFileSync( commandFile, 'utf-8' )
					.replace( 'buble', 'node ' + binFile );
				child_process.exec( command, {
					cwd: dir
				}, ( err, stdout, stderr ) => {
					if ( err ) return done( err );

					if ( stdout ) console.log( stdout );
					if ( stderr ) console.error( stderr );

					function catalogue ( subdir ) {
						subdir = path.resolve( dir, subdir );

						return glob.sync( '**/*.js?(.map)', { cwd: subdir })
							.sort()
							.map( name => {
								var contents = fs.readFileSync( path.resolve( subdir, name ), 'utf-8' ).trim();

								if ( path.extname( name ) === '.map' ) {
									contents = JSON.parse( contents );
								}

								return {
									name: name,
									contents: contents
								};
							});
					}

					var expected = catalogue( 'expected' );
					var actual = catalogue( 'actual' );

					try {
						assert.deepEqual( actual, expected );
						done();
					} catch ( err ) {
						done( err );
					}
				});
			});
		});
	});

	describe( 'errors', () => {
		it( 'reports the location of a syntax error', () => {
			var source = `var 42 = nope;`;

			try {
				buble.transform( source );
			} catch ( err ) {
				assert.equal( err.name, 'SyntaxError' );
				assert.deepEqual( err.loc, { line: 1, column: 4 });
				assert.equal( err.message, 'Unexpected token (1:4)' );
				assert.equal( err.snippet, `1 : var 42 = nope;\n        ^` );
				assert.equal( err.toString(), `SyntaxError: Unexpected token (1:4)\n1 : var 42 = nope;\n        ^` );
			}
		});

		it( 'reports the location of a compile error', () => {
			var source = `const x = 1; x++;`;

			try {
				buble.transform( source );
			} catch ( err ) {
				assert.equal( err.name, 'CompileError' );
				assert.equal( err.loc.line, 1 );
				assert.equal( err.loc.column, 13 );
				assert.equal( err.message, 'x is read-only (1:13)' );
				assert.equal( err.snippet, `1 : const x = 1; x++;\n                 ^^^` );
				assert.equal( err.toString(), `CompileError: x is read-only (1:13)\n1 : const x = 1; x++;\n                 ^^^` );
			}
		});
	});

	describe( 'target', () => {
		it( 'determines necessary transforms for a target environment', () => {
			var transforms = buble.target({ chrome: 49 });

			assert.ok( transforms.moduleImport );
			assert.ok( !transforms.arrow );
		});

		it( 'returns lowest common denominator support info', () => {
			var transforms = buble.target({ chrome: 49, node: 5 });

			assert.ok( transforms.defaultParameter );
			assert.ok( !transforms.arrow );
		});

		it( 'only applies necessary transforms', () => {
			var source = `
				const power = ( base, exponent = 2 ) => Math.pow( base, exponent );`;

			var result = buble.transform( source, {
				target: { chrome: 49, node: 5 }
			}).code;

			assert.equal( result, `
				const power = ( base, exponent ) => {
					if ( exponent === void 0 ) exponent = 2;

					return Math.pow( base, exponent );
				};` );
		});
	});

	describe( 'sourcemaps', () => {
		it( 'generates a valid sourcemap', () => {
			var map = buble.transform( '' ).map;
			assert.equal( map.version, 3 );
		});

		it( 'uses provided file and source', () => {
			var map = buble.transform( '', {
				file: 'output.js',
				source: 'input.js'
			}).map;

			assert.equal( map.file, 'output.js' );
			assert.deepEqual( map.sources, [ 'input.js' ] );
		});

		it( 'includes content by default', () => {
			var source = `let { x, y } = foo();`;
			var map = buble.transform( source ).map;

			assert.deepEqual( map.sourcesContent, [ source ] );
		});

		it( 'excludes content if requested', () => {
			var source = `let { x, y } = foo();`;
			var map = buble.transform( source, {
				includeContent: false
			}).map;

			assert.deepEqual( map.sourcesContent, [ null ] );
		});

		it( 'locates original content', () => {
			var source = `const add = ( a, b ) => a + b;`;
			var result = buble.transform( source, {
				file: 'output.js',
				source: 'input.js'
			});

			var smc = new SourceMapConsumer( result.map );

			var location = getLocation( result.code, 'add' );
			var expected = getLocation( source, 'add' );

			var actual = smc.originalPositionFor( location );

			assert.deepEqual( actual, {
				line: expected.line,
				column: expected.column,
				source: 'input.js',
				name: null
			});

			location = getLocation( result.code, 'a +' );
			expected = getLocation( source, 'a +' );

			actual = smc.originalPositionFor( location );

			assert.deepEqual( actual, {
				line: expected.line,
				column: expected.column,
				source: 'input.js',
				name: null
			});
		});

		it( 'recovers names', () => {
			var source = `
				const foo = 1;
				if ( x ) {
					const foo = 2;
				}`;

			var result = buble.transform( source, {
				file: 'output.js',
				source: 'input.js'
			});
			var smc = new SourceMapConsumer( result.map );

			var location = getLocation( result.code, 'var' );
			var actual = smc.originalPositionFor( location );

			assert.equal( actual.name, 'const' );

			location = getLocation( result.code, 'var', location.char + 1 );
			actual = smc.originalPositionFor( location );

			assert.equal( actual.name, 'const' );

			location = getLocation( result.code, 'foo$1', location.char + 1 );
			actual = smc.originalPositionFor( location );

			assert.equal( actual.name, 'foo' );
		});

		it( 'handles moved content', () => {
			var source = `
				for ( let i = 0; i < 10; i += 1 ) {
					const square = i * i;
					setTimeout( function () {
						log( square );
					}, i * 100 );
				}`;

			var result = buble.transform( source, {
				file: 'output.js',
				source: 'input.js'
			});
			var smc = new SourceMapConsumer( result.map );

			var location = getLocation( result.code, 'i < 10' );
			var expected = getLocation( source, 'i < 10' );

			var actual = smc.originalPositionFor( location );

			assert.deepEqual( actual, {
				line: expected.line,
				column: expected.column,
				source: 'input.js',
				name: null
			});

			location = getLocation( result.code, 'setTimeout' );
			expected = getLocation( source, 'setTimeout' );

			actual = smc.originalPositionFor( location );

			assert.deepEqual( actual, {
				line: expected.line,
				column: expected.column,
				source: 'input.js',
				name: null
			});
		});
	});
});
<|endoftext|>


<commit_before>'use strict'

const toHTML = require('vdom-to-html')
const parse5 = require('parse5-utils')
const assert = require('assert')
const path = require('path')
const fs = require('fs')

const render = require('..')

function renderFixture(fixtureName, locals) {
  const fn = eval(`(${render(fixture(fixtureName))})`)
  const root = fn.call({class: 'asdf'}, locals)
  const html = toHTML(root)
  parse5.parse(html, true)
  return html
}

describe('Render', function () {
  it('should render a template', function () {
    const html = renderFixture('item', {
      item: {
        id: '1234',
        title: 'some title',
        description: 'some description',
        active: true,
      }
    })

    assert(~html.indexOf('item active'))
    assert(~html.indexOf('class="title"'))
    assert(~html.indexOf(' 15)
    assert(lines[lines.length - 1].trim() === '}')
  })

  it('should run code blocks correctly', function () {
    const html = renderFixture('code')
    assert(~html.indexOf('
'))
  })

  it('should use locals when evaluating code blocks', function () {
    let html = renderFixture('code', {x: 0})
    assert(~html.indexOf('
'))
    html = renderFixture('code', {x: -1})
    assert(!~html.indexOf('
'))
  })

  it('should run while loops correctly', function () {
    const html = renderFixture('while')
    assert(html.match(/
/g).length === 5)
  })

  describe('case statements', function () {
    it('should not execute any cases when none match', function () {
      const html = renderFixture('case')
      assert(!html.includes('foo'))
      assert(!html.includes('bar'))
    })

    it('should execute default when no others match', function () {
      const html = renderFixture('case')
      assert(html.includes('llama'))
    })

    it('should execute only one match', function () {
      const html = renderFixture('case', {variable: 1})
      assert(html.includes('span'))
      assert(!html.includes('input'))
      assert(!html.includes('textarea'))
    })

    it('should fall through from the first case in a chain', function () {
      const html = renderFixture('case', {variable2: 'd'})
      assert(html.includes('bar'))
      assert(!html.includes('foo'))
    })

    it('should fall through from the middle case in a chain', function () {
      const html = renderFixture('case', {variable2: 'e'})
      assert(html.includes('bar'))
      assert(!html.includes('foo'))
    })

    it('should fall through from the last case in a chain', function () {
      const html = renderFixture('case', {variable2: 'f'})
      assert(html.includes('bar'))
      assert(!html.includes('foo'))
    })
  })
})

function fixture(name) {
  return fs.readFileSync(path.resolve(__dirname, 'fixtures/' + name + '.jade'), 'utf8')
}
<commit_msg>start attribute integration tests<commit_after>'use strict'

const toHTML = require('vdom-to-html')
const parse5 = require('parse5-utils')
const assert = require('assert')
const path = require('path')
const fs = require('fs')

const render = require('..')

function renderFixture(fixtureName, locals) {
  const fn = eval(`(${render(fixture(fixtureName))})`)
  const root = fn.call({class: 'asdf'}, locals)
  const html = toHTML(root)
  parse5.parse(html, true)
  return html
}

describe('Render', function () {
  it('should render a template', function () {
    const html = renderFixture('item', {
      item: {
        id: '1234',
        title: 'some title',
        description: 'some description',
        active: true,
      }
    })

    assert(~html.indexOf('item active'))
    assert(~html.indexOf('class="title"'))
    assert(~html.indexOf(' 15)
    assert(lines[lines.length - 1].trim() === '}')
  })

  it('should run code blocks correctly', function () {
    const html = renderFixture('code')
    assert(~html.indexOf('
'))
  })

  it('should use locals when evaluating code blocks', function () {
    let html = renderFixture('code', {x: 0})
    assert(~html.indexOf('
'))
    html = renderFixture('code', {x: -1})
    assert(!~html.indexOf('
'))
  })

  it('should run while loops correctly', function () {
    const html = renderFixture('while')
    assert(html.match(/
/g).length === 5)
  })

  describe('attributes', function () {
    it('should add arbitrary attributes', function () {
      const html = renderFixture('attributes')
      assert(html.includes('required'))
      assert(!html.includes('something'))
    })

    it('should add class attributes in array notation', function () {
      let html = renderFixture('attributes')
      assert(html.includes('1 2'))
      html = renderFixture('attributes', {variable: 'meow'})
      assert(html.includes('1 2 meow'))
    })
  })

  describe('case statements', function () {
    it('should not execute any cases when none match', function () {
      const html = renderFixture('case')
      assert(!html.includes('foo'))
      assert(!html.includes('bar'))
    })

    it('should execute default when no others match', function () {
      const html = renderFixture('case')
      assert(html.includes('llama'))
    })

    it('should execute only one match', function () {
      const html = renderFixture('case', {variable: 1})
      assert(html.includes('span'))
      assert(!html.includes('input'))
      assert(!html.includes('textarea'))
    })

    it('should fall through from the first case in a chain', function () {
      const html = renderFixture('case', {variable2: 'd'})
      assert(html.includes('bar'))
      assert(!html.includes('foo'))
    })

    it('should fall through from the middle case in a chain', function () {
      const html = renderFixture('case', {variable2: 'e'})
      assert(html.includes('bar'))
      assert(!html.includes('foo'))
    })

    it('should fall through from the last case in a chain', function () {
      const html = renderFixture('case', {variable2: 'f'})
      assert(html.includes('bar'))
      assert(!html.includes('foo'))
    })
  })
})

function fixture(name) {
  return fs.readFileSync(path.resolve(__dirname, 'fixtures/' + name + '.jade'), 'utf8')
}
<|endoftext|>


<commit_before>'use strict';

const expect = require('chai').expect;
const nock = require('nock');

const lib = require('../src');

describe('bip', () => {

  describe('valid', () => {

    const number = 11111111;

    beforeEach(() => {
      nock.disableNetConnect();
      nock('http://www.metrosantiago.cl')
        .get(`/contents/guia-viajero/includes/consultarTarjeta/${number}`)
        .reply(200, [
          {
            'estado': 0,
            'mensaje': 'Tarjeta Valida'
          },
          {
            'salida': true,
            'tarjeta': '11111111',
            'saldo': '1180',
            'fecha': '02\/01\/2016 20:59'
          }
        ]);
    });

    it('should return a balance data', done => {
      lib(number).then(data => {
        expect(data.number).to.eql(number);
        expect(data.balance).to.eql(1180);
        expect(data.date).to.eql(new Date('2016-01-02T23:59:00.000Z'));
        expect(data.message).to.eql('Tarjeta Valida');
        expect(data.valid).to.be.true;
        done();
      }).catch(err => {
        expect(err).to.be.undefined;
        done();
      });
    });
  });

  describe('invalid', () => {

    const number = 11111111;

    beforeEach(() => {
      nock.disableNetConnect();
      nock('http://www.metrosantiago.cl')
        .get(`/contents/guia-viajero/includes/consultarTarjeta/${number}`)
        .reply(200, [
          {
            'estado': 1,
            'mensaje': 'Esta tarjeta no se puede cargar'
          },
          {
            'salida': false,
            'tarjeta': '11111111'
          }
        ]);
    });

    it('should return a empty data', done => {
      lib(number).catch((err) => {
        expect(err.message).to.eql('Esta tarjeta no se puede cargar');
        done();
      });
    });
  });
});
<commit_msg>Fix tests<commit_after>'use strict';

const expect = require('chai').expect;
const nock = require('nock');

const lib = require('../src');

describe('bip', () => {

  describe('valid', () => {

    const number = 11111111;

    beforeEach(() => {
      nock.disableNetConnect();
      nock('http://www.metrosantiago.cl')
        .get(`/contents/guia-viajero/includes/consultarTarjeta/${number}`)
        .reply(200, [
          {
            'estado': 0,
            'mensaje': 'Tarjeta Valida'
          },
          {
            'salida': true,
            'tarjeta': '11111111',
            'saldo': '1180',
            'fecha': '02\/01\/2016 20:59'
          }
        ]);
    });

    it('should return a balance data', done => {
      lib(number).then(data => {
        expect(data.number).to.eql(number);
        expect(data.balance).to.eql(1180);
        expect(data.date).to.be.a('date');
        expect(data.message).to.eql('Tarjeta Valida');
        expect(data.valid).to.be.true;
        done();
      }).catch(err => {
        expect(err).to.be.undefined;
        done();
      });
    });
  });

  describe('invalid', () => {

    const number = 11111111;

    beforeEach(() => {
      nock.disableNetConnect();
      nock('http://www.metrosantiago.cl')
        .get(`/contents/guia-viajero/includes/consultarTarjeta/${number}`)
        .reply(200, [
          {
            'estado': 1,
            'mensaje': 'Esta tarjeta no se puede cargar'
          },
          {
            'salida': false,
            'tarjeta': '11111111'
          }
        ]);
    });

    it('should return a empty data', done => {
      lib(number).catch((err) => {
        expect(err.message).to.eql('Esta tarjeta no se puede cargar');
        done();
      });
    });
  });
});
<|endoftext|>