<commit_before>/**
 * ingestion.js
 * expects:
 * 1. path of directory (target)
 * 2. parentpid
 * 3. namespace
 * 4. model
 *   (note: basic image,large image,audio,video, collection, pdf, binary -- all require
 * the "ibsp" in the command string.)
 * output:
 *  log of drush run
 * errors:
 *  if drush not installed
 *  if parameters missing
 *  if first command did not run
 *  if first command did run but did not prep ingest
 *  if first command ran with a good ingest but second command did not run
 *   (only if first command ran successfully)if second ran but did not ingest
 *
 * @param target directory path
 * @param parentpid
 * @param namespace
 * @param model
 * @return $message
 *
 */
// for testing
//
var param = process.argv;
console.log('hi');
target = String(param[2]);
parentpid = String(param[3]);
namespace = String(param[4]);
model = String(param[5]);

var status=[];

function ingestion(target,parentpid,namespace,model) {
  // build command pieces
  // two drupalhomes one for testing on vagrant and one for server installation
  var drupalhome = '/var/www/drupal';
  //var drupalhome = '/vhosts/dlwork/web/collections';
  console.log('drupalhome = ',drupalhome);
  // serveruri is the location of the drupal_home on the drupal server
  var serveruri = 'http://localhost';

  //var serveruri = 'http://dlwork.lib.utk.edu/dev/';
  console.log('serveruri = ',serveruri);
  console.log('parentpid = ',parentpid);
  // namespace
  console.log('namespace = ',namespace);
  // target is the local directory holding the ingest files
  console.log('target = ',target);
  // make mongo connection
  /*
  var mongoose = require('mongoose');
  mongoose.connect('mongodb://localhost/ibu');
  var conn = mongoose.connection;
  */
  //
  var $message = 'ingest did not happen';
  var contentmodel = '';
  if ((model)&& (model==='basic')) {
    contentmodel = 'islandora:sp_basic_image';
  }
  if ((model)&&(model==='large')) {
    contentmodel = 'islandora:sp_Large_image';
  }
  console.log('model = ',model);
  // execute first drush command
  var exec = require('child_process').exec;
  // test for drush existance
  var cmdtest = String('whereis drush')
  exec(cmdtest, function(error, stdout, stderr) {
     // command output is in stdout
     var output = `stdout:${stdout}`;
     //console.log(`stdout:${stdout}`);
     // test command log, stdout, for success indication
     if(output.indexOf('bin/drush') > -1) {
       $message = 'drush installed';
       console.log($message);
       //status.push("$message");
     }// end if
     else {
       $message = 'drush not installed';
       //console.log($message);
       status.push("$message");
       //exit if drush not installed
       return $message;
     }//end else
  });//end exec
  var cmd = String('drush -r '+drupalhome+' -v -u=1 --uri='+serveruri+' ibsp --content_models='+contentmodel+' --type=directory --parent='+parentpid+' --namespace='+namespace+' --target='+target );
  // show assembled command
  //console.log('cmd=',cmd);
  if ((target !='')&&(contentmodel !='')&&(parentpid !='')&&(namespace !='')) {
    exec(cmd, function(error, stdout, stderr) {
     // command output is in stdout
     var output1 = `stdout:${stdout}`;
     //console.log(`stdout:${stdout}`);
     // test command log, stdout, for success indication
     if(output1.indexOf('SetID:') > -1) {
       $message = 'ingest prep drush command success';
       console.log($message);
       status.push("$message");
       //return $message;
     }// end if
     else {
       $message = 'first ingest command failed!';
       console.log($message);
       status.push("$message");
       return $message;
     }//end else
    });// end exec
  }// end if
  else {
     $message = 'parameters for first command missing, ingest not started.';
     console.log($message);
     status.push("$message");
     return $message;
  }// end else
  // exec second drush command
  var cmd2 = String('drush -r '+drupalhome+'-v -u=1 --uri='+serveruri+' islandora_batch_ingest');
  console.log('cmd2=',cmd2);
  //$message = 'hold';
  if ($message = 'ingest prep drush command success') {
    exec(cmd2, function(error, stdout, stderr) {
     // command output is in stdout
     var output2 = `stdout:${stdout}`;
     //console.log(`stdout:${stdout}`);
     // test command log, stdout, for success indication
     if(output2.indexOf('Processing complete;') > -1) {
       $message = 'ingest drush command success';
       console.log($message);
       status.push("$message");
       //return $message;
     }// end if
     else {
       $message = 'first ingest command failed!';
       console.log($message);
       status.push("$message");
       return $message;
     }//end else
    });
  }// end if
  return $message;
}// end function
//export default ingestion;
ingestion(target,parentpid,namespace,model);

<commit_msg>edit comments<commit_after>/**
 * ingestion.js
 * expects:
 * 1. path of directory (target)
 * 2. parentpid
 * 3. namespace
 * 4. model
 *   (note: basic image,large image,audio,video, collection, pdf, binary -- all require
 * the "ibsp" in the command string.)
 * output:
 *  log of drush run
 * errors:
 *  if drush not installed
 *  if parameters missing
 *  if first command did not run
 *  if first command did run but did not prep ingest
 *  if first command ran with a good ingest but second command did not run
 *   (only if first command ran successfully)if second ran but did not ingest
 *
 * @param target directory path
 * @param parentpid
 * @param namespace
 * @param model
 * @return $message
 *
 */
// for testing
//
var param = process.argv;
console.log('hi');
target = String(param[2]);
parentpid = String(param[3]);
namespace = String(param[4]);
model = String(param[5]);

var status=[];

function ingestion(target,parentpid,namespace,model) {
  // build command pieces
  // two drupalhomes one for testing on vagrant and one for server installation
  var drupalhome = '/var/www/drupal';
  //var drupalhome = '/vhosts/dlwork/web/collections';
  console.log('drupalhome = ',drupalhome);
  // serveruri is the location of the drupal_home on the drupal server
  var serveruri = 'http://localhost';

  //var serveruri = 'http://dlwork.lib.utk.edu/dev/';
  console.log('serveruri = ',serveruri);
  console.log('parentpid = ',parentpid);
  // namespace
  console.log('namespace = ',namespace);
  // target is the local directory holding the ingest files
  console.log('target = ',target);
  // make mongo connection
  /*
  var mongoose = require('mongoose');
  mongoose.connect('mongodb://localhost/ibu');
  var conn = mongoose.connection;
  */
  //
  var $message = 'ingest did not happen';
  var contentmodel = '';
  if ((model)&& (model==='basic')) {
    contentmodel = 'islandora:sp_basic_image';
  }
  if ((model)&&(model==='large')) {
    contentmodel = 'islandora:sp_Large_image';
  }
  console.log('model = ',model);
  // execute first drush command
  var exec = require('child_process').exec;
  // test for drush existance
  var cmdtest = String('whereis drush')
  exec(cmdtest, function(error, stdout, stderr) {
     // command output is in stdout
     var output = `stdout:${stdout}`;
     //console.log(`stdout:${stdout}`);
     // test command log, stdout, for success indication
     if(output.indexOf('bin/drush') > -1) {
       $message = 'drush installed';
       console.log($message);
       //status.push("$message");
     }// end if
     else {
       $message = 'drush not installed';
       //console.log($message);
       status.push("$message");
       //exit if drush not installed
       return $message;
     }//end else
  });//end exec
  var cmd = String('drush -r '+drupalhome+' -v -u=1 --uri='+serveruri+' ibsp --content_models='+contentmodel+' --type=directory --parent='+parentpid+' --namespace='+namespace+' --target='+target );
  // show assembled command
  //console.log('cmd=',cmd);
  if ((target !='')&&(contentmodel !='')&&(parentpid !='')&&(namespace !='')) {
    exec(cmd, function(error, stdout, stderr) {
     // command output is in stdout
     var output1 = `stdout:${stdout}`;
     //console.log(`stdout:${stdout}`);
     // test command log, stdout, for success indication
     if(output1.indexOf('SetID:') > -1) {
       $message = 'ingest prep drush command success';
       console.log($message);
       //status.push("$message");
       //return $message;
     }// end if
     else {
       $message = 'first ingest command failed!';
       console.log($message);
       status.push("$message");
       return $message;
     }//end else
    });// end exec
  }// end if
  else {
     $message = 'parameters for first command missing, ingest not started.';
     console.log($message);
     status.push("$message");
     return $message;
  }// end else
  // exec second drush command
  var cmd2 = String('drush -r '+drupalhome+'-v -u=1 --uri='+serveruri+' islandora_batch_ingest');
  console.log('cmd2=',cmd2);
  //$message = 'hold';
  if ($message = 'ingest prep drush command success') {
    exec(cmd2, function(error, stdout, stderr) {
     // command output is in stdout
     var output2 = `stdout:${stdout}`;
     //console.log(`stdout:${stdout}`);
     // test command log, stdout, for success indication
     if(output2.indexOf('Processing complete;') > -1) {
       $message = 'ingest drush command success';
       console.log($message);
       status.push("$message");
       //return $message;
     }// end if
     else {
       $message = 'first ingest command failed!';
       console.log($message);
       status.push("$message");
       return $message;
     }//end else
    });
  }// end if
  return $message;
}// end function
//export default ingestion;
ingestion(target,parentpid,namespace,model);

<|endoftext|>


<commit_before>'use strict';

var polygot = require('../lib/polygot');
var fs = require('fs');
var concat = require('concat-stream');
var expects = require('chai').expect;
var bufferEqual = require('buffer-equal');
var exec = require('child_process').exec;

fs.mkdirSync('tmp');

describe('polygot module', function() {

	it('should combine Windows and POSIX scripts', function(callback) {

		var winScript = fs.createReadStream('test/artifacts/hello.bat');
		var posixScript = fs.createReadStream('test/artifacts/hello.sh');

		var polygotStream = polygot(winScript, posixScript);

		var concatStream = concat(onResult);

		polygotStream.pipe(concatStream);

		function onResult(result)
		{
			var cmdScriptBuffer = fs.readFileSync('test/artifacts/hello.cmd');
			var resultBuffer = new Buffer(result);

			expects(bufferEqual(resultBuffer, cmdScriptBuffer)).to.equal(true);

			callback();
		}

	});

	it('result should execute on Windows and POSIX platforms', function(callback) {

		var winScript = fs.createReadStream('test/artifacts/hello.bat');
		var posixScript = fs.createReadStream('test/artifacts/hello.sh');

		var polygotStream = polygot(winScript, posixScript);

		var result = fs.createWriteStream('tmp/hello.cmd');

		polygotStream.pipe(result);

		polygotStream.on('end', function(){

			if (/^win/.test(process.platform))
			{
				execute('.\\tmp\\hello.cmd', function(greeting){

					expects(greeting).to.equal('Hello\r\n');

					callback();

				});
			}
			else
			{
				fs.chmodSync('tmp/hello.cmd', '755');

				// Work around "text file busy" issue on Linux
				setTimeout(function() {
					execute('tmp/hello.cmd', function(greeting){

						expects(greeting).to.equal('Hello\n');

						callback();

					});
				}, 100);
			}

		});

	});

});

function execute(command, callback)
{
    exec(command, function(error, stdout, stderr){
    	if (error)
    	{
    		throw error;
    	}

    	callback(stdout);
    });
}<commit_msg>Add program test<commit_after>'use strict';

var polygot = require('../lib/polygot');
var fs = require('fs');
var concat = require('concat-stream');
var expects = require('chai').expect;
var bufferEqual = require('buffer-equal');
var exec = require('child_process').exec;

fs.mkdirSync('tmp');

describe('polygot module', function() {

	it('should combine Windows and POSIX scripts', function(callback) {

		var winScript = fs.createReadStream('test/artifacts/hello.bat');
		var posixScript = fs.createReadStream('test/artifacts/hello.sh');

		var polygotStream = polygot(winScript, posixScript);

		var concatStream = concat(onResult);

		polygotStream.pipe(concatStream);

		function onResult(result)
		{
			var cmdScriptBuffer = fs.readFileSync('test/artifacts/hello.cmd');
			var resultBuffer = new Buffer(result);

			expects(bufferEqual(resultBuffer, cmdScriptBuffer)).to.equal(true);

			callback();
		}

	});

	it('result should execute on Windows and POSIX platforms', function(callback) {

		var winScript = fs.createReadStream('test/artifacts/hello.bat');
		var posixScript = fs.createReadStream('test/artifacts/hello.sh');

		var polygotStream = polygot(winScript, posixScript);

		var result = fs.createWriteStream('tmp/hello.cmd');

		polygotStream.pipe(result);

		polygotStream.on('end', function(){

			if (/^win/.test(process.platform))
			{
				execute('.\\tmp\\hello.cmd', function(greeting){

					expects(greeting).to.equal('Hello\r\n');

					callback();

				});
			}
			else
			{
				fs.chmod('tmp/hello.cmd', '755', function(){
					execute('tmp/hello.cmd', function(greeting){

						expects(greeting).to.equal('Hello\n');

						callback();

					});
				});
			}

		});

	});

});

describe('polygot program', function() {

	it('result should execute on Windows and POSIX platforms', function(callback) {

		execute('node bin/polygot.js test/artifacts/hello.bat test/artifacts/hello.sh > tmp/program.cmd', function() {

			if (/^win/.test(process.platform))
			{
				execute('.\\tmp\\hello.cmd', function(greeting){

					expects(greeting).to.equal('Hello\r\n');

					callback();

				});
			}
			else
			{
				fs.chmod('tmp/program.cmd', '755', function(){
					execute('tmp/program.cmd', function(greeting){

						expects(greeting).to.equal('Hello\n');

						callback();

					});
				});
			}

		});

	});

});

function execute(command, callback)
{
    exec(command, function(error, stdout, stderr){
    	if (error)
    	{
    		throw error;
    	}

    	callback(stdout);
    });
}<|endoftext|>


<commit_before>/**
* Manage pages in the dashboard tables list
*
* Calculate the pages of the dashboard tables list
* and show them
*
* Usage example:
*
var paginator = new cdb.admin.dashboard.DashboardPaginator({
  el: $("body"),
  items: model.items
});

* It needs a tables model to run correctly.
*/

cdb.admin.DashboardPaginator = cdb.core.View.extend({

  el: "ul",

  _TEXTS: {
    visualizations: {
      locked:   _t('View all locked visualizations'),
      unlocked: _t('View non locked visualizations')
    }
  },

  events: {
    'click .page': '_pageChange',
    'click .lock': '_onLockClick'
  },

  initialize: function() {
    _.bindAll(this, "_updatePaginator", "_pageChange");

    this.model = new cdb.core.Model({ locked: false });
    this.items = this.options.items;
    this.router = this.options.router;

    this.add_related_model(this.items);

    // Bindings
    this.items.bind('reset add remove', this._updatePaginator, this);
  },

  _renderLinks: function() {

    var self = this;

    var pages = [];

    for (var i = this.total_pages, length = 0; length < i; i--) {
      pages.push(i);
    }

    var $li = $("
");
    var $link = $(""+ this.current_page +"");
    this.$ul.append($li.append($link));

    var tag = this.attrs.tags;
    var q   = this.attrs.q;

    var path = '';

    this.dropdown = new cdb.admin.PaginatorDropdown({
      className: 'dropdown paginator border',
      template_base: 'dashboard/views/paginator_dropdown',
      path: path,
      current_page: this.current_page,
      pages: pages,
      vertical_offset: 10,
      vertical_position: "up",
      position: "offset",
      width: 32,
      target: $(".paginator_filter"),
    });

    this.dropdown.bind("onClick", function(e) {
      self._pageChange(e);
    });

    $("body").append(this.dropdown.render().el);
    cdb.god.bind("closeDialogs", this.dropdown.hide, this.dropdown);

  },

  _renderPrevLink: function() {

    var template = '
<a href="<%= url %>" class="<%= classes %>">
';
    var opts     = { url: "#", classes: "prev button grey page" };

    if (this.current_page - 1 > 0) {

      opts.url = (this.current_page - 1);

    } else {
      opts.classes = opts.classes + " disabled";
    }

    this.$ul.append(_.template(template, opts));

  },

  _renderNextLink: function() {

    var template = '
<a href="<%= url %>" class="<%= classes %>">
';
    var opts     = { url: "#", classes: "next button grey page" };

    if (this.current_page < this.total_pages) {
      opts.url = (this.current_page + 1);
    } else {
      opts.classes = opts.classes + " disabled";
    }

    this.$ul.append(_.template(template, opts));

  },

  _renderFullPagination: function() {

    this.$el.removeClass("view_all");
    this.$el.removeClass("empty");

    this._renderPrevLink();
    this._renderLinks();
    this._renderNextLink();

  },

  render: function() {
    this.clearSubViews();
    this.$el.empty();
    this.$el.removeClass('empty');

    this.attrs         = this.items.options.attributes;
    this.current_page  = parseInt(this.items.options.get("page"), 10);
    this.per_page      = this.items.options.get("per_page");
    this.total_entries = this.items.total_entries;
    this.total_pages   = this.items.getTotalPages();

    // Render?
    if (this.total_entries <= this.per_page && !this.model.get('locked') && !this.router.model.get('locked')) {
      this.$el.addClass("empty");
      return false;
    }

    this.$el.append($('
'));
    this.$ul = this.$("ul");
    this.$locked = $('
');
    this.$el.prepend(this.$locked);

    var per_page_count = (this.items.options.get("type") == 'table') ? this.items._PREVIEW_TABLES_PER_PAGE : this.items._PREVIEW_ITEMS_PER_PAGE;

    // Render pagination?
    if (this.total_entries > this.per_page) {
      this._renderFullPagination();
      this.$el.append(this.$ul);
    }

    // Add locked visualizations link?
    if (this.options.what === "visualizations" && ( this.model.get('locked') || this.router.model.get('locked') )) {
      var inLockView = this.router.model.get('locked');
      this.$locked.append("" + this._TEXTS.visualizations[ !inLockView ? 'locked' : 'unlocked' ] + "");
    }

    return this;

  },

  /**
  * Update the dashboard paginator
  */
  _updatePaginator: function() {
    // Don't show lock link from the beginning
    this.model.set('locked', false);

    // We need to check if there are any lock visualizations
    if (this.options.what !== "tables" && !this.router.model.get('locked')) {
      console.log("hello");
      this._checkLockTables();
    }

    this.render();
  },

  _checkLockTables: function() {
    var self = this;

    // There is no info about how many lock tables user has in this account
    // so we need to make a request to the visualizations endpoint and check
    // if there is any and show the link at the bottom.
    var vis_clone = new cdb.admin.Visualizations({ type: "derived" });

    vis_clone.options.set(
      _.extend(
        this.items.options.toJSON(),
        {
          locked: true,
          page: 1,
          per_page: 1
        }
      )
    );

    vis_clone.fetch({
      success: function(c) {
        console.log(c);
        if (c.size() > 0) {
          self.model.set('locked', true);
          self.render();
        }
      }
    });
  },

  _onLockClick: function(e) {
    this.killEvent(e);
    this.router.model.set({
      q: '',
      tag: '',
      page: 1,
      exclude_shared: false,
      locked: !this.router.model.get('locked')
    }, {
      silent: true
    });
    this.trigger('lockedVis', "1", this);
  },

  _pageChange: function(e) {
    this.killEvent(e);

    this.dropdown.hide();

    var page = $(e.currentTarget).attr('href');

    if (!$(e.currentTarget).hasClass("disabled")) {
      this.trigger('goToPage', page, this);

      // testeability
      if(this.cancelClicks) { this.killEvent(e); }
    }
  }

});
<commit_msg>removed unnecessary consoles<commit_after>/**
* Manage pages in the dashboard tables list
*
* Calculate the pages of the dashboard tables list
* and show them
*
* Usage example:
*
var paginator = new cdb.admin.dashboard.DashboardPaginator({
  el: $("body"),
  items: model.items
});

* It needs a tables model to run correctly.
*/

cdb.admin.DashboardPaginator = cdb.core.View.extend({

  el: "ul",

  _TEXTS: {
    visualizations: {
      locked:   _t('View all locked visualizations'),
      unlocked: _t('View non locked visualizations')
    }
  },

  events: {
    'click .page': '_pageChange',
    'click .lock': '_onLockClick'
  },

  initialize: function() {
    _.bindAll(this, "_updatePaginator", "_pageChange");

    this.model = new cdb.core.Model({ locked: false });
    this.items = this.options.items;
    this.router = this.options.router;

    this.add_related_model(this.items);

    // Bindings
    this.items.bind('reset add remove', this._updatePaginator, this);
  },

  _renderLinks: function() {

    var self = this;

    var pages = [];

    for (var i = this.total_pages, length = 0; length < i; i--) {
      pages.push(i);
    }

    var $li = $("
");
    var $link = $(""+ this.current_page +"");
    this.$ul.append($li.append($link));

    var tag = this.attrs.tags;
    var q   = this.attrs.q;

    var path = '';

    this.dropdown = new cdb.admin.PaginatorDropdown({
      className: 'dropdown paginator border',
      template_base: 'dashboard/views/paginator_dropdown',
      path: path,
      current_page: this.current_page,
      pages: pages,
      vertical_offset: 10,
      vertical_position: "up",
      position: "offset",
      width: 32,
      target: $(".paginator_filter"),
    });

    this.dropdown.bind("onClick", function(e) {
      self._pageChange(e);
    });

    $("body").append(this.dropdown.render().el);
    cdb.god.bind("closeDialogs", this.dropdown.hide, this.dropdown);

  },

  _renderPrevLink: function() {

    var template = '
<a href="<%= url %>" class="<%= classes %>">
';
    var opts     = { url: "#", classes: "prev button grey page" };

    if (this.current_page - 1 > 0) {

      opts.url = (this.current_page - 1);

    } else {
      opts.classes = opts.classes + " disabled";
    }

    this.$ul.append(_.template(template, opts));

  },

  _renderNextLink: function() {

    var template = '
<a href="<%= url %>" class="<%= classes %>">
';
    var opts     = { url: "#", classes: "next button grey page" };

    if (this.current_page < this.total_pages) {
      opts.url = (this.current_page + 1);
    } else {
      opts.classes = opts.classes + " disabled";
    }

    this.$ul.append(_.template(template, opts));

  },

  _renderFullPagination: function() {

    this.$el.removeClass("view_all");
    this.$el.removeClass("empty");

    this._renderPrevLink();
    this._renderLinks();
    this._renderNextLink();

  },

  render: function() {
    this.clearSubViews();
    this.$el.empty();
    this.$el.removeClass('empty');

    this.attrs         = this.items.options.attributes;
    this.current_page  = parseInt(this.items.options.get("page"), 10);
    this.per_page      = this.items.options.get("per_page");
    this.total_entries = this.items.total_entries;
    this.total_pages   = this.items.getTotalPages();

    // Render?
    if (this.total_entries <= this.per_page && !this.model.get('locked') && !this.router.model.get('locked')) {
      this.$el.addClass("empty");
      return false;
    }

    this.$el.append($('
'));
    this.$ul = this.$("ul");
    this.$locked = $('
');
    this.$el.prepend(this.$locked);

    var per_page_count = (this.items.options.get("type") == 'table') ? this.items._PREVIEW_TABLES_PER_PAGE : this.items._PREVIEW_ITEMS_PER_PAGE;

    // Render pagination?
    if (this.total_entries > this.per_page) {
      this._renderFullPagination();
      this.$el.append(this.$ul);
    }

    // Add locked visualizations link?
    if (this.options.what === "visualizations" && ( this.model.get('locked') || this.router.model.get('locked') )) {
      var inLockView = this.router.model.get('locked');
      this.$locked.append("" + this._TEXTS.visualizations[ !inLockView ? 'locked' : 'unlocked' ] + "");
    }

    return this;

  },

  /**
  * Update the dashboard paginator
  */
  _updatePaginator: function() {
    // Don't show lock link from the beginning
    this.model.set('locked', false);

    // We need to check if there are any lock visualizations
    if (this.options.what !== "tables" && !this.router.model.get('locked')) {
      this._checkLockTables();
    }

    this.render();
  },

  _checkLockTables: function() {
    var self = this;

    // There is no info about how many lock tables user has in this account
    // so we need to make a request to the visualizations endpoint and check
    // if there is any and show the link at the bottom.
    var vis_clone = new cdb.admin.Visualizations({ type: "derived" });

    vis_clone.options.set(
      _.extend(
        this.items.options.toJSON(),
        {
          locked: true,
          page: 1,
          per_page: 1
        }
      )
    );

    vis_clone.fetch({
      success: function(c) {
        if (c.size() > 0) {
          self.model.set('locked', true);
          self.render();
        }
      }
    });
  },

  _onLockClick: function(e) {
    this.killEvent(e);
    this.router.model.set({
      q: '',
      tag: '',
      page: 1,
      exclude_shared: false,
      locked: !this.router.model.get('locked')
    }, {
      silent: true
    });
    this.trigger('lockedVis', "1", this);
  },

  _pageChange: function(e) {
    this.killEvent(e);

    this.dropdown.hide();

    var page = $(e.currentTarget).attr('href');

    if (!$(e.currentTarget).hasClass("disabled")) {
      this.trigger('goToPage', page, this);

      // testeability
      if(this.cancelClicks) { this.killEvent(e); }
    }
  }

});
<|endoftext|>


<commit_before>/**
 * Tests results wrapper and asserts API
 */
var assert = require("assert"),
  Results = require("../core/results");

const { describe, it } = require("@jest/globals");

describe("Metrics", () => {
  const results = new Results();

  it("should be set to zero by default", () => {
    results.setMetric("foo");
    assert.strictEqual(results.getMetric("foo"), 0);
  });

  it("should be correctly set", () => {
    results.setMetric("foo", "bar");
    assert.strictEqual(results.getMetric("foo"), "bar");
  });

  it("avarage should be correctly calculated", () => {
    results.addToAvgMetric("foo", 2);
    results.addToAvgMetric("foo", 1);
    results.addToAvgMetric("bar", 4);
    assert.strictEqual(results.getMetric("foo"), 1.5);
    assert.strictEqual(results.getMetric("bar"), 4);
  });

  it("should be correctly set (with no casting)", () => {
    results.setMetric("bar", null);
    assert.strictEqual(results.getMetric("bar"), null);
  });

  it("should return the list of registered metrics", () => {
    assert.deepStrictEqual(results.getMetricsNames(), ["foo", "bar"]);
  });

  it("should return values of metrics", () => {
    results.setMetric("foo", "bar");
    results.setMetric("bar", 42);

    assert.deepStrictEqual(results.getMetrics(), {
      foo: "bar",
      bar: 42,
    });
  });

  it("should increment a metric", () => {
    results.setMetric("bar", 42);

    results.incrMetric("bar");
    assert.strictEqual(results.getMetric("bar"), 43);

    results.incrMetric("bar", 10);
    assert.strictEqual(results.getMetric("bar"), 53);
  });

  it("should increment even not existing metric", () => {
    results.incrMetric("not-existing-metric");
    assert.strictEqual(results.getMetric("not-existing-metric"), 1);
  });
});

describe("Offenders", () => {
  const results = new Results();

  it("should be registered", () => {
    results.addOffender("metric", "foo");
    results.addOffender("metric", { url: "bar", size: 42 });
    results.setMetric("metric", 42);

    results.addOffender("metric2", "test");

    assert.deepStrictEqual(results.getAllOffenders(), {
      metric: ["foo", { url: "bar", size: 42 }],
      metric2: ["test"],
    });
  });

  it("should be kept in order", () => {
    assert.deepStrictEqual(results.getOffenders("metric"), [
      "foo",
      { url: "bar", size: 42 },
    ]);
    assert.deepStrictEqual(results.getOffenders("metric2"), ["test"]);

    assert.strictEqual("undefined", typeof results.getOffenders("metric3"));
  });
});

describe("Asserts", () => {
  const results = new Results();

  it("should be correctly registered", () => {
    results.setAsserts({
      foo: 123,
      bar: 0,
    });
    assert.deepStrictEqual(results.getAsserts(), {
      foo: 123,
      bar: 0,
    });

    assert.ok(results.hasAssertion("foo"));
    assert.ok(results.hasAssertion("test") === false);

    assert.strictEqual(results.getAssertion("foo"), 123);
  });

  it("should be correctly processed", () => {
    results.setAsserts({
      foo: 123,
      bar: 0,
    });

    results.setMetric("foo", 123);
    assert.ok(results.assert("foo") === true, "foo lte 123");

    results.setMetric("foo", 124);
    assert.ok(results.assert("foo") === false, "foo is not lte 123");

    results.setMetric("test", 200);
    assert.ok(
      results.hasAssertion("test") === false,
      "no assert for test metric"
    );
    assert.ok(results.assert("test"), "no assert for test metric");
  });

  it("can be added on the fly", () => {
    results.setMetric("foo", 125);
    assert.ok(results.assert("foo") === false, "foo is lte 123");

    results.setAssert("foo", 200);
    assert.ok(results.assert("foo"), "foo is lte 200");
  });

  it("should always be meet for non-numeric values", () => {
    results.setAssert("foo", 200);

    results.setMetric("foo", "1.9.2");
    assert.ok(results.assert("foo"), "string assert");

    results.setMetric("foo", false);
    assert.ok(results.assert("foo"), "bool assert");
  });

  it("should be correctly reported", () => {
    results.setAsserts({
      foo: 123,
      bar: 0,
    });

    results.setMetric("foo", 123);
    results.setMetric("bar", 0);
    assert.deepStrictEqual(
      results.getFailedAsserts(),
      [],
      "all asserts are meet"
    );

    results.setMetric("foo", 124);
    results.setMetric("bar", 0);
    assert.deepStrictEqual(
      results.getFailedAsserts(),
      ["foo"],
      "one assert is not meet"
    );

    results.setMetric("foo", 124);
    results.setMetric("bar", 1);
    assert.deepStrictEqual(
      results.getFailedAsserts(),
      ["foo", "bar"],
      "two asserts are not meet"
    );
  });
});

describe("Setters and getters", () => {
  const results = new Results();

  it("setUrl/getUrl", () => {
    const URL = "https://example.com";
    results.setUrl(URL);
    assert.strictEqual(results.getUrl(), URL);
  });

  it("setGenerator/getGenerator", () => {
    const GENERATOR = "phantomas/" + require("../.").version;
    results.setGenerator(GENERATOR);
    assert.strictEqual(results.getGenerator(), GENERATOR);
  });
});

describe("Results", () => {
  const results = new Results({
    generator: "phantomas/1.2.3",
    asserts: { metric: 40 },
    metrics: { metric: 42, foo: "bar" },
    offenders: { foo: ["bar is foo"] },
    url: "https://example.com",
  });

  it("are pre-filled", () => {
    assert.strictEqual(results.getGenerator(), "phantomas/1.2.3");
    assert.strictEqual(results.getMetric("foo"), "bar");
    assert.ok(results.assert("metric") === false, "metric > 40");
    assert.deepStrictEqual(results.getOffenders("foo"), ["bar is foo"]);
    assert.strictEqual(results.getUrl(), "https://example.com");
  });
});
<commit_msg>core/results.js nowts.js100% code coverage, yay!<commit_after>/**
 * Tests results wrapper and asserts API
 */
var assert = require("assert"),
  Results = require("../core/results");

const { describe, it } = require("@jest/globals");

describe("Metrics", () => {
  const results = new Results();

  it("should be set to zero by default", () => {
    results.setMetric("foo");
    assert.strictEqual(results.getMetric("foo"), 0);
  });

  it("should be correctly set", () => {
    results.setMetric("foo", "bar");
    assert.strictEqual(results.getMetric("foo"), "bar");
  });

  it("avarage should be correctly calculated", () => {
    results.addToAvgMetric("foo", 2);
    results.addToAvgMetric("foo", 1);
    results.addToAvgMetric("bar", 4);
    assert.strictEqual(results.getMetric("foo"), 1.5);
    assert.strictEqual(results.getMetric("bar"), 4);
  });

  it("should be correctly set (with no casting)", () => {
    results.setMetric("bar", null);
    assert.strictEqual(results.getMetric("bar"), null);
  });

  it("should return the list of registered metrics", () => {
    assert.deepStrictEqual(results.getMetricsNames(), ["foo", "bar"]);
  });

  it("should return values of metrics", () => {
    results.setMetric("foo", "bar");
    results.setMetric("bar", 42);

    assert.deepStrictEqual(results.getMetrics(), {
      foo: "bar",
      bar: 42,
    });
  });

  it("should increment a metric", () => {
    results.setMetric("bar", 42);

    results.incrMetric("bar");
    assert.strictEqual(results.getMetric("bar"), 43);

    results.incrMetric("bar", 10);
    assert.strictEqual(results.getMetric("bar"), 53);
  });

  it("should increment even not existing metric", () => {
    results.incrMetric("not-existing-metric");
    assert.strictEqual(results.getMetric("not-existing-metric"), 1);
  });
});

describe("Offenders", () => {
  const results = new Results();

  it("should be registered", () => {
    results.addOffender("metric", "foo");
    results.addOffender("metric", { url: "bar", size: 42 });
    results.setMetric("metric", 42);

    results.addOffender("metric2", "test");

    assert.deepStrictEqual(results.getAllOffenders(), {
      metric: ["foo", { url: "bar", size: 42 }],
      metric2: ["test"],
    });
  });

  it("should be kept in order", () => {
    assert.deepStrictEqual(results.getOffenders("metric"), [
      "foo",
      { url: "bar", size: 42 },
    ]);
    assert.deepStrictEqual(results.getOffenders("metric2"), ["test"]);

    assert.strictEqual("undefined", typeof results.getOffenders("metric3"));
  });
});

describe("Asserts", () => {
  const results = new Results();

  it("should be correctly registered", () => {
    results.setAsserts({
      foo: 123,
      bar: 0,
    });
    assert.deepStrictEqual(results.getAsserts(), {
      foo: 123,
      bar: 0,
    });

    assert.ok(results.hasAssertion("foo"));
    assert.ok(results.hasAssertion("test") === false);

    assert.strictEqual(results.getAssertion("foo"), 123);
  });

  it("should be correctly processed", () => {
    results.setAsserts({
      foo: 123,
      bar: 0,
    });

    results.setMetric("foo", 123);
    assert.ok(results.assert("foo") === true, "foo lte 123");

    results.setMetric("foo", 124);
    assert.ok(results.assert("foo") === false, "foo is not lte 123");

    results.setMetric("test", 200);
    assert.ok(
      results.hasAssertion("test") === false,
      "no assert for test metric"
    );
    assert.ok(results.assert("test"), "no assert for test metric");
  });

  it("can be added on the fly", () => {
    results.setMetric("foo", 125);
    assert.ok(results.assert("foo") === false, "foo is lte 123");

    results.setAssert("foo", 200);
    assert.ok(results.assert("foo"), "foo is lte 200");
  });

  it("should always be meet for non-numeric values", () => {
    results.setAssert("foo", 200);

    results.setMetric("foo", "1.9.2");
    assert.ok(results.assert("foo"), "string assert");

    results.setMetric("foo", false);
    assert.ok(results.assert("foo"), "bool assert");
  });

  it("should be correctly reported", () => {
    results.setAsserts({
      foo: 123,
      bar: 0,
    });

    results.setMetric("foo", 123);
    results.setMetric("bar", 0);
    assert.deepStrictEqual(
      results.getFailedAsserts(),
      [],
      "all asserts are meet"
    );

    results.setMetric("foo", 124);
    results.setMetric("bar", 0);
    assert.deepStrictEqual(
      results.getFailedAsserts(),
      ["foo"],
      "one assert is not meet"
    );

    results.setMetric("foo", 124);
    results.setMetric("bar", 1);
    assert.deepStrictEqual(
      results.getFailedAsserts(),
      ["foo", "bar"],
      "two asserts are not meet"
    );
  });
});

describe("Setters and getters", () => {
  const results = new Results();

  it("setUrl/getUrl", () => {
    const URL = "https://example.com";
    results.setUrl(URL);
    assert.strictEqual(results.getUrl(), URL);
  });

  it("setGenerator/getGenerator", () => {
    const GENERATOR = "phantomas/" + require("../.").version;
    results.setGenerator(GENERATOR);
    assert.strictEqual(results.getGenerator(), GENERATOR);
  });
});

describe("Results", () => {
  const results = new Results({
    generator: "phantomas/1.2.3",
    asserts: { metric: 40 },
    metrics: { metric: 42, foo: "bar" },
    offenders: { foo: ["bar is foo"] },
    url: "https://example.com",
  });

  it("are pre-filled", () => {
    assert.strictEqual(results.getGenerator(), "phantomas/1.2.3");
    assert.strictEqual(results.getMetric("foo"), "bar");
    assert.ok(results.assert("metric") === false, "metric > 40");
    assert.deepStrictEqual(results.getOffenders("foo"), ["bar is foo"]);
    assert.strictEqual(results.getUrl(), "https://example.com");
  });

  it("defaults asserts entry to {}", () => {
    const results = new Results({});

    assert.deepStrictEqual(results.getAsserts(), {});
  });

  it("setAsserts() defaults to {}", () => {
    const results = new Results({});

    results.setAsserts({ foo: 42 });
    assert.deepStrictEqual(results.getAsserts(), { foo: 42 });

    results.setAsserts();
    assert.deepStrictEqual(results.getAsserts(), {});
  });
});
<|endoftext|>


<commit_before>'use strict';

// MODULES //

var bench = require( '@stdlib/bench' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var pow = require( '@stdlib/math/base/special/pow' );
var pkg = require( './../package.json' ).name;
var isNumericArray = require( './../lib' );

// FUNCTIONS //

/**
* Creates a benchmark function.
*
* @private
* @param {PositiveInteger} len - array length
* @returns {Function} benchmark function
*/
function createBenchmark( len ) {
	var x;
	var i;

	x = [];
	for ( i = 0; i < len; i++ ) {
		x.push( 1.0 );
	}
	return benchmark;

	/**
	* Benchmark function.
	*
	* @private
	* @param {Benchmark} b - benchmark instance
	*/
	function benchmark( b ) {
		var bool;
		var i;

		b.tic();
		for ( i = 0; i < b.iterations; i++ ) {
			// Note: we are testing the worst case scenario where a function must scan the entire array before finding a failing value.
			x[ x.length ] = String.fromCharCode( i % 126 );
			bool = isNumericArray( x );
			if ( !isBoolean( bool ) ) {
				b.fail( 'should return a boolean' );
			}
		}
		b.toc();
		if ( isBoolean( bool ) ) {
			b.pass( 'benchmark finished' );
		} else {
			b.fail( 'should return a boolean' );
		}
		b.end();
	} // end FUNCTION benchmark()
} // end FUNCTION createBenchmark()

// MAIN //

/**
* Main execution sequence.
*
* @private
*/
function main() {
	var len;
	var min;
	var max;
	var f;
	var i;

	min = 1; // 10^min
	max = 6; // 10^max

	for ( i = min; i <= max; i++ ) {
		len = pow( 10, i );
		f = createBenchmark( len );
		bench( pkg+':len='+len, f );
	}
} // end FUNCTION main()

main();
<commit_msg>Fix index<commit_after>'use strict';

// MODULES //

var bench = require( '@stdlib/bench' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var pow = require( '@stdlib/math/base/special/pow' );
var pkg = require( './../package.json' ).name;
var isNumericArray = require( './../lib' );

// FUNCTIONS //

/**
* Creates a benchmark function.
*
* @private
* @param {PositiveInteger} len - array length
* @returns {Function} benchmark function
*/
function createBenchmark( len ) {
	var x;
	var i;

	x = [];
	for ( i = 0; i < len; i++ ) {
		x.push( 1.0 );
	}
	return benchmark;

	/**
	* Benchmark function.
	*
	* @private
	* @param {Benchmark} b - benchmark instance
	*/
	function benchmark( b ) {
		var bool;
		var i;

		b.tic();
		for ( i = 0; i < b.iterations; i++ ) {
			// Note: we are testing the worst case scenario where a function must scan the entire array before finding a failing value.
			x[ len-1 ] = String.fromCharCode( i % 126 );
			bool = isNumericArray( x );
			if ( !isBoolean( bool ) ) {
				b.fail( 'should return a boolean' );
			}
		}
		b.toc();
		if ( isBoolean( bool ) ) {
			b.pass( 'benchmark finished' );
		} else {
			b.fail( 'should return a boolean' );
		}
		b.end();
	} // end FUNCTION benchmark()
} // end FUNCTION createBenchmark()

// MAIN //

/**
* Main execution sequence.
*
* @private
*/
function main() {
	var len;
	var min;
	var max;
	var f;
	var i;

	min = 1; // 10^min
	max = 6; // 10^max

	for ( i = min; i <= max; i++ ) {
		len = pow( 10, i );
		f = createBenchmark( len );
		bench( pkg+':len='+len, f );
	}
} // end FUNCTION main()

main();
<|endoftext|>


<commit_before>'use strict';

// MODULES //

var tape = require( 'tape' );
var isnan = require( '@stdlib/math/base/utils/is-nan' );
var exp = require( '@stdlib/math/base/special/exp' );
var mgf = require( './../lib' );

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.equal( typeof mgf, 'function', 'main export is a function' );
	t.end();
});

tape( 'if provided `NaN` for any parameter, the function returns `NaN`', function test( t ) {
	var y;

	y = mgf( NaN, 0.0 );
	t.equal( isnan( y ), true, 'returns NaN' );

	y = mgf( 0.0, NaN );
	t.equal( isnan( y ), true, 'returns NaN' );

	t.end();
});

tape( 'the function evaluates the MGF of a degenerate distribution centered at `mu`', function test( t ) {
	var mu;
	var x;
	var y;

	mu = 0.0;
	x = 2.0;
	y = mgf( x, mu );
	t.equal( y, exp( x * mu ), 'returns exp( t * mu )' );

	mu = 2.0;
	x = 1.0;
	y = mgf( x, mu );
	t.equal( y, exp( x * mu ), 'returns exp( t * mu )' );

	x = 3.0;
	y = mgf( x, mu );
	t.equal( y, exp( x * mu ), 'returns exp( t * mu )' );

	t.end();
});
<commit_msg>Add test case and update test assertion messages<commit_after>'use strict';

// MODULES //

var tape = require( 'tape' );
var isnan = require( '@stdlib/math/base/utils/is-nan' );
var exp = require( '@stdlib/math/base/special/exp' );
var mgf = require( './../lib' );

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.equal( typeof mgf, 'function', 'main export is a function' );
	t.end();
});

tape( 'if provided `NaN` for any parameter, the function returns `NaN`', function test( t ) {
	var y;

	y = mgf( NaN, 0.0 );
	t.equal( isnan( y ), true, 'returns NaN' );

	y = mgf( 0.0, NaN );
	t.equal( isnan( y ), true, 'returns NaN' );

	y = mgf( NaN, NaN );
	t.equal( isnan( y ), true, 'returns NaN' );

	t.end();
});

tape( 'the function evaluates the MGF of a degenerate distribution centered at `mu`', function test( t ) {
	var mu;
	var x;
	var y;

	mu = 0.0;
	x = 2.0;
	y = mgf( x, mu );
	t.equal( y, exp( x*mu ), 'returns expected value' );

	mu = 2.0;
	x = 1.0;
	y = mgf( x, mu );
	t.equal( y, exp( x*mu ), 'returns expected value' );

	x = 3.0;
	y = mgf( x, mu );
	t.equal( y, exp( x*mu ), 'returns expected value' );

	t.end();
});
<|endoftext|>


<commit_before>'use strict';

// MODULES //

var ceil = require( '@stdlib/math/base/special/ceil' );
var isNumber = require( '@stdlib/utils/is-number' ).isPrimitive;
var isnan = require( '@stdlib/math/base/utils/is-nan' );
var MAX_LENGTH = require( '@stdlib/math/constants/uint32-max' );

// MAIN //

/**
* Generates a linearly spaced numeric array using a provided increment.
*
* @param {number} start - first array value
* @param {number} stop - array element bound
* @param {number} [increment] - increment
* @throws {TypeError} first argument must be numeric
* @throws {TypeError} second argument must be numeric
* @throws {TypeError} third argument must be numeric
* @throws {RangeError} length of created array must be less than 4294967295 (2**32 - 1)
* @returns {Array} linearly spaced numeric array
*/
function incrspace( x1, x2, increment ) {
	var arr;
	var len;
	var inc;
	var i;
	if ( !isNumber( x1 ) || isnan( x1 ) ) {
		throw new TypeError( 'invalid input argument. Start must be numeric. Value: `' + x1 + '`.' );
	}
	if ( !isNumber( x2 ) || isnan( x2 ) ) {
		throw new TypeError( 'invalid input argument. Stop must be numeric. Value: `' + x2 + '`.' );
	}
	if ( arguments.length < 3 ) {
		inc = 1;
	} else {
		inc = increment;
		if ( !isNumber( inc ) || isnan( inc ) ) {
			throw new TypeError( 'invalid input argument. Increment must be numeric. Value: `' + inc + '`.' );
		}
	}
	len = ceil( ( x2-x1 ) / inc );

	if ( len > MAX_LENGTH ) {
		throw new RangeError( 'invalid input arguments. Generated array exceeds maximum array length.' );
	}
	if ( len <= 1 ) {
		return [ x1 ];
	}
	if ( len > 64000 ) {
		// Ensure fast elements...
		arr = [];
		arr.push( x1 );
		for ( i = 1; i < len; i++ ) {
			arr.push( x1 + inc*i );
		}
	} else {
		arr = new Array( len );
		arr[ 0 ] = x1;
		for ( i = 1; i < len; i++ ) {
			arr[ i ] = x1 + inc*i;
		}
	}
	return arr;
} // end FUNCTION incrspace()

// EXPORTS //

module.exports = incrspace;
<commit_msg>Fix lint errors<commit_after>'use strict';

// MODULES //

var ceil = require( '@stdlib/math/base/special/ceil' );
var isNumber = require( '@stdlib/utils/is-number' ).isPrimitive;
var isnan = require( '@stdlib/math/base/utils/is-nan' );
var MAX_LENGTH = require( '@stdlib/math/constants/uint32-max' );

// MAIN //

/**
* Generates a linearly spaced numeric array using a provided increment.
*
* @param {number} x1 - first array value
* @param {number} x2 - array element bound
* @param {number} [increment] - increment
* @throws {TypeError} first argument must be numeric
* @throws {TypeError} second argument must be numeric
* @throws {TypeError} third argument must be numeric
* @throws {RangeError} length of created array must be less than `4294967295` (`2**32 - 1`)
* @returns {Array} linearly spaced numeric array
*/
function incrspace( x1, x2, increment ) {
	var arr;
	var len;
	var inc;
	var i;
	if ( !isNumber( x1 ) || isnan( x1 ) ) {
		throw new TypeError( 'invalid input argument. Start must be numeric. Value: `' + x1 + '`.' );
	}
	if ( !isNumber( x2 ) || isnan( x2 ) ) {
		throw new TypeError( 'invalid input argument. Stop must be numeric. Value: `' + x2 + '`.' );
	}
	if ( arguments.length < 3 ) {
		inc = 1;
	} else {
		inc = increment;
		if ( !isNumber( inc ) || isnan( inc ) ) {
			throw new TypeError( 'invalid input argument. Increment must be numeric. Value: `' + inc + '`.' );
		}
	}
	len = ceil( ( x2-x1 ) / inc );

	if ( len > MAX_LENGTH ) {
		throw new RangeError( 'invalid input arguments. Generated array exceeds maximum array length.' );
	}
	if ( len <= 1 ) {
		return [ x1 ];
	}
	if ( len > 64000 ) {
		// Ensure fast elements...
		arr = [];
		arr.push( x1 );
		for ( i = 1; i < len; i++ ) {
			arr.push( x1 + (inc*i) );
		}
	} else {
		arr = new Array( len );
		arr[ 0 ] = x1;
		for ( i = 1; i < len; i++ ) {
			arr[ i ] = x1 + (inc*i);
		}
	}
	return arr;
} // end FUNCTION incrspace()

// EXPORTS //

module.exports = incrspace;
<|endoftext|>


<commit_before>
require("glob-loader!dir.pattern");
<commit_msg>Fix require<commit_after>
require("glob-loader!./dir.pattern");
<|endoftext|>


<commit_before>function Token(value, definition) {
    this.value = value;
    this.definition = definition;
    this.evaluate = function() {
        return this.definition.evaluator.apply(this, arguments);
    }
}

function TokenFactory(definitions) {
    this.tokenDefinitions = {};

    //Operators
    this.tokenDefinitions[TokenFactory.prototype.OPERATOR] = {
        '^': {
            value: '^',
            precedence: 2,
            type: TokenFactory.prototype.OPERATOR,
            evaluator: () => {
                return this.value;
            }
        }
    };

    //Numbers
    this.tokenDefinitions[TokenFactory.prototype.NUMBER] = {};
    this.tokenDefinitions[TokenFactory.prototype.NUMBER][TokenFactory.prototype.NUMBER] = {
        value: null,
        precedence: 0,
        type: TokenFactory.prototype.NUMBER,
        evaluator: () => {
            return this.value;
        }
    };

    //Variables
    this.tokenDefinitions[TokenFactory.prototype.VARIABLE] = {};
    this.tokenDefinitions[TokenFactory.prototype.VARIABLE][TokenFactory.prototype.VARIABLE] = {
        value: null,
        precedence: 0,
        type: TokenFactory.prototype.VARIABLE,
        evaluator: () => {
            return this.value;
        }
    };

    //Functions
    this.tokenDefinitions[TokenFactory.prototype.FUNCTION] = {
        sin: {
            value: 'sin',
            precedence: 0,
            type: TokenFactory.prototype.FUNCTION,
            evaluator: (n) => {
                var n = parseFloat(n);
                if(isNaN(n)) { throw 'Incorrect argument types'; }
                return Math.sin(n);
            }
        },
        cos: {
            value: 'cos',
            precedence: 0,
            type: TokenFactory.prototype.FUNCTION,
            evaluator: (n) => {
                var n = parseFloat(n);
                if(isNaN(n)) { throw 'Incorrect argument types'; }
                return Math.cos(n);
            }
        },
        tan: {
            value: 'tan',
            precedence: 0,
            type: TokenFactory.prototype.FUNCTION,
            evaluator: (n) => {
                var n = parseFloat(n);
                if(isNaN(n)) { throw 'Incorrect argument types'; }
                return Math.tan(n);
            }
        }
    };

    //Constants
    this.tokenDefinitions[TokenFactory.prototype.CONSTANT] = {
        pi: {
            value: 'pi',
            precedence: 0,
            type: TokenFactory.prototype.FUNCTION,
            evaluator: () => {
                return Math.PI;
            }
        }
    };

    //Extend the definitions with any user supplied definitions
    this.tokenDefinitions = Object.assign(this.tokenDefinitions, definitions);

    this.tokenDefinitionMap = {};

    for(td in this.tokenDefinitions) {
        Object.assign(this.tokenDefinitionMap, this.tokenDefinitions[td]);
    }

    //Retrieve the token values for use in our regex
    var functions = Object.keys(this.tokenDefinitions[TokenFactory.prototype.FUNCTION]);
    var operators = Object.keys(this.tokenDefinitions[TokenFactory.prototype.OPERATOR]);
    var constants = Object.keys(this.tokenDefinitions[TokenFactory.prototype.CONSTANT]);
}

TokenFactory.prototype.OPERATOR = 'operator';
TokenFactory.prototype.VARIABLE = 'variable';
TokenFactory.prototype.NUMBER = 'number';
TokenFactory.prototype.FUNCTION = 'function';
TokenFactory.prototype.CONSTANT = 'constant';

TokenFactory.prototype.getFunctionValues = function() {
    return Object.keys(this.tokenDefinitions[TokenFactory.prototype.FUNCTION]);

}

TokenFactory.prototype.getConstantValues = function() {
    return Object.keys(this.tokenDefinitions[TokenFactory.prototype.CONSTANT]);
}

TokenFactory.prototype.getOperatorValues = function() {
    return Object.keys(this.tokenDefinitions[TokenFactory.prototype.OPERATOR]);
}

TokenFactory.prototype.createToken = function(value) {

    //Look up the token definition by value
    var definition = this.tokenDefinitionMap.hasOwnProperty(value) ? this.tokenDefinitionMap[value] : null;

    if(!definition) {
        var numeric = !isNaN(parseFloat(value));
        if(!numeric) {
            definition = this.tokenDefinitionMap[TokenFactory.prototype.VARIABLE];
        } else {
            definition = this.tokenDefinitionMap[TokenFactory.prototype.NUMBER];
        }
    }

    return new Token(value, definition);

}

module.exports = TokenFactory;<commit_msg>add definitions back<commit_after>function Token(value, definition) {
    this.value = value;
    this.definition = definition;
    this.evaluate = function() {
        return this.definition.evaluator.apply(this, arguments);
    }
}

function TokenFactory(definitions) {

    this.tokenDefinitions = {};

    //Operators
    this.tokenDefinitions[TokenFactory.prototype.OPERATOR] = {
         '^': {
            value: '^',
            precedence: 2,
            type: TokenFactory.prototype.OPERATOR,
            evaluator: (a, b) => {
                a = parseFloat(a);
                b = parseFloat(b);
                if(isNaN(a) || isNaN(b)) { throw 'Incorrect argument types'; }
                return Math.pow(a, b);
            }
        },
        '/': {
            value: '/',
            precedence: 1,
            type: TokenFactory.prototype.OPERATOR,
            evaluator: (a, b) => {
                a = parseFloat(a);
                b = parseFloat(b);
                if(isNaN(a) || isNaN(b)) { throw 'Incorrect argument types'; }
                return a / b;
            }
        },
        '*': {
            value: '*',
            precedence: 1,
            type: TokenFactory.prototype.OPERATOR,
            evaluator: (a, b) => {
                a = parseFloat(a);
                b = parseFloat(b);
                if(isNaN(a) || isNaN(b)) { throw 'Incorrect argument types'; }
                return a * b;
            }
        },
        '-': {
            value: '-',
            precedence: 0,
            type: TokenFactory.prototype.OPERATOR,
            evaluator: (a, b) => {
                a = parseFloat(a);
                b = parseFloat(b);
                if(isNaN(a) || isNaN(b)) { throw 'Incorrect argument types'; }
                return a - b;
            }
        },
        '+': {
            value: '+',
            precedence: 0,
            type: TokenFactory.prototype.OPERATOR,
            evaluator: (a, b) => {
                a = parseFloat(a);
                b = parseFloat(b);
                if(isNaN(a) || isNaN(b)) { throw 'Incorrect argument types'; }
                return a + b;
            }
        },
        '=': {
            value: '=',
            precedence: 0,
            type: TokenFactory.prototype.OPERATOR,
            evaluator: () => {
                return this.value;
            }
        },
        '(': {
            value: '(',
            precedence: 0,
            type: TokenFactory.prototype.OPERATOR,
            evaluator: () => {
                return this.value;
            }
        },
        ')': {
            value: ')',
            precedence: 0,
            type: TokenFactory.prototype.OPERATOR,
            evaluator: () => {
                return this.value;
            }
        },
        ',': {
            value: ',',
            precedence: 0,
            type: TokenFactory.prototype.OPERATOR,
            evaluator: () => {
                return this.value;
            }
        }
    };

    //Numbers
    this.tokenDefinitions[TokenFactory.prototype.NUMBER] = {};
    this.tokenDefinitions[TokenFactory.prototype.NUMBER][TokenFactory.prototype.NUMBER] = {
        value: null,
        precedence: 0,
        type: TokenFactory.prototype.NUMBER,
        evaluator: () => {
            return this.value;
        }
    };

    //Variables
    this.tokenDefinitions[TokenFactory.prototype.VARIABLE] = {};
    this.tokenDefinitions[TokenFactory.prototype.VARIABLE][TokenFactory.prototype.VARIABLE] = {
        value: null,
        precedence: 0,
        type: TokenFactory.prototype.VARIABLE,
        evaluator: () => {
            return this.value;
        }
    };

    //Functions
    this.tokenDefinitions[TokenFactory.prototype.FUNCTION] = {
        sin: {
            value: 'sin',
            precedence: 0,
            type: TokenFactory.prototype.FUNCTION,
            evaluator: (n) => {
                var n = parseFloat(n);
                if(isNaN(n)) { throw 'Incorrect argument types'; }
                return Math.sin(n);
            }
        },
        cos: {
            value: 'cos',
            precedence: 0,
            type: TokenFactory.prototype.FUNCTION,
            evaluator: (n) => {
                var n = parseFloat(n);
                if(isNaN(n)) { throw 'Incorrect argument types'; }
                return Math.cos(n);
            }
        },
        tan: {
            value: 'tan',
            precedence: 0,
            type: TokenFactory.prototype.FUNCTION,
            evaluator: (n) => {
                var n = parseFloat(n);
                if(isNaN(n)) { throw 'Incorrect argument types'; }
                return Math.tan(n);
            }
        }
    };

    //Constants
    this.tokenDefinitions[TokenFactory.prototype.CONSTANT] = {
        pi: {
            value: 'pi',
            precedence: 0,
            type: TokenFactory.prototype.FUNCTION,
            evaluator: () => {
                return Math.PI;
            }
        }
    };

    //Extend the definitions with any user supplied definitions
    this.tokenDefinitions = Object.assign(this.tokenDefinitions, definitions);

    this.tokenDefinitionMap = {};

    for(td in this.tokenDefinitions) {
        Object.assign(this.tokenDefinitionMap, this.tokenDefinitions[td]);
    }

    //Retrieve the token values for use in our regex
    var functions = Object.keys(this.tokenDefinitions[TokenFactory.prototype.FUNCTION]);
    var operators = Object.keys(this.tokenDefinitions[TokenFactory.prototype.OPERATOR]);
    var constants = Object.keys(this.tokenDefinitions[TokenFactory.prototype.CONSTANT]);
}

TokenFactory.prototype.OPERATOR = 'operator';
TokenFactory.prototype.VARIABLE = 'variable';
TokenFactory.prototype.NUMBER = 'number';
TokenFactory.prototype.FUNCTION = 'function';
TokenFactory.prototype.CONSTANT = 'constant';

TokenFactory.prototype.getFunctionValues = function() {
    return Object.keys(this.tokenDefinitions[TokenFactory.prototype.FUNCTION]);

}

TokenFactory.prototype.getConstantValues = function() {
    return Object.keys(this.tokenDefinitions[TokenFactory.prototype.CONSTANT]);
}

TokenFactory.prototype.getOperatorValues = function() {
    return Object.keys(this.tokenDefinitions[TokenFactory.prototype.OPERATOR]);
}

TokenFactory.prototype.createToken = function(value) {

    //Look up the token definition by value
    var definition = this.tokenDefinitionMap.hasOwnProperty(value) ? this.tokenDefinitionMap[value] : null;

    if(!definition) {
        var numeric = !isNaN(parseFloat(value));
        if(!numeric) {
            definition = this.tokenDefinitionMap[TokenFactory.prototype.VARIABLE];
        } else {
            definition = this.tokenDefinitionMap[TokenFactory.prototype.NUMBER];
        }
    }

    return new Token(value, definition);

}

module.exports = TokenFactory;<|endoftext|>


<commit_before>'use strict';

require('../test-helper');

/* global bootstrapModeler, inject */

var pick = require('lodash/object/pick');

var fs = require('fs');

var modelingModule = require('bpmn-js/lib/features/modeling'),
    coreModule = require('bpmn-js/lib/core'),
    cliModule = require('../../');

describe('cli', function() {

  var startDiagramXML = fs.readFileSync('resources/start.bpmn', 'utf8');
  var simpleDiagramXML = fs.readFileSync('resources/simple.bpmn', 'utf8');

  var testModules = [ coreModule, cliModule, modelingModule ];

  describe('bootstrap', function() {

    beforeEach(bootstrapModeler(startDiagramXML, {
      modules: testModules,
      cli: {
        bindTo: 'cli'
      }
    }));

    it('should bind to window', inject(function(cli) {
      expect(window.cli).to.equal(cli);
    }));

  });

  describe('model', function() {

    beforeEach(bootstrapModeler(startDiagramXML, {
      modules: testModules,
      cli: {
        bindTo: 'cli'
      }
    }));

    it('should model process', inject(function(cli) {

      // elements
      var elements = cli.elements();

      // then
      expect(elements).to.eql([
        'Process_1',
        'StartEvent_1',
        'StartEvent_1_label'
      ]);

      // element
      var startEventElement = cli.element('StartEvent_1');

      // then
      expect(startEventElement.id).to.equal('StartEvent_1');

      // move
      var startEventPos = pick(startEventElement, [ 'x', 'y' ]);
      cli.move('StartEvent_1', '0,100');

      // then
      expect(startEventElement.x).to.equal(startEventPos.x);
      expect(startEventElement.y).to.equal(startEventPos.y + 100);

      // append
      var orGateway = cli.append(
        'StartEvent_1',
        'bpmn:InclusiveGateway',
        { x: 150, y: 0 }
      );

      // then
      expect(orGateway).to.exist;

      // set label
      cli.setLabel(orGateway, 'You have to decide');

      // then
      expect(cli.element(orGateway).businessObject.name).to.equal('You have to decide');

      // append user task
      var userTask = cli.append(orGateway, 'bpmn:UserTask 150,0');

      // then
      expect(userTask).to.exist;

      // continue modeling

      // append gateway
      var gateway = cli.append(userTask, 'bpmn:ExclusiveGateway');

      // append manual task
      var manualTask = cli.append(
        gateway,
        'bpmn:ManualTask',
        { x: 150, y: -70 }
      );

      // append intermediate catch event
      var intermediateCatchEvent = cli.append(
        gateway,
        'bpmn:IntermediateCatchEvent',
        { x: 150, y: 70 }
      );

      // append joining gateway
      var joiningGateway = cli.append(
        manualTask,
        'bpmn:ExclusiveGateway',
        '150,70'
      );

      // connect event -> gateway
      cli.connect(
        intermediateCatchEvent,
        joiningGateway,
        'bpmn:SequenceFlow'
      );

      // create text-annotation next to orGateway
      var orGatewayShape = cli.element(orGateway);

      var textAnnotation = cli.create(
        'bpmn:TextAnnotation',
        {
          x: orGatewayShape.x + 100,
          y: orGatewayShape.y - 100
        },
        orGatewayShape.parent
      );

      cli.setLabel(textAnnotation, 'What do you choose, yes or no?');

      // create association
      cli.connect(orGateway, textAnnotation, 'bpmn:Association');

      // move some nodes
      cli.move([
        joiningGateway,
        orGateway,
        intermediateCatchEvent
      ], '0,30');

      // var
      // export as svg
      cli.save('svg');

      // export as bpmn
      cli.save('bpmn');

    }));
  });

  describe('set label', function() {

    // given that
    beforeEach(bootstrapModeler(simpleDiagramXML, {
      modules: testModules
    }));

    it('should set TextAnnotation label', inject(function(cli) {

      // given
      var textAnnotation = cli.create(
        'bpmn:TextAnnotation',
        {
          x: 100,
          y: 100
        },
        'ID_PROCESS_1'
      );

      var text = 'What do you choose, yes or no?';

      // when
      cli.setLabel(textAnnotation, text);

      // then
      var shape = cli.element(textAnnotation);

      expect(shape.businessObject.text).to.eql(text);
    }));

  });

  describe('remove', function() {

    // given that
    beforeEach(bootstrapModeler(simpleDiagramXML, {
      modules: testModules
    }));

    it('should remove shape', inject(function(cli) {

      // when
      cli.removeShape('ID_TASK_1');

      // then
      var elements = cli.elements();
      expect(elements).to.eql([ 'ID_PROCESS_1', 'ID_TASK_2' ]);
    }));

    it('should remove connection', inject(function(cli) {

      // when
      cli.removeConnection('ID_CONNECTION_1');

      // then
      var elements = cli.elements();
      expect(elements).to.eql([
        'ID_PROCESS_1',
        'ID_TASK_1',
        'ID_TASK_2'
      ]);
    }));

  });

  describe('attach', function() {

    beforeEach(bootstrapModeler(simpleDiagramXML, {
      modules: testModules,
    }));

    it('should create', inject(function(cli) {

      // when
      var newElement = cli.create(
        'bpmn:BoundaryEvent',
        '400,150',
        'ID_TASK_2',
        true
      );

      var connectedTask = cli.append(
        newElement,
        'bpmn:ExclusiveGateway',
        '50,50'
      );

      // then
      var elements = cli.elements();

      expect(elements).to.contain(newElement);
      expect(elements).to.contain(connectedTask);
    }));

    it('should move', inject(function(cli) {

      // given
      var newElement = cli.create(
        'bpmn:BoundaryEvent',
        '400,150',
        'ID_TASK_2',
        true
      );

      cli.append(newElement, 'bpmn:ExclusiveGateway', '50,50');

      // when
      cli.move(newElement, '-200,0', 'ID_TASK_1', true);

      // then
      var taskElement = cli.element('ID_TASK_1');
      var boundaryElement = cli.element(newElement);

      expect(boundaryElement.host).to.eql(taskElement);
    }));

  });

});
<commit_msg>test(cli): verify help command works<commit_after>'use strict';

require('../test-helper');

/* global bootstrapModeler, inject */

var pick = require('lodash/object/pick');

var fs = require('fs');

var modelingModule = require('bpmn-js/lib/features/modeling'),
    coreModule = require('bpmn-js/lib/core'),
    cliModule = require('../../');

describe('cli', function() {

  var startDiagramXML = fs.readFileSync('resources/start.bpmn', 'utf8');
  var simpleDiagramXML = fs.readFileSync('resources/simple.bpmn', 'utf8');

  var testModules = [ coreModule, cliModule, modelingModule ];

  describe('bootstrap', function() {

    beforeEach(bootstrapModeler(startDiagramXML, {
      modules: testModules,
      cli: {
        bindTo: 'cli'
      }
    }));

    it('should bind to window', inject(function(cli) {
      expect(window.cli).to.equal(cli);
    }));

  });

  describe('model', function() {

    beforeEach(bootstrapModeler(startDiagramXML, {
      modules: testModules,
      cli: {
        bindTo: 'cli'
      }
    }));

    it('should model process', inject(function(cli) {

      // elements
      var elements = cli.elements();

      // then
      expect(elements).to.eql([
        'Process_1',
        'StartEvent_1',
        'StartEvent_1_label'
      ]);

      // element
      var startEventElement = cli.element('StartEvent_1');

      // then
      expect(startEventElement.id).to.equal('StartEvent_1');

      // move
      var startEventPos = pick(startEventElement, [ 'x', 'y' ]);
      cli.move('StartEvent_1', '0,100');

      // then
      expect(startEventElement.x).to.equal(startEventPos.x);
      expect(startEventElement.y).to.equal(startEventPos.y + 100);

      // append
      var orGateway = cli.append(
        'StartEvent_1',
        'bpmn:InclusiveGateway',
        { x: 150, y: 0 }
      );

      // then
      expect(orGateway).to.exist;

      // set label
      cli.setLabel(orGateway, 'You have to decide');

      // then
      expect(cli.element(orGateway).businessObject.name).to.equal('You have to decide');

      // append user task
      var userTask = cli.append(orGateway, 'bpmn:UserTask 150,0');

      // then
      expect(userTask).to.exist;

      // continue modeling

      // append gateway
      var gateway = cli.append(userTask, 'bpmn:ExclusiveGateway');

      // append manual task
      var manualTask = cli.append(
        gateway,
        'bpmn:ManualTask',
        { x: 150, y: -70 }
      );

      // append intermediate catch event
      var intermediateCatchEvent = cli.append(
        gateway,
        'bpmn:IntermediateCatchEvent',
        { x: 150, y: 70 }
      );

      // append joining gateway
      var joiningGateway = cli.append(
        manualTask,
        'bpmn:ExclusiveGateway',
        '150,70'
      );

      // connect event -> gateway
      cli.connect(
        intermediateCatchEvent,
        joiningGateway,
        'bpmn:SequenceFlow'
      );

      // create text-annotation next to orGateway
      var orGatewayShape = cli.element(orGateway);

      var textAnnotation = cli.create(
        'bpmn:TextAnnotation',
        {
          x: orGatewayShape.x + 100,
          y: orGatewayShape.y - 100
        },
        orGatewayShape.parent
      );

      cli.setLabel(textAnnotation, 'What do you choose, yes or no?');

      // create association
      cli.connect(orGateway, textAnnotation, 'bpmn:Association');

      // move some nodes
      cli.move([
        joiningGateway,
        orGateway,
        intermediateCatchEvent
      ], '0,30');

      // var
      // export as svg
      cli.save('svg');

      // export as bpmn
      cli.save('bpmn');

    }));

  });

  describe('set label', function() {

    // given that
    beforeEach(bootstrapModeler(simpleDiagramXML, {
      modules: testModules
    }));

    it('should set TextAnnotation label', inject(function(cli) {

      // given
      var textAnnotation = cli.create(
        'bpmn:TextAnnotation',
        {
          x: 100,
          y: 100
        },
        'ID_PROCESS_1'
      );

      var text = 'What do you choose, yes or no?';

      // when
      cli.setLabel(textAnnotation, text);

      // then
      var shape = cli.element(textAnnotation);

      expect(shape.businessObject.text).to.eql(text);
    }));

  });

  describe('help', function() {

    // given that
    beforeEach(bootstrapModeler(simpleDiagramXML, {
      modules: testModules
    }));

    it('should show available commands', inject(function(cli) {

      // when
      var helpText = cli.help();

      // then
      expect(helpText).to.match(/available commands:/);

      expect(helpText).to.contain('undo');
      expect(helpText).to.contain('removeShape');
      expect(helpText).to.contain('append');
    }));

  });

  describe('remove', function() {

    // given that
    beforeEach(bootstrapModeler(simpleDiagramXML, {
      modules: testModules
    }));

    it('should remove shape', inject(function(cli) {

      // when
      cli.removeShape('ID_TASK_1');

      // then
      var elements = cli.elements();

      expect(elements).to.eql([
        'ID_PROCESS_1',
        'ID_TASK_2'
      ]);
    }));

    it('should remove connection', inject(function(cli) {

      // when
      cli.removeConnection('ID_CONNECTION_1');

      // then
      var elements = cli.elements();
      expect(elements).to.eql([
        'ID_PROCESS_1',
        'ID_TASK_1',
        'ID_TASK_2'
      ]);
    }));

  });

  describe('attach', function() {

    beforeEach(bootstrapModeler(simpleDiagramXML, {
      modules: testModules,
    }));

    it('should create', inject(function(cli) {

      // when
      var newElement = cli.create(
        'bpmn:BoundaryEvent',
        '400,150',
        'ID_TASK_2',
        true
      );

      var connectedTask = cli.append(
        newElement,
        'bpmn:ExclusiveGateway',
        '50,50'
      );

      // then
      var elements = cli.elements();

      expect(elements).to.contain(newElement);
      expect(elements).to.contain(connectedTask);
    }));

    it('should move', inject(function(cli) {

      // given
      var newElement = cli.create(
        'bpmn:BoundaryEvent',
        '400,150',
        'ID_TASK_2',
        true
      );

      cli.append(newElement, 'bpmn:ExclusiveGateway', '50,50');

      // when
      cli.move(newElement, '-200,0', 'ID_TASK_1', true);

      // then
      var taskElement = cli.element('ID_TASK_1');
      var boundaryElement = cli.element(newElement);

      expect(boundaryElement.host).to.eql(taskElement);
    }));

  });

});
<|endoftext|>


<commit_before>
    basis.require('basis.date');
    basis.require('basis.dom');
    basis.require('basis.dom.event');
    basis.require('basis.data');
    basis.require('basis.entity');

    var MAX_COUNT = 3000;
    var MAX_COUNT_QUATER = MAX_COUNT >> 2;
    var PROFILE = false;

    var DOM = basis.dom;
    var Data = basis.data;
    var nsEntity = basis.entity;

    var getter = basis.getter;
    var arrayFrom = basis.array.from;

    var eventStat = {};

    if (basis.event.Emitter.event)
    {
      function wrapEvent(eventName){
        var func = basis.event.Emitter.event[eventName];
        basis.event.Emitter.event[eventName] = function(){
          eventStat[eventName] = (eventStat[eventName] || 0) + 1;
          func.apply(this, arguments);
        };
      }

      basis.object.keys(basis.event.Emitter.event).forEach(wrapEvent);
    }

    var addCount = 0;
    var removeCount = 0;
    /*var _add = basis.Emitter.prototype.addHandler.method;
    basis.Emitter.prototype.addHandler.method = function(){
      addCount++;
      return _add.apply(this, arguments);
    }/*
    var _remove = basis.Emitter.prototype.removeHandler.method;
    basis.Emitter.prototype.removeHandler.method = function(){
      removeCount++;
      _remove.apply(this, arguments);
    }*/

    function saveEventStat(){
      savedEventStat_ = basis.object.extend({}, eventStat);
    }
    function getEventStat(){
      var res = {};
      for (var event in eventStat)
      {
        if (eventStat[event] != savedEventStat_[event])
          res[event] = eventStat[event] - (savedEventStat_[event] || 0);
      }
      return res;
    }

    basis.fn.$nullOrValue = function(value){
      return value == null ? null : value;
    };

    basis.fn.$nullOrString = function(value){
      return value == null ? null : String(value);
    };

    basis.fn.$nullOrBoolean = function(value){
      return value == null ? null : Boolean(value);
    };

    basis.fn.$date = function(value){
      return value instanceof Date || value == null ? value : basis.date.fromISOString(value);
    };

    basis.fn.$nullOrArray = function(value){
      return value == null || value.length == 0 ? null : arrayFrom(value);
    };

    var User = new nsEntity.EntityType({
      name: 'User',
      id: 'UserId',
      fields: {
        UserId: nsEntity.IntId || basis.fn.def(Number, null, isNaN),
        Title: String,
        Value: Number
      }
    });

    var Currency = new nsEntity.EntityType({
      name: 'Currency',
      id: 'CurrencyId',
      fields: {
        CurrencyId: nsEntity.IntId || basis.fn.def(Number, null, isNaN),
        Code: String,
        Title: String
      }
    });

    var Transfer = new nsEntity.EntityType({
      name: 'Transfer',
      id: 'TransferId',
      fields: {
        TransferId: nsEntity.IntId || basis.fn.def(Number, null, isNaN),
        User: User,
        Amount: Number,
        Currency: Currency,
        Value: Number,
        CreateDate: basis.fn.$date
      }
    });
    Currency.entityType.entityClass.extend({
      behaviour: {
        update: function(){},
        destroy: function(){}
      }
    });
    User.entityType.entityClass.extend({
      behaviour: {
        update: function(){},
        destroy: function(){}
      }
    });
    Transfer.entityType.entityClass.extend({
      behaviour: {
        update: function(){},
        destroy: function(){}
      }
    });

    var date = new Date();
    function test(){
      var st = Date.now();
      for (var i = 1; i <= MAX_COUNT; i++)
      {
        Transfer({
          TransferId: i,
          User: {
            UserId: 1 + (i % MAX_COUNT_QUATER),
            Title: 'User #' + (i % MAX_COUNT_QUATER)
          },
          Amount: i,
          Currency: 1 + (i % 5),
          CreateDate: date
        });
      }
      return Date.now() - st;
    }

    function test_fast_insert(){
      var st = Date.now();
      var data = [];
      for (var i = 1; i <= MAX_COUNT; i++)
      {
        data.push({
          TransferId: i,
          User: {
            UserId: 1 + (i % MAX_COUNT_QUATER),
            Title: 'User #' + (i % MAX_COUNT_QUATER)
          },
          Amount: i,
          Currency: 1 + (i % 5),
          CreateDate: date
        });
      }
      Transfer.all.sync(data);
      return Date.now() - st;
    }

    var uniqValue = 1;
    function test_update(){
      var st = Date.now();
      for (var i = 1; i <= MAX_COUNT; i++)
      {
        Transfer({
          TransferId: i,
          User: {
            Value: Math.random()
          },
          Value: uniqValue++,
          Currency: {
            Title: 'Currency ' + 1 + (i % 5)
          }
        });
      }
      return Date.now() - st;
    }

    function getCount(es){
      if (es.value)
        return es.value.length;
      if (es.items)
        return es.items.length;
      return es.itemCount;
    }
    function clear(){
      var st = Date.now();
      for (var i = 1, cnt = getCount(Transfer.all); i <= cnt; i++)
        Transfer(i).destroy();
      for (var i = 1, cnt = getCount(Currency.all); i <= cnt; i++)
        Currency(i).destroy();
      for (var i = 1, cnt = getCount(User.all); i <= cnt; i++)
        User(i).destroy();
      return Date.now() - st;
    }

    function fast_clear(){
      if (Transfer.all.sync)
      {
        var st = Date.now();
        Transfer.all.sync([]);
        User.all.sync([]);
        Currency.all.sync([]);
        return Date.now() - st;
      }
      else
        return clear();
    }

    var cold_insert = 0;
    var hot_update = 0;
    var hot_update_changes = 0;
    var clear_time = 0;
    var fast_clear_time = 0;

    function run1(func){
      saveEventStat();
      var t1 = test(); var s1 = summary(); var es1 = getEventStatElement();
      saveEventStat();
      var t2 = test(); var s2 = summary(); var es2 = getEventStatElement();
      saveEventStat();
      var t22 = test_update(); var s3 = summary(); var es3 = getEventStatElement();
      saveEventStat();
      var t3 = clear(); var s4 = summary(); var es4 = getEventStatElement();

      cold_insert += t1;
      hot_update += t2;
      hot_update_changes += t22;
      clear_time += t3;

      DOM.insert(document.body, [
        DOM.createElement('hr'),
        DOM.createElement(null, '1st run: ', '{0:.3} sec'.format(t1/1000), s1, es1),
        DOM.createElement(null, '2nd run (no changes): ', '{0:.3} sec'.format(t2/1000), s2, es2),
        DOM.createElement(null, '3rd run (changes): ', '{0:.3} sec'.format(t22/1000), s3, es3),
        DOM.createElement(null, 'Clear all: ', '{0:.3} sec'.format(t3/1000), s4, es4)
      ]);
      setTimeout(func, 50);
    }

    function run2(func){
      saveEventStat();
      var t1 = test_fast_insert(); var s1 = summary(); var es1 = getEventStatElement();
      saveEventStat();
      var t2 = test_fast_insert(); var s2 = summary(); var es2 = getEventStatElement();
      saveEventStat();
      var t22 = test_update(); var s3 = summary(); var es3 = getEventStatElement();
      saveEventStat();
      var t3 = fast_clear(); var s4 = summary(); var es4 = getEventStatElement();

      cold_insert += t1;
      hot_update += t2;
      hot_update_changes += t22;
      fast_clear_time += t3;

      DOM.insert(document.body, [
        DOM.createElement('hr'),
        DOM.createElement(null, '1st run: ', '{0:.3} sec'.format(t1/1000), s1, es1),
        DOM.createElement(null, '2nd run (no changes): ', '{0:.3} sec'.format(t2/1000), s2, es2),
        DOM.createElement(null, '3rd run (changes): ', '{0:.3} sec'.format(t22/1000), s3, es3),
        DOM.createElement(null, 'Fast clear all: ', '{0:.3} sec'.format(t3/1000), s4, es4)
      ]);
      setTimeout(func, 50);
    }

    function summary(){
      return DOM.createElement({
          description: 'SPAN',
          css: {
            display: 'block',
            color: '#888',
            fontSize: '10px',
            padding: '0 2ex'
          }
        },
        [Transfer.all, Currency.all, User.all].map(function(ds, idx){ return ['Transfer', 'Currency', 'User'][idx] + ' ' + getCount(ds); }).join(', ')
      );
    }

    function getEventStatElement(){
      var res = getEventStat();
      return DOM.createElement({
          description: 'SPAN',
          css: {
            display: 'block',
            color: '#D00',
            fontSize: '10px',
            padding: '0 2ex'
          }
        },
        basis.object.iterate(res, basis.string.format, '{0}: +{1}').sort().join(', ')
      );
    }

    function total(){
      DOM.insert(document.body, [
        DOM.createElement('hr'),
        DOM.createElement('H2', 'SCORE: ', '{0:.0}'.format((cold_insert+hot_update+hot_update_changes + 2*clear_time + 2*fast_clear_time)/4)),
        DOM.createElement(null, 'First run: ', '{0:.3} sec'.format(cold_insert/4000)),
        DOM.createElement(null, 'Second run (no changes): ', '{0:.3} sec'.format(hot_update/4000)),
        DOM.createElement(null, 'Second run (changes): ', '{0:.3} sec'.format(hot_update_changes/4000)),
        DOM.createElement(null, 'Clear total: ', '{0:.3} sec'.format(clear_time/2000)),
        DOM.createElement(null, 'Fast clear total: ', '{0:.3} sec'.format(fast_clear_time/2000))
      ]);
    }

    window.c1count = 0;
    window.c2count = 0;

    function run_test(){
      if (PROFILE) console.profile();
      run1(function(){
        run1(function(){
          var c1 = Transfer.createCollection('col1', getter('getId()%2'), Transfer.all);
          var c2 = User.createCollection('col2', getter('getId()%2'), User.all);
          c1.addHandler({ itemsChanged: function(dataset, delta){ c1count += (delta.inserted ? delta.inserted.length : 0) - (delta.deleted ? delta.deleted.length : 0); } });
          c2.addHandler({ itemsChanged: function(dataset, delta){ c2count += (delta.inserted ? delta.inserted.length : 0) - (delta.deleted ? delta.deleted.length : 0); } });
          DOM.insert(document.body, [
            DOM.createElement('hr'),
            DOM.createElement(null, '2 collection added')
          ]);
          run2(function(){
            run2(function(){
              if (PROFILE) console.profileEnd();
              total();
            });
          });
        });
      });
    }

    DOM.insert(document.body,
      runBtn = DOM.createElement({
        description: 'BUTTON',
        click: function(){
          DOM.remove(this);
          run_test();
        }
      }, 'run test')
    );

    if (location.hash == '#autorun')
    {
      basis.Event.onLoad(function(){ runBtn.click(); });
    }<commit_msg>fix entity test<commit_after>
    basis.require('basis.date');
    basis.require('basis.cssom');
    basis.require('basis.dom');
    basis.require('basis.dom.event');
    basis.require('basis.data');
    basis.require('basis.entity');

    var MAX_COUNT = 3000;
    var MAX_COUNT_QUATER = MAX_COUNT >> 2;
    var PROFILE = false;

    var DOM = basis.dom;
    var Data = basis.data;
    var nsEntity = basis.entity;

    var getter = basis.getter;
    var arrayFrom = basis.array.from;

    var eventStat = {};

    basis.event.Emitter.prototype.dispatch_debug = function(event){
      eventStat[event.type] = (eventStat[event.type] || 0) + 1;
    }

    function saveEventStat(){
      savedEventStat_ = basis.object.extend({}, eventStat);
    }
    function getEventStat(){
      var res = {};
      for (var event in eventStat)
      {
        if (eventStat[event] != savedEventStat_[event])
          res[event] = eventStat[event] - (savedEventStat_[event] || 0);
      }
      return res;
    }

    basis.fn.$nullOrValue = function(value){
      return value == null ? null : value;
    };

    basis.fn.$nullOrString = function(value){
      return value == null ? null : String(value);
    };

    basis.fn.$nullOrBoolean = function(value){
      return value == null ? null : Boolean(value);
    };

    basis.fn.$date = function(value){
      return value instanceof Date || value == null ? value : basis.date.fromISOString(value);
    };

    basis.fn.$nullOrArray = function(value){
      return value == null || value.length == 0 ? null : arrayFrom(value);
    };

    var User = new nsEntity.EntityType({
      name: 'User',
      id: 'UserId',
      fields: {
        UserId: nsEntity.IntId || basis.fn.def(Number, null, isNaN),
        Title: String,
        Value: Number
      }
    });

    var Currency = new nsEntity.EntityType({
      name: 'Currency',
      id: 'CurrencyId',
      fields: {
        CurrencyId: nsEntity.IntId || basis.fn.def(Number, null, isNaN),
        Code: String,
        Title: String
      }
    });

    var Transfer = new nsEntity.EntityType({
      name: 'Transfer',
      id: 'TransferId',
      fields: {
        TransferId: nsEntity.IntId || basis.fn.def(Number, null, isNaN),
        User: User,
        Amount: Number,
        Currency: Currency,
        Value: Number,
        CreateDate: basis.fn.$date
      }
    });
    Currency.entityType.entityClass.extend({
      behaviour: {
        update: function(){},
        destroy: function(){}
      }
    });
    User.entityType.entityClass.extend({
      behaviour: {
        update: function(){},
        destroy: function(){}
      }
    });
    Transfer.entityType.entityClass.extend({
      behaviour: {
        update: function(){},
        destroy: function(){}
      }
    });

    var date = new Date();
    function test(){
      var st = Date.now();
      for (var i = 1; i <= MAX_COUNT; i++)
      {
        Transfer({
          TransferId: i,
          User: {
            UserId: 1 + (i % MAX_COUNT_QUATER),
            Title: 'User #' + (i % MAX_COUNT_QUATER)
          },
          Amount: i,
          Currency: 1 + (i % 5),
          CreateDate: date
        });
      }
      return Date.now() - st;
    }

    function test_fast_insert(){
      var st = Date.now();
      var data = [];
      for (var i = 1; i <= MAX_COUNT; i++)
      {
        data.push({
          TransferId: i,
          User: {
            UserId: 1 + (i % MAX_COUNT_QUATER),
            Title: 'User #' + (i % MAX_COUNT_QUATER)
          },
          Amount: i,
          Currency: 1 + (i % 5),
          CreateDate: date
        });
      }
      Transfer.all.sync(data);
      return Date.now() - st;
    }

    var uniqValue = 1;
    function test_update(){
      var st = Date.now();
      for (var i = 1; i <= MAX_COUNT; i++)
      {
        Transfer({
          TransferId: i,
          User: {
            Value: Math.random()
          },
          Value: uniqValue++,
          Currency: {
            Title: 'Currency ' + 1 + (i % 5)
          }
        });
      }
      return Date.now() - st;
    }

    function getCount(es){
      if (es.value)
        return es.value.length;
      if (es.items)
        return es.items.length;
      return es.itemCount;
    }
    function clear(){
      var st = Date.now();
      for (var i = 1, cnt = getCount(Transfer.all); i <= cnt; i++)
        Transfer(i).destroy();
      for (var i = 1, cnt = getCount(Currency.all); i <= cnt; i++)
        Currency(i).destroy();
      for (var i = 1, cnt = getCount(User.all); i <= cnt; i++)
        User(i).destroy();
      return Date.now() - st;
    }

    function fast_clear(){
      if (Transfer.all.sync)
      {
        var st = Date.now();
        Transfer.all.sync([]);
        User.all.sync([]);
        Currency.all.sync([]);
        return Date.now() - st;
      }
      else
        return clear();
    }

    var cold_insert = 0;
    var hot_update = 0;
    var hot_update_changes = 0;
    var clear_time = 0;
    var fast_clear_time = 0;

    function run1(func){
      saveEventStat();
      var t1 = test(); var s1 = summary(); var es1 = getEventStatElement();
      saveEventStat();
      var t2 = test(); var s2 = summary(); var es2 = getEventStatElement();
      saveEventStat();
      var t22 = test_update(); var s3 = summary(); var es3 = getEventStatElement();
      saveEventStat();
      var t3 = clear(); var s4 = summary(); var es4 = getEventStatElement();

      cold_insert += t1;
      hot_update += t2;
      hot_update_changes += t22;
      clear_time += t3;

      DOM.insert(document.body, [
        DOM.createElement('hr'),
        DOM.createElement(null, '1st run: ', '{0:.3} sec'.format(t1/1000), s1, es1),
        DOM.createElement(null, '2nd run (no changes): ', '{0:.3} sec'.format(t2/1000), s2, es2),
        DOM.createElement(null, '3rd run (changes): ', '{0:.3} sec'.format(t22/1000), s3, es3),
        DOM.createElement(null, 'Clear all: ', '{0:.3} sec'.format(t3/1000), s4, es4)
      ]);
      setTimeout(func, 50);
    }

    function run2(func){
      saveEventStat();
      var t1 = test_fast_insert(); var s1 = summary(); var es1 = getEventStatElement();
      saveEventStat();
      var t2 = test_fast_insert(); var s2 = summary(); var es2 = getEventStatElement();
      saveEventStat();
      var t22 = test_update(); var s3 = summary(); var es3 = getEventStatElement();
      saveEventStat();
      var t3 = fast_clear(); var s4 = summary(); var es4 = getEventStatElement();

      cold_insert += t1;
      hot_update += t2;
      hot_update_changes += t22;
      fast_clear_time += t3;

      DOM.insert(document.body, [
        DOM.createElement('hr'),
        DOM.createElement(null, '1st run: ', '{0:.3} sec'.format(t1/1000), s1, es1),
        DOM.createElement(null, '2nd run (no changes): ', '{0:.3} sec'.format(t2/1000), s2, es2),
        DOM.createElement(null, '3rd run (changes): ', '{0:.3} sec'.format(t22/1000), s3, es3),
        DOM.createElement(null, 'Fast clear all: ', '{0:.3} sec'.format(t3/1000), s4, es4)
      ]);
      setTimeout(func, 50);
    }

    function summary(){
      return DOM.createElement({
          description: 'DIV',
          css: {
            display: 'block',
            color: '#888',
            fontSize: '10px',
            padding: '0 2ex'
          }
        },
        [Transfer.all, Currency.all, User.all].map(function(ds, idx){ return ['Transfer', 'Currency', 'User'][idx] + ' ' + getCount(ds); }).join(', ')
      );
    }

    function getEventStatElement(){
      var res = getEventStat();
      return DOM.createElement({
          description: 'SPAN',
          css: {
            display: 'block',
            color: '#D00',
            fontSize: '10px',
            padding: '0 2ex'
          }
        },
        basis.object.iterate(res, basis.string.format, '{0}: +{1}').sort().join(', ')
      );
    }

    function total(){
      DOM.insert(document.body, [
        DOM.createElement('hr'),
        DOM.createElement('H2', 'SCORE: ', '{0:.0}'.format((cold_insert+hot_update+hot_update_changes + 2*clear_time + 2*fast_clear_time)/4)),
        DOM.createElement(null, 'First run: ', '{0:.3} sec'.format(cold_insert/4000)),
        DOM.createElement(null, 'Second run (no changes): ', '{0:.3} sec'.format(hot_update/4000)),
        DOM.createElement(null, 'Second run (changes): ', '{0:.3} sec'.format(hot_update_changes/4000)),
        DOM.createElement(null, 'Clear total: ', '{0:.3} sec'.format(clear_time/2000)),
        DOM.createElement(null, 'Fast clear total: ', '{0:.3} sec'.format(fast_clear_time/2000))
      ]);
    }

    window.c1count = 0;
    window.c2count = 0;

    function run_test(){
      if (PROFILE) console.profile();
      run1(function(){
        run1(function(){
          var c1 = new basis.entity.Collection({
            source: Transfer.all,
            rule: 'getId()%2'
          });
          var c2 = new basis.entity.Collection({
            source: User.all,
            rule: 'getId()%2'
          });
          c1.addHandler({ itemsChanged: function(dataset, delta){ c1count += (delta.inserted ? delta.inserted.length : 0) - (delta.deleted ? delta.deleted.length : 0); } });
          c2.addHandler({ itemsChanged: function(dataset, delta){ c2count += (delta.inserted ? delta.inserted.length : 0) - (delta.deleted ? delta.deleted.length : 0); } });
          DOM.insert(document.body, [
            DOM.createElement('hr'),
            DOM.createElement(null, '2 collection added')
          ]);
          run2(function(){
            run2(function(){
              if (PROFILE) console.profileEnd();
              total();
            });
          });
        });
      });
    }

    DOM.insert(document.body,
      runBtn = DOM.createElement({
        description: 'BUTTON',
        click: function(){
          DOM.remove(this);
          run_test();
        }
      }, 'run test')
    );

    if (location.hash == '#autorun')
    {
      basis.Event.onLoad(function(){ runBtn.click(); });
    }<|endoftext|>