<commit_before>/*jshint node: true, -W106 */
'use strict';

/*
* Name : norrisSpec.js
* Module : UnitTest
* Location : /test/businessTier/norris
*
* History :
*
* Version   Date         Programmer         Description
* =========================================================
* 0.0.1     2015-05-30   Samuele Zanella    Initial code
* =========================================================
*/

var Norris = require('../../../lib/businessTier/norris/norris.js');
var Page = require('../../../lib/businessTier/page/page.js');
//var Socket=require('../../../lib/presentationTier/socket.js');
var NetworkHandler = require('../../../lib/businessTier/networkHandler/networkHandler.js');
var PageListModel = require('../../../lib/dataTier/pageList/pageListModel.js');
var assert = require('assert');
//var request = require('superagent');

var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io')(server);
io.listen(5000);
var ioclient = require('socket.io-client');

describe('Norris', function() {

    it('returns null when there are no params', function() {
        assert.strictEqual((new Norris()).hasOwnProperty('_app'), false);
    });

    it('returns null when passed invalid parameters', function() {
        assert.strictEqual((new Norris('abc', 'def', 2)).hasOwnProperty('_app'), false);
    });

    it('returns null when passed invalid route', function() {
        assert.strictEqual((new Norris('abc', 'def', '/')).hasOwnProperty('_app'), false);
    });

    it('set param values to properties', function() {
        var nor=new Norris(app, io, '/norris');
        assert.deepEqual(nor._app, app);
        assert.deepEqual(nor._io, io);
        assert.deepEqual(nor._pageList, new PageListModel('norris'));
        assert.deepEqual(nor._networkHandler, new NetworkHandler(app, io, '/norris'));
        var plm = (new NetworkHandler(app, io, '/norris')).createSocket('/norris');
        plm.attachObject(nor, 'configPageList');
        assert.deepEqual(nor._pageListSocket, plm);
        assert.strictEqual(nor._pages.length, 0);
    });

    describe('#createPage', function() {
        it('returns null if no parameter is passed', function() {
            var nor=new Norris(app, io, '/norris');
            assert.deepEqual(nor.createPage(), null);
        });

        it('returns null if the passed parameter does not contain an ID', function() {
            var nor=new Norris(app, io, '/norris');
            assert.strictEqual(nor.createPage({p: 'abc'}), null);
        });

        it('returns null if the passed ID is already used', function() {
            var nor=new Norris(app, io, '/norris');
            nor._pages.push({_page: {_ID: 'abc'}});
            assert.strictEqual(nor.createPage({ID: 'abc'}), null);
        });

        it('returns null if the PageModel is not created', function() {
            var nor=new Norris(app, io, '/norris');
            assert.strictEqual(nor.createPage({ID: ''}), null);
        });

         it('behaves correctly with the right parameters', function() {
            var nor=new Norris(app, io, '/norris');
            var socketURL = 'http://0.0.0.0:5000/norris';
            var options ={
                transports: ['websocket'],
                'force new connection': true
            };
            /*var expJSON = {
                ID: 'page1',
                name: '',
                description: '',
                URLSocket: 'http://0.0.0.0:5000/page1',
                graphs: []
            };*/
            //var stPage = new Page({ID: 'page1'}, nor._networkHandler, nor);
            assert.deepEqual(nor.createPage({ID: 'page1'}) instanceof Page, true);
            assert.strictEqual(nor._pages.length, 1);
            assert.strictEqual(nor._pageList._pages.length, 1);
            var client1 = ioclient.connect(socketURL, options);
            client1.on('insertPage', function(message) {
                console.dir('Received message');
                console.dir(message);
                //assert.strictEqual(message, expJSON);
                assert.strictEqual(message, 'ciao');
            });
        });
    });

    describe('#getConfigJSON', function() {
        it('returns the correct JSON', function() {
            var nor = new Norris(app, io, '/norris');
            var p1=nor.createPage({ID: 'p1', name:'page1'});
            var p2=nor.createPage({ID: 'p2', name:'page2'});

            var mapChart=p1.createMapChart({
                ID: 'map1',
                title: 'APS',
                height: 600,
                width: 1000,
                enableLegend: true,
                legend: {
                    position: 'NE',
                },
                latitude: 45.42533493042,
                longitude: 45.42533493042,
                mapType: 'roadMap',
                mapWidth: 2000,
                mapHeight: 2000,
                legendOnPoint: true
            });

            var lineChart=p1.createLineChart({
                ID: 'line1',
                title: 'LINEE',
                height: 600,
                width: 1000,
                enableLegend: true,
                legend: {
                    position: 'NE',
                },
                xAxis:{
                    name: 'tempo',
                    color: '#000000'
                    //ecc
                },
                yAxis:{
                    name: 'temperatura',
                    color: '#000000'
                    //ecc
                },
                backGroundColor: '#FFFFFF',
                viewFinde: true,
                horizontalGrid: true,
                verticalGrid: true,
                legendOnPoint: true,
                scale: 'linear'
            });

            var expJSON = {
                name: 'norris',
                data: [
                    {
                        ID: 'p1',
                        name: 'page1',
                        description: '',
                        URLSocket: 'http://0.0.0.0:5000/p1',
                        graphs: []
                    },
                    {
                        ID: 'p2',
                        name: 'page2',
                        description: '',
                        URLSocket: 'http://0.0.0.0:5000/p2',
                        graphs: []
                    }
                ]
            };
            console.log('stampaaaa');
            console.dir(nor.getConfigJSON());
            assert.deepEqual(nor.getConfigJSON(), expJSON);
        });
    });

    describe('#pageChanged', function() {
        it('sends the message over the socket', function() {
            var nor = new Norris(app, io, '/norris');
            var socketURL = 'http://0.0.0.0:5000/norris';
            var options ={
                transports: ['websocket'],
                'force new connection': true
            };
            var params = {
                eventType: 'updatePage',
                params: {
                    name: 'page1',
                    description: 'newDesc'
                }
            };
            nor.pageChanged(params);
            var client1 = ioclient.connect(socketURL, options);
            client1.on('updatePage', function(message) {
                assert.strictEqual(message, params);
            });
        });
    });
});<commit_msg>try to fix test<commit_after>/*jshint node: true, -W106 */
'use strict';

/*
* Name : norrisSpec.js
* Module : UnitTest
* Location : /test/businessTier/norris
*
* History :
*
* Version   Date         Programmer         Description
* =========================================================
* 0.0.1     2015-05-30   Samuele Zanella    Initial code
* =========================================================
*/

var Norris = require('../../../lib/businessTier/norris/norris.js');
var Page = require('../../../lib/businessTier/page/page.js');
//var Socket=require('../../../lib/presentationTier/socket.js');
var NetworkHandler = require('../../../lib/businessTier/networkHandler/networkHandler.js');
var PageListModel = require('../../../lib/dataTier/pageList/pageListModel.js');
var assert = require('assert');
//var request = require('superagent');

var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io')(server);
io.listen(5000);
var ioclient = require('socket.io-client');

describe('Norris', function() {

    it('returns null when there are no params', function() {
        assert.strictEqual((new Norris()).hasOwnProperty('_app'), false);
    });

    it('returns null when passed invalid parameters', function() {
        assert.strictEqual((new Norris('abc', 'def', 2)).hasOwnProperty('_app'), false);
    });

    it('returns null when passed invalid route', function() {
        assert.strictEqual((new Norris(app, io, '/')).hasOwnProperty('_app'), false);
    });

    it('set param values to properties', function() {
        var nor=new Norris(app, io, '/norris');
        assert.deepEqual(nor._app, app);
        assert.deepEqual(nor._io, io);
        assert.deepEqual(nor._pageList, new PageListModel('norris'));
        assert.deepEqual(nor._networkHandler, new NetworkHandler(app, io, '/norris'));
        var plm = (new NetworkHandler(app, io, '/norris')).createSocket('/norris');
        plm.attachObject(nor, 'configPageList');
        assert.deepEqual(nor._pageListSocket, plm);
        assert.strictEqual(nor._pages.length, 0);
    });

    describe('#createPage', function() {
        it('returns null if no parameter is passed', function() {
            var nor=new Norris(app, io, '/norris');
            assert.deepEqual(nor.createPage(), null);
        });

        it('returns null if the passed parameter does not contain an ID', function() {
            var nor=new Norris(app, io, '/norris');
            assert.strictEqual(nor.createPage({p: 'abc'}), null);
        });

        it('returns null if the passed ID is already used', function() {
            var nor=new Norris(app, io, '/norris');
            nor._pages.push({_page: {_ID: 'abc'}});
            assert.strictEqual(nor.createPage({ID: 'abc'}), null);
        });

        it('returns null if the PageModel is not created', function() {
            var nor=new Norris(app, io, '/norris');
            assert.strictEqual(nor.createPage({ID: ''}), null);
        });

         it('behaves correctly with the right parameters', function() {
            var nor=new Norris(app, io, '/norris');
            var socketURL = 'http://0.0.0.0:5000/norris';
            var options ={
                transports: ['websocket'],
                'force new connection': true
            };
            /*var expJSON = {
                ID: 'page1',
                name: '',
                description: '',
                URLSocket: 'http://0.0.0.0:5000/page1',
                graphs: []
            };*/
            //var stPage = new Page({ID: 'page1'}, nor._networkHandler, nor);
            assert.deepEqual(nor.createPage({ID: 'page1'}) instanceof Page, true);
            assert.strictEqual(nor._pages.length, 1);
            assert.strictEqual(nor._pageList._pages.length, 1);
            var client1 = ioclient.connect(socketURL, options);
            client1.on('insertPage', function(message) {
                console.dir('Received message');
                console.dir(message);
                //assert.strictEqual(message, expJSON);
                assert.strictEqual(message, 'ciao');
            });
        });
    });

    describe('#getConfigJSON', function() {
        it('returns the correct JSON', function() {
            var nor = new Norris(app, io, '/norris');
            var p1=nor.createPage({ID: 'page1', name:'Page one'});
            nor.createPage({ID: 'page2', name:'Page two'});

            p1.createMapChart({
                ID: 'map1',
                title: 'APS',
                height: 600,
                width: 1000,
                enableLegend: true,
                legend: {
                    position: 'NE',
                },
                latitude: 45.42533493042,
                longitude: 45.42533493042,
                mapType: 'roadMap',
                mapWidth: 2000,
                mapHeight: 2000,
                legendOnPoint: true
            });

            p1.createLineChart({
                ID: 'line1',
                title: 'LINEE',
                height: 600,
                width: 1000,
                enableLegend: true,
                legend: {
                    position: 'NE',
                },
                xAxis:{
                    name: 'tempo',
                    color: '#000000'
                    //ecc
                },
                yAxis:{
                    name: 'temperatura',
                    color: '#000000'
                    //ecc
                },
                backGroundColor: '#FFFFFF',
                viewFinde: true,
                horizontalGrid: true,
                verticalGrid: true,
                legendOnPoint: true,
                scale: 'linear'
            });

            var expJSON = {
                name: 'norris',
                data: [
                    {
                        ID: 'p1',
                        name: 'page1',
                        description: '',
                        URLSocket: 'http://0.0.0.0:5000/p1',
                        graphs: []
                    },
                    {
                        ID: 'p2',
                        name: 'page2',
                        description: '',
                        URLSocket: 'http://0.0.0.0:5000/p2',
                        graphs: []
                    }
                ]
            };
            console.log('stampaaaa');
            console.dir(nor.getConfigJSON());
            assert.deepEqual(nor.getConfigJSON(), expJSON);
        });
    });

    describe('#pageChanged', function() {
        it('sends the message over the socket', function() {
            var nor = new Norris(app, io, '/norris');
            var socketURL = 'http://0.0.0.0:5000/norris';
            var options ={
                transports: ['websocket'],
                'force new connection': true
            };
            var params = {
                eventType: 'updatePage',
                params: {
                    name: 'page1',
                    description: 'newDesc'
                }
            };
            nor.pageChanged(params);
            var client1 = ioclient.connect(socketURL, options);
            client1.on('updatePage', function(message) {
                assert.strictEqual(message, params);
            });
        });
    });
});<|endoftext|>


<commit_before>//Test the create variation command
var fs = require('fs');

var assert = require('chai').assert;
var nexpect = require('nexpect');
var quickTemp = require('quick-temp');
var options = {
  'cwd': __dirname
};
var directory = {};

describe('Create Variation Module', function () {
  before(function (done) {
    quickTemp.makeOrRemake(directory, 'project');
    options.cwd = directory.project;
    nexpect.spawn('optcli', ['init'], options)
      .run(function (err) {
        assert(!err, 'Error while initializing a project: ' + err);
        nexpect.spawn('optcli', ['experiment', 'test-experiment', '"Test Experiment"', 'http://example.com'], options)
          .run(function (err) {
            assert(!err, 'Error while creating experiment: ' + err);
            done();
          });
      });
  });
  after(function () {
    quickTemp.remove(directory, 'project');
  });
  it('Should create a variation within the experiment folder with a variation.js and variation.json', function (done) {
    nexpect.spawn('optcli', ['variation', 'test-experiment', 'test-variation', '"Test Variation"'], options)
      .run(function (err) {
        assert(!err, 'Error when creating variation');
        directory.variation = directory.project + '/test-experiment/test-variation';
        fs.exists(directory.variation + '/variation.json', function (exists) {
          console.log(directory.variation);
          assert(exists, 'variation.json not found');
          fs.exists(directory.variation + '/variation.js', function (exists) {
            assert(exists, 'variation.js not found');
            done();
          });
        });
      });
  });
});<commit_msg>fixed a stray console.log<commit_after>//Test the create variation command
var fs = require('fs');

var assert = require('chai').assert;
var nexpect = require('nexpect');
var quickTemp = require('quick-temp');
var options = {
  'cwd': __dirname
};
var directory = {};

describe('Create Variation Module', function () {
  before(function (done) {
    quickTemp.makeOrRemake(directory, 'project');
    options.cwd = directory.project;
    nexpect.spawn('optcli', ['init'], options)
      .run(function (err) {
        assert(!err, 'Error while initializing a project: ' + err);
        nexpect.spawn('optcli', ['experiment', 'test-experiment', '"Test Experiment"', 'http://example.com'], options)
          .run(function (err) {
            assert(!err, 'Error while creating experiment: ' + err);
            done();
          });
      });
  });
  after(function () {
    quickTemp.remove(directory, 'project');
  });
  it('Should create a variation within the experiment folder with a variation.js and variation.json', function (done) {
    nexpect.spawn('optcli', ['variation', 'test-experiment', 'test-variation', '"Test Variation"'], options)
      .run(function (err) {
        assert(!err, 'Error when creating variation');
        directory.variation = directory.project + '/test-experiment/test-variation';
        fs.exists(directory.variation + '/variation.json', function (exists) {
          assert(exists, 'variation.json not found');
          fs.exists(directory.variation + '/variation.js', function (exists) {
            assert(exists, 'variation.js not found');
            done();
          });
        });
      });
  });
});<|endoftext|>


<commit_before>// test simplify
var assert = require('assert');
var math = require('../../../index');

describe('simplify', function() {

  function simplifyAndCompare(left, right, scope) {
    try {
        if (scope) {
            assert.equal(math.simplify(left, scope).toString(), math.parse(right).toString());
        } else {
            assert.equal(math.simplify(left).toString(), math.parse(right).toString());
        }
    } catch (err) {
        if (err instanceof Error) {
            console.log(err.stack);
        } else {
            console.log(new Error(err));
        }
        throw err;
    }
  }

  function simplifyAndCompareEval (left, right, scope) {
    scope = scope || {};
    assert.equal(math.simplify(left).eval(scope), math.parse(right).eval(scope));
  }

  it('should not change the value of the function', function() {
    simplifyAndCompareEval('3+2/4+2*8', '39/2');
    simplifyAndCompareEval('x+1+x', '2x+1', {x:7});
    simplifyAndCompareEval('x+1+2x', '3x+1', {x:7});
    simplifyAndCompareEval('x^2+x-3+x^2', '2x^2+x-3', {x:7});
  });

  it('should simplify rational expressions with no symbols to fraction', function() {
    simplifyAndCompare('3*4', '12');
    simplifyAndCompare('3+2/4', '7/2');
  });

  it('should simplify (-1)*n', function() {
    simplifyAndCompare('(-1)*4', '-4');
    simplifyAndCompare('(-1)*x', '-x');
  });

  it('should simplify (n- -n1)', function() {
    simplifyAndCompare('2 + -3', '-1');
    simplifyAndCompare('2 - 3', '-1');
    simplifyAndCompare('2 - -3', '5');
    var e = math.parse('2 - -3');
    e = math.simplify.simplifyCore(e);
    assert.equal(e.toString(), '5'); // simplifyCore
    simplifyAndCompare('x - -x', '2*x');
    var e = math.parse('x - -x');
    e = math.simplify.simplifyCore(e);
    assert.equal(e.toString(), 'x + x'); // not a core simplification since + is cheaper than *
  });

  it('should preserve the value of BigNumbers', function() {
    var bigmath = math.create({number: 'BigNumber', precision: 64});
    assert.deepEqual(bigmath.simplify('111111111111111111 + 111111111111111111').eval(), bigmath.eval('222222222222222222'));
    assert.deepEqual(bigmath.simplify('1 + 111111111111111111').eval(), bigmath.eval('111111111111111112'));
    assert.deepEqual(bigmath.simplify('1/2 + 11111111111111111111').eval(), bigmath.eval('11111111111111111111.5'));
    assert.deepEqual(bigmath.simplify('1/3 + 11111111111111111111').eval(), bigmath.eval('11111111111111111111.33333333333333333333333333333333333333333333'));
    assert.deepEqual(bigmath.simplify('3 + 1 / 11111111111111111111').eval(), bigmath.eval('3 + 1 / 11111111111111111111'));
  });

  it('should not change the value of numbers when converting to fractions (1)', function() {
    simplifyAndCompareEval('1e-10', '1e-10');
  });

  it('should not change the value of numbers when converting to fractions (2)', function() {
    simplifyAndCompareEval('0.2 * 1e-14', '2e-15');
  });

  it.skip('should not change the value of numbers when converting to fractions (3)', function() {
    // TODO this requires that all operators and functions have the correct logic in their 'Fraction' typed-functions.
    //      Ideally they should convert parameters to Fractions if they can all be expressed exactly,
    //      otherwise convert all parameters to the 'number' type.
    simplifyAndCompareEval('1 - 1e-10', '1 - 1e-10');
    simplifyAndCompareEval('1 + 1e-10', '1 + 1e-10');
    simplifyAndCompareEval('1e-10 / 2', '1e-10 / 2');
    simplifyAndCompareEval('(1e-5)^2', '(1e-5)^2');
    simplifyAndCompareEval('min(1, -1e-10)', '-1e-10');
    simplifyAndCompareEval('max(1e-10, -1)', '1e-10');
  });

  it('should simplify non-rational expressions with no symbols to number', function() {
    simplifyAndCompare('3+sin(4)', '2.2431975046920716');
  });

  it('should collect like terms', function() {
    simplifyAndCompare('x+x', '2*x');
    simplifyAndCompare('2x+x', '3*x');
    simplifyAndCompare('2(x+1)+(x+1)', '3*(x + 1)');
    simplifyAndCompare('y*x^2+2*x^2', '(y+2)*x^2');
  });

  it('should collect separated like terms', function() {
    simplifyAndCompare('x+1+x', '2*x+1');
    simplifyAndCompare('x^2+x+3+x^2', '2*x^2+x+3');
    simplifyAndCompare('x+1+2x', '3*x+1');
    simplifyAndCompare('x-1+x', '2*x-1');
    simplifyAndCompare('x-1-2x+2', '1-x');
  });

  it('should collect separated like factors', function() {
    simplifyAndCompare('x/2*x', 'x^2/2');
    simplifyAndCompare('x*2*x', '2*x^2');
    simplifyAndCompare('x*y*-x/(x^2)', '-y');
  });

  it('should handle non-existing functions like a pro', function() {
    simplifyAndCompare('foo(x)', 'foo(x)');
  });

  it('should handle valid built-in constant symbols in rules', function() {
    assert.equal(math.simplify('true', ['true -> 1']).toString(), '1');
    assert.equal(math.simplify('false', ['false -> 0']).toString(), '0');
    assert.equal(math.simplify('log(e)', ['log(e) -> 1']).toString(), '1');
    assert.equal(math.simplify('sin(pi * x)', ['sin(pi * n) -> 0']).toString(), '0');
    assert.equal(math.simplify('i', ['i -> 1']).toString(), '1');
    assert.equal(math.simplify('Infinity', ['Infinity -> 1']).toString(), '1');
    assert.equal(math.simplify('LN2', ['LN2 -> 1']).toString(), '1');
    assert.equal(math.simplify('LN10', ['LN10 -> 1']).toString(), '1');
    assert.equal(math.simplify('LOG2E', ['LOG2E -> 1']).toString(), '1');
    assert.equal(math.simplify('LOG10E', ['LOG10E -> 1']).toString(), '1');
    assert.equal(math.simplify('NaN', ['NaN -> 1']).toString(), '1');
    assert.equal(math.simplify('phi', ['phi -> 1']).toString(), '1');
    assert.equal(math.simplify('SQRT1_2', ['SQRT1_2 -> 1']).toString(), '1');
    assert.equal(math.simplify('SQRT2', ['SQRT2 -> 1']).toString(), '1');
    assert.equal(math.simplify('tau', ['tau -> 1']).toString(), '1');
  });

  it('should throw an error for invalid built-in constant symbols in rules', function() {
    assert.throws(function(){ math.simplify('null', ['null -> 1']).toString(); });
    assert.throws(function(){ math.simplify('uninitialized', ['uninitialized -> 1']).toString(); });
    assert.throws(function(){ math.simplify('version', ['version -> 1']).toString(); });
  });

  it('should remove addition of 0', function() {
    simplifyAndCompare('x+0', 'x');
    simplifyAndCompare('x-0', 'x');
  });

  it('resolve() should substitute scoped constants', function() {
    assert.equal(
        math.simplify.resolve(math.parse('x+y'), {x:1}).toString(),
        "1 + y"
    ); // direct
    simplifyAndCompare('x+y', 'x+y', {}); // operator
    simplifyAndCompare('x+y', 'y+1', {x:1});
    simplifyAndCompare('x+y', 'y+1', {x:math.parse('1')});
    simplifyAndCompare('x+y', '3', {x:1,y:2});
    simplifyAndCompare('x+x+x', '3*x');
    simplifyAndCompare('y', 'x+1', {y:math.parse("1+x")});
    simplifyAndCompare('y', '3', {x:2, y:math.parse("1+x")});
    simplifyAndCompare('x+y', '3*x', {y:math.parse("x+x")});
    simplifyAndCompare('x+y', '6', {x:2,y:math.parse("x+x")});
    simplifyAndCompare('x+(y+2-1-1)', '6', {x:2,y:math.parse("x+x")}); // parentheses
    simplifyAndCompare('log(x+y)', `${Math.log(6)}`, {x:2,y:math.parse("x+x")}); // function
    simplifyAndCompare('combinations( ceil(abs(sin(x)) * y), abs(x) )',
        'combinations(ceil(0.9092974268256817 * y ), 2)', {x:-2});

    // TODO(deal with accessor nodes) simplifyAndCompare('size(text)[1]', '11', {text: "hello world"})
  });

  describe('expression parser' ,function () {

    it('should evaluate simplify containing string value', function() {
      var res = math.eval('simplify("2x + 3x")');
      assert.ok(res && res.isNode)
      assert.equal(res.toString(), '5 * x');
    });

    it('should evaluate simplify containing nodes', function() {
      var res = math.eval('simplify(parse("2x + 3x"))');
      assert.ok(res && res.isNode)
      assert.equal(res.toString(), '5 * x');
    });

    it('should compute and simplify derivatives', function() {
      var res = math.eval('derivative("5x*3x", "x")');
      assert.ok(res && res.isNode)
      assert.equal(res.toString(), '30 * x');
    });

    it('should compute and simplify derivatives (2)', function() {
      var scope = {}
      math.eval('a = derivative("5x*3x", "x")', scope)
      var res = math.eval('simplify(a)', scope);
      assert.ok(res && res.isNode)
      assert.equal(res.toString(), '30 * x');
    });

    it.skip('should compute and simplify derivatives (3)', function() {
      // TODO: this requires the + operator to support Nodes,
      //       i.e.   math.add(5, math.parse('2')) => return an OperatorNode
      var res = math.eval('simplify(5+derivative(5/(3x), x))');
      assert.ok(res && res.isNode)
      assert.equal(res.toString(), '5 - 15 / (3 * x) ^ 2');
    });

  });

});
<commit_msg>Replaced another occurrence of ES6 backtick<commit_after>// test simplify
var assert = require('assert');
var math = require('../../../index');

describe('simplify', function() {

  function simplifyAndCompare(left, right, scope) {
    try {
        if (scope) {
            assert.equal(math.simplify(left, scope).toString(), math.parse(right).toString());
        } else {
            assert.equal(math.simplify(left).toString(), math.parse(right).toString());
        }
    } catch (err) {
        if (err instanceof Error) {
            console.log(err.stack);
        } else {
            console.log(new Error(err));
        }
        throw err;
    }
  }

  function simplifyAndCompareEval (left, right, scope) {
    scope = scope || {};
    assert.equal(math.simplify(left).eval(scope), math.parse(right).eval(scope));
  }

  it('should not change the value of the function', function() {
    simplifyAndCompareEval('3+2/4+2*8', '39/2');
    simplifyAndCompareEval('x+1+x', '2x+1', {x:7});
    simplifyAndCompareEval('x+1+2x', '3x+1', {x:7});
    simplifyAndCompareEval('x^2+x-3+x^2', '2x^2+x-3', {x:7});
  });

  it('should simplify rational expressions with no symbols to fraction', function() {
    simplifyAndCompare('3*4', '12');
    simplifyAndCompare('3+2/4', '7/2');
  });

  it('should simplify (-1)*n', function() {
    simplifyAndCompare('(-1)*4', '-4');
    simplifyAndCompare('(-1)*x', '-x');
  });

  it('should simplify (n- -n1)', function() {
    simplifyAndCompare('2 + -3', '-1');
    simplifyAndCompare('2 - 3', '-1');
    simplifyAndCompare('2 - -3', '5');
    var e = math.parse('2 - -3');
    e = math.simplify.simplifyCore(e);
    assert.equal(e.toString(), '5'); // simplifyCore
    simplifyAndCompare('x - -x', '2*x');
    var e = math.parse('x - -x');
    e = math.simplify.simplifyCore(e);
    assert.equal(e.toString(), 'x + x'); // not a core simplification since + is cheaper than *
  });

  it('should preserve the value of BigNumbers', function() {
    var bigmath = math.create({number: 'BigNumber', precision: 64});
    assert.deepEqual(bigmath.simplify('111111111111111111 + 111111111111111111').eval(), bigmath.eval('222222222222222222'));
    assert.deepEqual(bigmath.simplify('1 + 111111111111111111').eval(), bigmath.eval('111111111111111112'));
    assert.deepEqual(bigmath.simplify('1/2 + 11111111111111111111').eval(), bigmath.eval('11111111111111111111.5'));
    assert.deepEqual(bigmath.simplify('1/3 + 11111111111111111111').eval(), bigmath.eval('11111111111111111111.33333333333333333333333333333333333333333333'));
    assert.deepEqual(bigmath.simplify('3 + 1 / 11111111111111111111').eval(), bigmath.eval('3 + 1 / 11111111111111111111'));
  });

  it('should not change the value of numbers when converting to fractions (1)', function() {
    simplifyAndCompareEval('1e-10', '1e-10');
  });

  it('should not change the value of numbers when converting to fractions (2)', function() {
    simplifyAndCompareEval('0.2 * 1e-14', '2e-15');
  });

  it.skip('should not change the value of numbers when converting to fractions (3)', function() {
    // TODO this requires that all operators and functions have the correct logic in their 'Fraction' typed-functions.
    //      Ideally they should convert parameters to Fractions if they can all be expressed exactly,
    //      otherwise convert all parameters to the 'number' type.
    simplifyAndCompareEval('1 - 1e-10', '1 - 1e-10');
    simplifyAndCompareEval('1 + 1e-10', '1 + 1e-10');
    simplifyAndCompareEval('1e-10 / 2', '1e-10 / 2');
    simplifyAndCompareEval('(1e-5)^2', '(1e-5)^2');
    simplifyAndCompareEval('min(1, -1e-10)', '-1e-10');
    simplifyAndCompareEval('max(1e-10, -1)', '1e-10');
  });

  it('should simplify non-rational expressions with no symbols to number', function() {
    simplifyAndCompare('3+sin(4)', '2.2431975046920716');
  });

  it('should collect like terms', function() {
    simplifyAndCompare('x+x', '2*x');
    simplifyAndCompare('2x+x', '3*x');
    simplifyAndCompare('2(x+1)+(x+1)', '3*(x + 1)');
    simplifyAndCompare('y*x^2+2*x^2', '(y+2)*x^2');
  });

  it('should collect separated like terms', function() {
    simplifyAndCompare('x+1+x', '2*x+1');
    simplifyAndCompare('x^2+x+3+x^2', '2*x^2+x+3');
    simplifyAndCompare('x+1+2x', '3*x+1');
    simplifyAndCompare('x-1+x', '2*x-1');
    simplifyAndCompare('x-1-2x+2', '1-x');
  });

  it('should collect separated like factors', function() {
    simplifyAndCompare('x/2*x', 'x^2/2');
    simplifyAndCompare('x*2*x', '2*x^2');
    simplifyAndCompare('x*y*-x/(x^2)', '-y');
  });

  it('should handle non-existing functions like a pro', function() {
    simplifyAndCompare('foo(x)', 'foo(x)');
  });

  it('should handle valid built-in constant symbols in rules', function() {
    assert.equal(math.simplify('true', ['true -> 1']).toString(), '1');
    assert.equal(math.simplify('false', ['false -> 0']).toString(), '0');
    assert.equal(math.simplify('log(e)', ['log(e) -> 1']).toString(), '1');
    assert.equal(math.simplify('sin(pi * x)', ['sin(pi * n) -> 0']).toString(), '0');
    assert.equal(math.simplify('i', ['i -> 1']).toString(), '1');
    assert.equal(math.simplify('Infinity', ['Infinity -> 1']).toString(), '1');
    assert.equal(math.simplify('LN2', ['LN2 -> 1']).toString(), '1');
    assert.equal(math.simplify('LN10', ['LN10 -> 1']).toString(), '1');
    assert.equal(math.simplify('LOG2E', ['LOG2E -> 1']).toString(), '1');
    assert.equal(math.simplify('LOG10E', ['LOG10E -> 1']).toString(), '1');
    assert.equal(math.simplify('NaN', ['NaN -> 1']).toString(), '1');
    assert.equal(math.simplify('phi', ['phi -> 1']).toString(), '1');
    assert.equal(math.simplify('SQRT1_2', ['SQRT1_2 -> 1']).toString(), '1');
    assert.equal(math.simplify('SQRT2', ['SQRT2 -> 1']).toString(), '1');
    assert.equal(math.simplify('tau', ['tau -> 1']).toString(), '1');
  });

  it('should throw an error for invalid built-in constant symbols in rules', function() {
    assert.throws(function(){ math.simplify('null', ['null -> 1']).toString(); });
    assert.throws(function(){ math.simplify('uninitialized', ['uninitialized -> 1']).toString(); });
    assert.throws(function(){ math.simplify('version', ['version -> 1']).toString(); });
  });

  it('should remove addition of 0', function() {
    simplifyAndCompare('x+0', 'x');
    simplifyAndCompare('x-0', 'x');
  });

  it('resolve() should substitute scoped constants', function() {
    assert.equal(
        math.simplify.resolve(math.parse('x+y'), {x:1}).toString(),
        "1 + y"
    ); // direct
    simplifyAndCompare('x+y', 'x+y', {}); // operator
    simplifyAndCompare('x+y', 'y+1', {x:1});
    simplifyAndCompare('x+y', 'y+1', {x:math.parse('1')});
    simplifyAndCompare('x+y', '3', {x:1,y:2});
    simplifyAndCompare('x+x+x', '3*x');
    simplifyAndCompare('y', 'x+1', {y:math.parse("1+x")});
    simplifyAndCompare('y', '3', {x:2, y:math.parse("1+x")});
    simplifyAndCompare('x+y', '3*x', {y:math.parse("x+x")});
    simplifyAndCompare('x+y', '6', {x:2,y:math.parse("x+x")});
    simplifyAndCompare('x+(y+2-1-1)', '6', {x:2,y:math.parse("x+x")}); // parentheses
    simplifyAndCompare('log(x+y)', String(Math.log(6)), {x:2,y:math.parse("x+x")}); // function
    simplifyAndCompare('combinations( ceil(abs(sin(x)) * y), abs(x) )',
        'combinations(ceil(0.9092974268256817 * y ), 2)', {x:-2});

    // TODO(deal with accessor nodes) simplifyAndCompare('size(text)[1]', '11', {text: "hello world"})
  });

  describe('expression parser' ,function () {

    it('should evaluate simplify containing string value', function() {
      var res = math.eval('simplify("2x + 3x")');
      assert.ok(res && res.isNode)
      assert.equal(res.toString(), '5 * x');
    });

    it('should evaluate simplify containing nodes', function() {
      var res = math.eval('simplify(parse("2x + 3x"))');
      assert.ok(res && res.isNode)
      assert.equal(res.toString(), '5 * x');
    });

    it('should compute and simplify derivatives', function() {
      var res = math.eval('derivative("5x*3x", "x")');
      assert.ok(res && res.isNode)
      assert.equal(res.toString(), '30 * x');
    });

    it('should compute and simplify derivatives (2)', function() {
      var scope = {}
      math.eval('a = derivative("5x*3x", "x")', scope)
      var res = math.eval('simplify(a)', scope);
      assert.ok(res && res.isNode)
      assert.equal(res.toString(), '30 * x');
    });

    it.skip('should compute and simplify derivatives (3)', function() {
      // TODO: this requires the + operator to support Nodes,
      //       i.e.   math.add(5, math.parse('2')) => return an OperatorNode
      var res = math.eval('simplify(5+derivative(5/(3x), x))');
      assert.ok(res && res.isNode)
      assert.equal(res.toString(), '5 - 15 / (3 * x) ^ 2');
    });

  });

});
<|endoftext|>


<commit_before>import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr('string'),
  redirect_uri: DS.attr('string'),
  image_uri: DS.attr('string'),
  client_secret: DS.attr('string')
});
<commit_msg>fix(model): add can_grant<commit_after>import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr('string'),
  redirect_uri: DS.attr('string'),
  image_uri: DS.attr('string'),
  client_secret: DS.attr('string'),
  can_grant: DS.attr('boolean'),
  whitelisted: DS.attr('boolean')
});
<|endoftext|>


<commit_before>var expect = require('chai').expect,
  sinon = require('sinon'),
  FileSystem = require('../../../../lib/daemon/util/FileSystem'),
  os = require('os'),
  fs = require('fs'),
  posix = require('posix'),
  mkdirp = require('mkdirp'),
  shortId = require('shortid')

describe('FileSystem', function () {
  var temp, fileSystem

  beforeEach(function () {
    temp = os.tmpdir() + '/' + shortId.generate()
    fileSystem = new FileSystem()
    fileSystem._config = {
      guvnor: {
        logdir: temp + '/log',
        confdir: temp + '/conf',
        rundir: temp + '/run',
        appdir: temp + '/apps',
        user: posix.getpwnam(process.getuid()).name,
        group: posix.getgrnam(process.getgid()).name
      }
    }
    fileSystem._logger = {
      info: function () {
      },
      warn: function () {
      },
      error: function () {
      },
      debug: function () {
      }
    }
    fileSystem._posix = posix
    fileSystem._fs = fs
    fileSystem._mkdirp = mkdirp
  })

  it('should create directories', function () {
    expect(fs.existsSync(fileSystem._config.guvnor.rundir)).to.be.false

    fileSystem.afterPropertiesSet()

    expect(fs.existsSync(fileSystem._config.guvnor.rundir)).to.be.true
    expect(fs.existsSync(fileSystem._config.guvnor.rundir + '/processes')).to.be.true
    expect(fs.existsSync(fileSystem._config.guvnor.logdir)).to.be.true
    expect(fs.existsSync(fileSystem._config.guvnor.confdir)).to.be.true
    expect(fs.existsSync(fileSystem._config.guvnor.appdir)).to.be.true
  })

  it('should not create a directory when one exists', function () {
    fileSystem._fs = {
      existsSync: sinon.stub()
    }
    fileSystem._mkdirp = {
      sync: sinon.stub()
    }

    fileSystem._fs.existsSync.returns(true)

    fileSystem.afterPropertiesSet()

    expect(fileSystem._mkdirp.sync.callCount).to.equal(0)
  })

  it('should throw an error when directory creation fails', function () {
    fileSystem._fs = {
      existsSync: sinon.stub(),
      chownSync: sinon.stub()
    }
    fileSystem._mkdirp = {
      sync: sinon.stub()
    }

    fileSystem._fs.existsSync.returns(false)
    fileSystem._mkdirp.sync.throws(new Error('urk!'))

    try {
      fileSystem.afterPropertiesSet()
    } catch (e) {
      if (e.message != 'urk!')
        throw e
    }

    expect(fileSystem._fs.chownSync.callCount).to.equal(0)
  })
})
<commit_msg>tests for file system<commit_after>var expect = require('chai').expect,
  sinon = require('sinon'),
  FileSystem = require('../../../../lib/daemon/util/FileSystem'),
  os = require('os'),
  fs = require('fs'),
  posix = require('posix'),
  mkdirp = require('mkdirp'),
  shortId = require('shortid')

describe('FileSystem', function () {
  var temp, fileSystem

  beforeEach(function () {
    temp = os.tmpdir() + '/' + shortId.generate()
    fileSystem = new FileSystem()
    fileSystem._config = {
      guvnor: {
        logdir: temp + '/log',
        confdir: temp + '/conf',
        rundir: temp + '/run',
        appdir: temp + '/apps',
        user: posix.getpwnam(process.getuid()).name,
        group: posix.getgrnam(process.getgid()).name
      }
    }
    fileSystem._logger = {
      info: function () {
      },
      warn: function () {
      },
      error: function () {
      },
      debug: function () {
      }
    }
    fileSystem._posix = posix
    fileSystem._fs = fs
    fileSystem._mkdirp = mkdirp
  })

  it('should create directories', function () {
    expect(fs.existsSync(fileSystem._config.guvnor.rundir)).to.be.false

    fileSystem.afterPropertiesSet()

    expect(fs.existsSync(fileSystem._config.guvnor.rundir)).to.be.true
    expect(fs.existsSync(fileSystem._config.guvnor.rundir + '/processes')).to.be.true
    expect(fs.existsSync(fileSystem._config.guvnor.logdir)).to.be.true
    expect(fs.existsSync(fileSystem._config.guvnor.confdir)).to.be.true
    expect(fs.existsSync(fileSystem._config.guvnor.appdir)).to.be.true
  })

  it('should not create a directory when one exists', function () {
    fileSystem._fs = {
      existsSync: sinon.stub()
    }
    fileSystem._mkdirp = {
      sync: sinon.stub()
    }

    fileSystem._fs.existsSync.returns(true)

    fileSystem.afterPropertiesSet()

    expect(fileSystem._mkdirp.sync.callCount).to.equal(0)
  })

  it('should throw an error when directory creation fails', function () {
    fileSystem._fs = {
      existsSync: sinon.stub(),
      chownSync: sinon.stub()
    }
    fileSystem._mkdirp = {
      sync: sinon.stub()
    }

    fileSystem._fs.existsSync.returns(false)
    fileSystem._mkdirp.sync.throws(new Error('urk!'))

    try {
      fileSystem.afterPropertiesSet()
    } catch (e) {
      if (e.message != 'urk!') {
        throw e
      }
    }

    expect(fileSystem._fs.chownSync.callCount).to.equal(0)
  })

  it('should return run dir', function () {
    var dir = 'foo'
    fileSystem._config.guvnor.rundir = dir

    expect(dir).to.equal(fileSystem.getRunDir())
  })

  it('should return log dir', function () {
    var dir = 'foo'
    fileSystem._config.guvnor.logdir = dir

    expect(dir).to.equal(fileSystem.getLogDir())
  })

  it('should return conf dir', function () {
    var dir = 'foo'
    fileSystem._config.guvnor.confdir = dir

    expect(dir).to.equal(fileSystem.getConfDir())
  })

  it('should return app dir', function () {
    var dir = 'foo'
    fileSystem._config.guvnor.appdir = dir

    expect(dir).to.equal(fileSystem.getAppDir())
  })
})
<|endoftext|>


<commit_before>"use strict";

class gsuiDrumrows extends HTMLElement {
	constructor() {
		super();
		this._rows = new Map();
		this._lines = new Map();
		this._reorder = new gsuiReorder( {
			rootElement: this,
			direction: "column",
			dataTransferType: "drumrow",
			itemSelector: ".gsuiDrumrow",
			handleSelector: ".gsuiDrumrow-grip",
			parentSelector: ".gsuiDrumrows",
			onchange: this._onreorderRows.bind( this ),
		} );
		this._dragoverId =
		this._elDragover =
		this._elLinesParent =
		this._timeoutIdDragleave = null;
		this._dispatch = GSUI.dispatchEvent.bind( null, this, "gsuiDrumrows" );
		Object.seal( this );

		this.ondrop = this._ondropRows.bind( this );
		this.onclick = this._onclickRows.bind( this );
		this.onchange = this._onchangeRows.bind( this );
		this.ondragover = this._ondragoverRows.bind( this );
		this.ondragstart = e => e.stopPropagation();
		this.onmousedown = this._onmousedownRows.bind( this );
		this.oncontextmenu = this._oncontextmenuRows.bind( this );
		this.onanimationend = this._onanimationendRows.bind( this );
	}

	// .........................................................................
	connectedCallback() {
		if ( !this.firstChild ) {
			this.classList.add( "gsuiDrumrows" );
			this.append( ...GSUI.getTemplate( "gsui-drumrows" ) );
		}
	}

	// .........................................................................
	setLinesParent( el, childClass ) {
		this._elLinesParent = el;
		this._reorder.setShadowElement( el );
		this._reorder.setShadowChildClass( childClass );
	}
	reorderDrumrows( obj ) {
		gsuiReorder.listReorder( this, obj );
		gsuiReorder.listReorder( this._elLinesParent, obj );
	}
	playRow( id ) {
		const rect = document.createElement( "div" );

		rect.classList.add( "gsuiDrumrow-startCursor" );
		this._rows.get( id ).root.querySelector( ".gsuiDrumrow-waveWrap" ).append( rect );
	}
	stopRow( id ) {
		this._rows.get( id ).root.querySelectorAll( ".gsuiDrumrow-startCursor" )
			.forEach( el => el.remove() );
	}
	setPropFilter( id, prop ) {
		this._rows.get( id ).root.querySelector( `.gsuiDrumrow-propRadio[value="${ prop }"]` ).checked = true;
	}
	setDrumPropValue( rowId, prop, val ) {
		const el = this._getPropBtn( rowId, prop ),
			fixval = prop === "detune" ? val : val.toFixed( 2 ),
			txtval = prop !== "gain"
				? `${ val > 0 ? "+" : "" }${ fixval }`
				: fixval;

		el.classList.add( "gsuiDrumrow-propSpanValue" );
		el.textContent = txtval;
	}
	removeDrumPropValue( rowId, prop ) {
		const el = this._getPropBtn( rowId, prop );

		el.classList.remove( "gsuiDrumrow-propSpanValue" );
		el.textContent = prop === "detune" ? "pitch" : prop;
	}

	// .........................................................................
	add( id, elLine ) {
		const elRow = GSUI.getTemplate( "gsui-drumrow" ),
			sliDetune = elRow.querySelector( ".gsuiDrumrow-detune gsui-slider" ),
			sliGain = elRow.querySelector( ".gsuiDrumrow-gain gsui-slider" ),
			sliPan = elRow.querySelector( ".gsuiDrumrow-pan gsui-slider" ),
			html = {
				root: elRow,
				name: elRow.querySelector( ".gsuiDrumrow-name" ),
				detune: sliDetune,
				gain: sliGain,
				pan: sliPan,
			};

		elRow.dataset.id =
		elLine.dataset.id = id;
		sliDetune.oninput = val => {
			this._namePrint( id, `pitch: ${ val > 0 ? "+" : "" }${ val }` );
			this._dispatch( "liveChangeDrumrow", id, "detune", val );
		};
		sliGain.oninput = val => {
			this._namePrint( id, `gain: ${ val.toFixed( 2 ) }` );
			this._dispatch( "liveChangeDrumrow", id, "gain", val );
		};
		sliPan.oninput = val => {
			this._namePrint( id, `pan: ${ val > 0 ? "+" : "" }${ val.toFixed( 2 ) }` );
			this._dispatch( "liveChangeDrumrow", id, "pan", val );
		};
		sliDetune.onchange = this._onchangeRowSlider.bind( this, id, "detune" );
		sliGain.onchange = this._onchangeRowSlider.bind( this, id, "gain" );
		sliPan.onchange = this._onchangeRowSlider.bind( this, id, "pan" );
		sliDetune.oninputend =
		sliGain.oninputend =
		sliPan.oninputend = this._oninputendRowSlider.bind( this, id );
		this._rows.set( id, html );
		this._lines.set( id, elLine );
		this.append( elRow );
		this._elLinesParent.append( elLine );
	}
	remove( id ) {
		this._rows.get( id ).root.remove();
		this._lines.get( id ).remove();
		this._rows.delete( id );
		this._lines.delete( id );
	}
	change( id, prop, val ) {
		switch ( prop ) {
			case "pan": this._changePan( id, val ); break;
			case "name": this._changeName( id, val ); break;
			case "gain": this._changeGain( id, val ); break;
			case "order": this._changeOrder( id, val ); break;
			case "detune": this._changeDetune( id, val ); break;
			case "toggle": this._changeToggle( id, val ); break;
			case "pattern": this._changePattern( id, val ); break;
			case "duration": this._changeDuration( id, val ); break;
		}
	}
	_changePan( id, val ) {
		this._rows.get( id ).pan.setValue( val );
	}
	_changeGain( id, val ) {
		this._rows.get( id ).gain.setValue( val );
	}
	_changeDetune( id, val ) {
		this._rows.get( id ).detune.setValue( val );
	}
	_changeName( id, name ) {
		const el = this._rows.get( id ).name;

		el.dataset.name =
		el.textContent = name;
	}
	_changeToggle( id, b ) {
		this._rows.get( id ).root.classList.toggle( "gsuiDrumrow-mute", !b );
		this._lines.get( id ).classList.toggle( "gsuiDrumrow-mute", !b );
	}
	_changeDuration( id, dur ) {
		this._rows.get( id ).root.querySelector( ".gsuiDrumrow-waveWrap" ).style.animationDuration = `${ dur * 2 }s`;
	}
	_changePattern( id, svg ) {
		const elWave = this._rows.get( id ).root.querySelector( ".gsuiDrumrow-waveWrap" );

		if ( elWave.firstChild ) {
			elWave.firstChild.remove();
		}
		if ( svg ) {
			svg.classList.add( "gsuiDrumrow-wave" );
			elWave.append( svg );
		}
	}
	_changeOrder( id, order ) {
		this._rows.get( id ).root.dataset.order =
		this._lines.get( id ).dataset.order = order;
	}

	// .........................................................................
	_namePrint( id, msg ) {
		const el = this._rows.get( id ).name;

		el.textContent = msg;
		el.classList.add( "gsuiDrumrow-nameInfo" );
	}
	_expandProps( id ) {
		this._rows.get( id ).root.classList.toggle( "gsuiDrumrow-open" );
		this._lines.get( id ).classList.toggle( "gsuiDrums-lineOpen" );
	}
	_getPropBtn( rowId, prop ) {
		return this._rows.get( rowId ).root
			.querySelector( `.gsuiDrumrow-propRadio[value="${ prop }"] + .gsuiDrumrow-propSpan` );
	}

	// events:
	// .........................................................................
	_oninputendRowSlider( id ) {
		const el = this._rows.get( id ).name;

		el.textContent = el.dataset.name;
		el.classList.remove( "gsuiDrumrow-nameInfo" );
	}
	_onchangeRowSlider( id, prop, val ) {
		this._dispatch( "change", "changeDrumrow", id, prop, val );
	}
	_onreorderRows( elRow ) {
		const rows = gsuiReorder.listComputeOrderChange( this, {} );

		this._dispatch( "change", "reorderDrumrow", elRow.dataset.id, rows );
	}
	_onchangeRows( e ) {
		const id = e.target.closest( ".gsuiDrumrow" ).dataset.id;

		this._dispatch( "propFilter", id, e.target.value );
	}
	_onclickRows( e ) {
		if ( e.target !== this ) {
			const id = e.target.closest( ".gsuiDrumrow" ).dataset.id;

			switch ( e.target.dataset.action ) {
				case "props": this._expandProps( id ); break;
				case "toggle": this._dispatch( "change", "toggleDrumrow", id ); break;
				case "delete": this._dispatch( "change", "removeDrumrow", id ); break;
			}
		}
	}
	_onmousedownRows( e ) {
		if ( ( e.button === 0 || e.button === 2 ) && e.target.classList.contains( "gsuiDrumrow-main" ) ) {
			this._dispatch(
				e.button === 0 ? "liveStartDrum" : "liveStopDrum",
				e.target.parentNode.dataset.id );
		}
	}
	_onanimationendRows( e ) {
		if ( e.target.classList.contains( "gsuiDrumrow-startCursor" ) ) {
			e.target.remove();
		}
	}
	_oncontextmenuRows( e ) {
		e.preventDefault();
		if ( e.target.dataset.action === "toggle" ) {
			this._dispatch( "change", "toggleSoloDrumrow", e.target.closest( ".gsuiDrumrow" ).dataset.id );
		} else if ( e.target.classList.contains( "gsuiDrumrow-propSpan" ) ) {
			this._dispatch( "propFilters", e.target.previousElementSibling.value );
		}
	}
	_ondropRows( e ) {
		if ( this._dragoverId ) {
			const [ patId ] = e.dataTransfer.getData( "pattern-buffer" ).split( ":" );

			if ( patId ) {
				this._dragoverId === Infinity
					? this._dispatch( "change", "addDrumrow", patId )
					: this._dispatch( "change", "changeDrumrowPattern", this._dragoverId, patId );
			}
		}
		this._ondragleaveRows();
	}
	_ondragleaveRows() {
		if ( this._elDragover ) {
			this._elDragover.classList.remove( "gsuiDrumrows-dragover" );
			this._elDragover =
			this._dragoverId = null;
		}
	}
	_ondragoverRows( e ) {
		if ( e.dataTransfer.types.includes( "pattern-buffer" ) ) {
			const tar = e.target,
				isParent = tar.classList.contains( "gsuiDrumrows" ),
				elDragover = isParent ? tar : tar.closest( ".gsuiDrumrow" );

			clearTimeout( this._timeoutIdDragleave );
			this._timeoutIdDragleave = setTimeout( () => this._ondragleaveRows(), 125 );
			if ( elDragover !== this._elDragover ) {
				this._dragoverId = null;
				if ( isParent ) {
					this._dragoverId = Infinity;
				} else if ( elDragover ) {
					this._dragoverId = elDragover.dataset.id;
				}
				if ( this._elDragover ) {
					this._elDragover.classList.remove( "gsuiDrumrows-dragover" );
				}
				this._elDragover = elDragover;
				if ( elDragover ) {
					elDragover.classList.add( "gsuiDrumrows-dragover" );
				}
			}
		}
	}
}

customElements.define( "gsui-drumrows", gsuiDrumrows );
<commit_msg>gsuiDrumrows: private fields<commit_after>"use strict";

class gsuiDrumrows extends HTMLElement {
	#rows = new Map()
	#lines = new Map()
	#dragoverId = null
	#elDragover = null
	#elLinesParent = null
	#timeoutIdDragleave = null
	#dispatch = GSUI.dispatchEvent.bind( null, this, "gsuiDrumrows" )
	#reorder = new gsuiReorder( {
		rootElement: this,
		direction: "column",
		dataTransferType: "drumrow",
		itemSelector: ".gsuiDrumrow",
		handleSelector: ".gsuiDrumrow-grip",
		parentSelector: ".gsuiDrumrows",
		onchange: this.#onreorderRows.bind( this ),
	} )

	constructor() {
		super();
		Object.seal( this );

		this.ondrop = this.#ondropRows.bind( this );
		this.onclick = this.#onclickRows.bind( this );
		this.onchange = this.#onchangeRows.bind( this );
		this.ondragover = this.#ondragoverRows.bind( this );
		this.ondragstart = e => e.stopPropagation();
		this.onmousedown = this.#onmousedownRows.bind( this );
		this.oncontextmenu = this.#oncontextmenuRows.bind( this );
		this.onanimationend = this.#onanimationendRows.bind( this );
	}

	// .........................................................................
	connectedCallback() {
		if ( !this.firstChild ) {
			this.classList.add( "gsuiDrumrows" );
			this.append( ...GSUI.getTemplate( "gsui-drumrows" ) );
		}
	}

	// .........................................................................
	setLinesParent( el, childClass ) {
		this.#elLinesParent = el;
		this.#reorder.setShadowElement( el );
		this.#reorder.setShadowChildClass( childClass );
	}
	reorderDrumrows( obj ) {
		gsuiReorder.listReorder( this, obj );
		gsuiReorder.listReorder( this.#elLinesParent, obj );
	}
	playRow( id ) {
		const rect = document.createElement( "div" );

		rect.classList.add( "gsuiDrumrow-startCursor" );
		this.#rows.get( id ).root.querySelector( ".gsuiDrumrow-waveWrap" ).append( rect );
	}
	stopRow( id ) {
		this.#rows.get( id ).root.querySelectorAll( ".gsuiDrumrow-startCursor" )
			.forEach( el => el.remove() );
	}
	setPropFilter( id, prop ) {
		this.#rows.get( id ).root.querySelector( `.gsuiDrumrow-propRadio[value="${ prop }"]` ).checked = true;
	}
	setDrumPropValue( rowId, prop, val ) {
		const el = this.#getPropBtn( rowId, prop ),
			fixval = prop === "detune" ? val : val.toFixed( 2 ),
			txtval = prop !== "gain"
				? `${ val > 0 ? "+" : "" }${ fixval }`
				: fixval;

		el.classList.add( "gsuiDrumrow-propSpanValue" );
		el.textContent = txtval;
	}
	removeDrumPropValue( rowId, prop ) {
		const el = this.#getPropBtn( rowId, prop );

		el.classList.remove( "gsuiDrumrow-propSpanValue" );
		el.textContent = prop === "detune" ? "pitch" : prop;
	}

	// .........................................................................
	add( id, elLine ) {
		const elRow = GSUI.getTemplate( "gsui-drumrow" ),
			sliDetune = elRow.querySelector( ".gsuiDrumrow-detune gsui-slider" ),
			sliGain = elRow.querySelector( ".gsuiDrumrow-gain gsui-slider" ),
			sliPan = elRow.querySelector( ".gsuiDrumrow-pan gsui-slider" ),
			html = {
				root: elRow,
				name: elRow.querySelector( ".gsuiDrumrow-name" ),
				detune: sliDetune,
				gain: sliGain,
				pan: sliPan,
			};

		elRow.dataset.id =
		elLine.dataset.id = id;
		sliDetune.oninput = val => {
			this.#namePrint( id, `pitch: ${ val > 0 ? "+" : "" }${ val }` );
			this.#dispatch( "liveChangeDrumrow", id, "detune", val );
		};
		sliGain.oninput = val => {
			this.#namePrint( id, `gain: ${ val.toFixed( 2 ) }` );
			this.#dispatch( "liveChangeDrumrow", id, "gain", val );
		};
		sliPan.oninput = val => {
			this.#namePrint( id, `pan: ${ val > 0 ? "+" : "" }${ val.toFixed( 2 ) }` );
			this.#dispatch( "liveChangeDrumrow", id, "pan", val );
		};
		sliDetune.onchange = this.#onchangeRowSlider.bind( this, id, "detune" );
		sliGain.onchange = this.#onchangeRowSlider.bind( this, id, "gain" );
		sliPan.onchange = this.#onchangeRowSlider.bind( this, id, "pan" );
		sliDetune.oninputend =
		sliGain.oninputend =
		sliPan.oninputend = this.#oninputendRowSlider.bind( this, id );
		this.#rows.set( id, html );
		this.#lines.set( id, elLine );
		this.append( elRow );
		this.#elLinesParent.append( elLine );
	}
	remove( id ) {
		this.#rows.get( id ).root.remove();
		this.#lines.get( id ).remove();
		this.#rows.delete( id );
		this.#lines.delete( id );
	}
	change( id, prop, val ) {
		switch ( prop ) {
			case "pan": this.#changePan( id, val ); break;
			case "name": this.#changeName( id, val ); break;
			case "gain": this.#changeGain( id, val ); break;
			case "order": this.#changeOrder( id, val ); break;
			case "detune": this.#changeDetune( id, val ); break;
			case "toggle": this.#changeToggle( id, val ); break;
			case "pattern": this.#changePattern( id, val ); break;
			case "duration": this.#changeDuration( id, val ); break;
		}
	}
	#changePan( id, val ) {
		this.#rows.get( id ).pan.setValue( val );
	}
	#changeGain( id, val ) {
		this.#rows.get( id ).gain.setValue( val );
	}
	#changeDetune( id, val ) {
		this.#rows.get( id ).detune.setValue( val );
	}
	#changeName( id, name ) {
		const el = this.#rows.get( id ).name;

		el.dataset.name =
		el.textContent = name;
	}
	#changeToggle( id, b ) {
		this.#rows.get( id ).root.classList.toggle( "gsuiDrumrow-mute", !b );
		this.#lines.get( id ).classList.toggle( "gsuiDrumrow-mute", !b );
	}
	#changeDuration( id, dur ) {
		this.#rows.get( id ).root.querySelector( ".gsuiDrumrow-waveWrap" ).style.animationDuration = `${ dur * 2 }s`;
	}
	#changePattern( id, svg ) {
		const elWave = this.#rows.get( id ).root.querySelector( ".gsuiDrumrow-waveWrap" );

		if ( elWave.firstChild ) {
			elWave.firstChild.remove();
		}
		if ( svg ) {
			svg.classList.add( "gsuiDrumrow-wave" );
			elWave.append( svg );
		}
	}
	#changeOrder( id, order ) {
		this.#rows.get( id ).root.dataset.order =
		this.#lines.get( id ).dataset.order = order;
	}

	// .........................................................................
	#namePrint( id, msg ) {
		const el = this.#rows.get( id ).name;

		el.textContent = msg;
		el.classList.add( "gsuiDrumrow-nameInfo" );
	}
	#expandProps( id ) {
		this.#rows.get( id ).root.classList.toggle( "gsuiDrumrow-open" );
		this.#lines.get( id ).classList.toggle( "gsuiDrums-lineOpen" );
	}
	#getPropBtn( rowId, prop ) {
		return this.#rows.get( rowId ).root
			.querySelector( `.gsuiDrumrow-propRadio[value="${ prop }"] + .gsuiDrumrow-propSpan` );
	}

	// events:
	// .........................................................................
	#oninputendRowSlider( id ) {
		const el = this.#rows.get( id ).name;

		el.textContent = el.dataset.name;
		el.classList.remove( "gsuiDrumrow-nameInfo" );
	}
	#onchangeRowSlider( id, prop, val ) {
		this.#dispatch( "change", "changeDrumrow", id, prop, val );
	}
	#onreorderRows( elRow ) {
		const rows = gsuiReorder.listComputeOrderChange( this, {} );

		this.#dispatch( "change", "reorderDrumrow", elRow.dataset.id, rows );
	}
	#onchangeRows( e ) {
		const id = e.target.closest( ".gsuiDrumrow" ).dataset.id;

		this.#dispatch( "propFilter", id, e.target.value );
	}
	#onclickRows( e ) {
		if ( e.target !== this ) {
			const id = e.target.closest( ".gsuiDrumrow" ).dataset.id;

			switch ( e.target.dataset.action ) {
				case "props": this.#expandProps( id ); break;
				case "toggle": this.#dispatch( "change", "toggleDrumrow", id ); break;
				case "delete": this.#dispatch( "change", "removeDrumrow", id ); break;
			}
		}
	}
	#onmousedownRows( e ) {
		if ( ( e.button === 0 || e.button === 2 ) && e.target.classList.contains( "gsuiDrumrow-main" ) ) {
			this.#dispatch(
				e.button === 0 ? "liveStartDrum" : "liveStopDrum",
				e.target.parentNode.dataset.id );
		}
	}
	#onanimationendRows( e ) {
		if ( e.target.classList.contains( "gsuiDrumrow-startCursor" ) ) {
			e.target.remove();
		}
	}
	#oncontextmenuRows( e ) {
		e.preventDefault();
		if ( e.target.dataset.action === "toggle" ) {
			this.#dispatch( "change", "toggleSoloDrumrow", e.target.closest( ".gsuiDrumrow" ).dataset.id );
		} else if ( e.target.classList.contains( "gsuiDrumrow-propSpan" ) ) {
			this.#dispatch( "propFilters", e.target.previousElementSibling.value );
		}
	}
	#ondropRows( e ) {
		if ( this.#dragoverId ) {
			const [ patId ] = e.dataTransfer.getData( "pattern-buffer" ).split( ":" );

			if ( patId ) {
				this.#dragoverId === Infinity
					? this.#dispatch( "change", "addDrumrow", patId )
					: this.#dispatch( "change", "changeDrumrowPattern", this.#dragoverId, patId );
			}
		}
		this.#ondragleaveRows();
	}
	#ondragleaveRows() {
		if ( this.#elDragover ) {
			this.#elDragover.classList.remove( "gsuiDrumrows-dragover" );
			this.#elDragover =
			this.#dragoverId = null;
		}
	}
	#ondragoverRows( e ) {
		if ( e.dataTransfer.types.includes( "pattern-buffer" ) ) {
			const tar = e.target,
				isParent = tar.classList.contains( "gsuiDrumrows" ),
				elDragover = isParent ? tar : tar.closest( ".gsuiDrumrow" );

			clearTimeout( this.#timeoutIdDragleave );
			this.#timeoutIdDragleave = setTimeout( () => this.#ondragleaveRows(), 125 );
			if ( elDragover !== this.#elDragover ) {
				this.#dragoverId = null;
				if ( isParent ) {
					this.#dragoverId = Infinity;
				} else if ( elDragover ) {
					this.#dragoverId = elDragover.dataset.id;
				}
				if ( this.#elDragover ) {
					this.#elDragover.classList.remove( "gsuiDrumrows-dragover" );
				}
				this.#elDragover = elDragover;
				if ( elDragover ) {
					elDragover.classList.add( "gsuiDrumrows-dragover" );
				}
			}
		}
	}
}

customElements.define( "gsui-drumrows", gsuiDrumrows );
<|endoftext|>


<commit_before>import DS from 'ember-data';

var Device = DS.Model.extend({
    nitrogen_id: DS.attr('string'),
    name: DS.attr('string'),
    status: DS.attr('boolean', {defaultValue: false}),
    lastUpdated: DS.attr('number'),
    last_connection: DS.attr('string'),
    last_ip: DS.attr('string'),
    nickname: DS.attr('string'),
    created_at: DS.attr('string'),
    updated_at: DS.attr('string'),
    tags: DS.attr(),

    // Relations
    owner: DS.belongsTo('user', {async: true})
});

export default Device;
<commit_msg>Add Type and Location to Device Model<commit_after>import DS from 'ember-data';

var Device = DS.Model.extend({
    nitrogen_id: DS.attr('string'),
    name: DS.attr('string'),
    status: DS.attr('boolean', {defaultValue: false}),
    lastUpdated: DS.attr('number'),
    last_connection: DS.attr('string'),
    last_ip: DS.attr('string'),
    nickname: DS.attr('string'),
    created_at: DS.attr('string'),
    updated_at: DS.attr('string'),
    tags: DS.attr(),
    type: DS.attr(),
    location: DS.attr(),

    // Relations
    owner: DS.belongsTo('user', {async: true})
});

export default Device;
<|endoftext|>


<commit_before>window = require('jsdom').jsdom().createWindow();
document = window.document;
jQuery = require('jquery');
$ = jQuery;
jqueryJasmine = require('jasmine-jquery');

require('../../jquery.videosequence');

describe('$.videosequence, $.audiosequence', function() {
  beforeEach(function() {
    setFixtures(
      '
' +
        '<video id="video-with-no-specs"></video>' +
        '<audio id="audio-with-no-specs"></audio>' +

        '

' +

        '<video data-rel="videosequence"' +
          ' data-videosequence-sources=\'["video-1.webm","video-2.webm"]\'' +
          ' data-videosequence-offsets=\'[0,3]\'>' +
        '</video>' +
        '<audio data-rel="audiosequence"' +
          ' data-audiosequence-sources=\'["audio-1.webm","audio-2.webm"]\'' +
          ' data-audiosequence-offsets=\'[6,9]\'>' +
        '</audio>' +
      '
'
    );
  });

  it('raises an error if called on a wrong tag', function() {
    expect(function() {
      $('#wrong-tag').videosequence({});
    }).toThrow('Called $.videosequence on a non VIDEO tag.');

    expect(function() {
      $('#wrong-tag').audiosequence({});
    }).toThrow('Called $.audiosequence on a non AUDIO tag.');
  });

  it('raises an error if called with no specs', function() {
    expect(function() {
      $('#video-with-no-specs').videosequence();
    }).toThrow('Called $.videosequence with no specs given.');

    expect(function() {
      $('#audio-with-no-specs').audiosequence();
    }).toThrow('Called $.audiosequence with no specs given.');
  });

  describe('with data-attrs', function() {
    beforeEach(function() {
      spyOn($.prototype, 'videosequence');
      spyOn($.prototype, 'audiosequence');
    });

    it('takes the values from them', function() {
      $(document).trigger('videosequence:initialize');
      expect($.prototype.videosequence).toHaveBeenCalledWith([
        {source: 'video-1.webm', timestampOffset: 0},
        {source: 'video-2.webm', timestampOffset: 3}
      ]);

      $(document).trigger('audiosequence:initialize');
      expect($.prototype.audiosequence).toHaveBeenCalledWith([
        {source: 'audio-1.webm', timestampOffset: 6},
        {source: 'audio-2.webm', timestampOffset: 9}
      ]);
    });
  });
});
<commit_msg>Fixed wrong call in specs<commit_after>window = require('jsdom').jsdom().createWindow();
document = window.document;
jQuery = require('jquery');
$ = jQuery;
jqueryJasmine = require('jasmine-jquery');

require('../../jquery.videosequence');

describe('$.videosequence, $.audiosequence', function() {
  beforeEach(function() {
    setFixtures(
      '
' +
        '<video id="video-with-no-specs"></video>' +
        '<audio id="audio-with-no-specs"></audio>' +

        '

' +

        '<video data-rel="videosequence"' +
          ' data-videosequence-sources=\'["video-1.webm","video-2.webm"]\'' +
          ' data-videosequence-offsets=\'[0,3]\'>' +
        '</video>' +
        '<audio data-rel="audiosequence"' +
          ' data-audiosequence-sources=\'["audio-1.webm","audio-2.webm"]\'' +
          ' data-audiosequence-offsets=\'[6,9]\'>' +
        '</audio>' +
      '
'
    );
  });

  it('raises an error if called on a wrong tag', function() {
    expect(function() {
      $('#wrong-tag').videosequence();
    }).toThrow('Called $.videosequence on a non VIDEO tag.');

    expect(function() {
      $('#wrong-tag').audiosequence();
    }).toThrow('Called $.audiosequence on a non AUDIO tag.');
  });

  it('raises an error if called with no specs', function() {
    expect(function() {
      $('#video-with-no-specs').videosequence();
    }).toThrow('Called $.videosequence with no specs given.');

    expect(function() {
      $('#audio-with-no-specs').audiosequence();
    }).toThrow('Called $.audiosequence with no specs given.');
  });

  describe('with data-attrs', function() {
    beforeEach(function() {
      spyOn($.prototype, 'videosequence');
      spyOn($.prototype, 'audiosequence');
    });

    it('takes the values from them', function() {
      $(document).trigger('videosequence:initialize');
      expect($.prototype.videosequence).toHaveBeenCalledWith([
        {source: 'video-1.webm', timestampOffset: 0},
        {source: 'video-2.webm', timestampOffset: 3}
      ]);

      $(document).trigger('audiosequence:initialize');
      expect($.prototype.audiosequence).toHaveBeenCalledWith([
        {source: 'audio-1.webm', timestampOffset: 6},
        {source: 'audio-2.webm', timestampOffset: 9}
      ]);
    });
  });
});
<|endoftext|>


<commit_before>goog.provide('ol.test.expression.Parser');

describe('ol.expression.Parser', function() {

  describe('constructor', function() {
    it('creates a new expression parser', function() {
      var parser = new ol.expression.Parser();
      expect(parser).to.be.a(ol.expression.Parser);
    });
  });

  describe('#parseArguments_()', function() {

    function parse(source) {
      var lexer = new ol.expression.Lexer(source);
      var parser = new ol.expression.Parser();
      return parser.parseArguments_(lexer);
    }

    it('parses comma separated expressions in parens', function() {
      var args = parse('(1/3, "foo", true)');
      expect(args).length(3);

      expect(args[0]).to.be.a(ol.expression.Math);
      expect(args[0].evaluate()).to.be(1 / 3);

      expect(args[1]).to.be.a(ol.expression.Literal);
      expect(args[1].evaluate()).to.be('foo');

      expect(args[2]).to.be.a(ol.expression.Literal);
      expect(args[2].evaluate()).to.be(true);
    });

    it('throws on invalid arg expression', function() {
      expect(function() {
        parse('(6e)');
      }).throwException();
    });

    it('throws on unterminated args', function() {
      expect(function() {
        parse('("foo", 42, )');
      }).throwException();
    });

  });

  describe('#parseGroupExpression_()', function() {

    function parse(source) {
      var lexer = new ol.expression.Lexer(source);
      var parser = new ol.expression.Parser();
      return parser.parseGroupExpression_(lexer);
    }

    it('parses grouped expressions', function() {
      var expr = parse('(3 * (foo + 2))');
      expect(expr).to.be.a(ol.expression.Math);
      expect(expr.evaluate({foo: 3})).to.be(15);
    });

  });

  describe('#parsePrimaryExpression_()', function() {

    function parse(source) {
      var lexer = new ol.expression.Lexer(source);
      var parser = new ol.expression.Parser();
      return parser.parsePrimaryExpression_(lexer);
    }

    it('parses string literal', function() {
      var expr = parse('"foo"');
      expect(expr).to.be.a(ol.expression.Literal);
      expect(expr.evaluate()).to.be('foo');
    });

    it('parses numeric literal', function() {
      var expr = parse('.42e2');
      expect(expr).to.be.a(ol.expression.Literal);
      expect(expr.evaluate()).to.be(42);
    });

    it('parses boolean literal', function() {
      var expr = parse('.42e2');
      expect(expr).to.be.a(ol.expression.Literal);
      expect(expr.evaluate()).to.be(42);
    });

    it('parses null literal', function() {
      var expr = parse('null');
      expect(expr).to.be.a(ol.expression.Literal);
      expect(expr.evaluate()).to.be(null);
    });

  });

});

goog.require('ol.expression.Expression');
goog.require('ol.expression.Lexer');
goog.require('ol.expression.Math');
goog.require('ol.expression.Parser');
<commit_msg>Binary expression parsing<commit_after>goog.provide('ol.test.expression.Parser');

describe('ol.expression.Parser', function() {

  describe('constructor', function() {
    it('creates a new expression parser', function() {
      var parser = new ol.expression.Parser();
      expect(parser).to.be.a(ol.expression.Parser);
    });
  });

  describe('#parseArguments_()', function() {

    function parse(source) {
      var lexer = new ol.expression.Lexer(source);
      var parser = new ol.expression.Parser();
      return parser.parseArguments_(lexer);
    }

    it('parses comma separated expressions in parens', function() {
      var args = parse('(1/3, "foo", true)');
      expect(args).length(3);

      expect(args[0]).to.be.a(ol.expression.Math);
      expect(args[0].evaluate()).to.be(1 / 3);

      expect(args[1]).to.be.a(ol.expression.Literal);
      expect(args[1].evaluate()).to.be('foo');

      expect(args[2]).to.be.a(ol.expression.Literal);
      expect(args[2].evaluate()).to.be(true);
    });

    it('throws on invalid arg expression', function() {
      expect(function() {
        parse('(6e)');
      }).throwException();
    });

    it('throws on unterminated args', function() {
      expect(function() {
        parse('("foo", 42, )');
      }).throwException();
    });

  });

  describe('#parseBinaryExpression_()', function() {

    function parse(source) {
      var lexer = new ol.expression.Lexer(source);
      var parser = new ol.expression.Parser();
      return parser.parseBinaryExpression_(lexer);
    }

    it('works with multiplicitave operators', function() {
      var expr = parse('4 * 1e4');
      expect(expr).to.be.a(ol.expression.Math);
      expect(expr.evaluate()).to.be(40000);

      expect(parse('10/3').evaluate()).to.be(10 / 3);
    });

    it('works with additive operators', function() {
      var expr = parse('4 +1e4');
      expect(expr).to.be.a(ol.expression.Math);
      expect(expr.evaluate()).to.be(10004);

      expect(parse('10-3').evaluate()).to.be(7);
    });

    it('works with relational operators', function() {
      var expr = parse('4 < 1e4');
      expect(expr).to.be.a(ol.expression.Comparison);
      expect(expr.evaluate()).to.be(true);

      expect(parse('10<3').evaluate()).to.be(false);
      expect(parse('10 <= "10"').evaluate()).to.be(true);
      expect(parse('10 > "10"').evaluate()).to.be(false);
      expect(parse('10 >= 9').evaluate()).to.be(true);
    });

    it('works with equality operators', function() {
      var expr = parse('4 == 1e4');
      expect(expr).to.be.a(ol.expression.Comparison);
      expect(expr.evaluate()).to.be(false);

      expect(parse('10!=3').evaluate()).to.be(true);
      expect(parse('10 == "10"').evaluate()).to.be(true);
      expect(parse('10 === "10"').evaluate()).to.be(false);
      expect(parse('10 !== "10"').evaluate()).to.be(true);
    });

    it('works with binary logical operators', function() {
      var expr = parse('true && false');
      expect(expr).to.be.a(ol.expression.Logical);
      expect(expr.evaluate()).to.be(false);

      expect(parse('false||true').evaluate()).to.be(true);
      expect(parse('false || false').evaluate()).to.be(false);
      expect(parse('true &&true').evaluate()).to.be(true);
    });

    it('throws for invalid binary expression', function() {
      expect(function() {
        parse('4 * / 2');
      }).throwException();
    });

  });

  describe('#parseGroupExpression_()', function() {

    function parse(source) {
      var lexer = new ol.expression.Lexer(source);
      var parser = new ol.expression.Parser();
      return parser.parseGroupExpression_(lexer);
    }

    it('parses grouped expressions', function() {
      var expr = parse('(3 * (foo + 2))');
      expect(expr).to.be.a(ol.expression.Math);
      expect(expr.evaluate({foo: 3})).to.be(15);
    });

  });

  describe('#parsePrimaryExpression_()', function() {

    function parse(source) {
      var lexer = new ol.expression.Lexer(source);
      var parser = new ol.expression.Parser();
      return parser.parsePrimaryExpression_(lexer);
    }

    it('parses string literal', function() {
      var expr = parse('"foo"');
      expect(expr).to.be.a(ol.expression.Literal);
      expect(expr.evaluate()).to.be('foo');
    });

    it('parses numeric literal', function() {
      var expr = parse('.42e2');
      expect(expr).to.be.a(ol.expression.Literal);
      expect(expr.evaluate()).to.be(42);
    });

    it('parses boolean literal', function() {
      var expr = parse('.42e2');
      expect(expr).to.be.a(ol.expression.Literal);
      expect(expr.evaluate()).to.be(42);
    });

    it('parses null literal', function() {
      var expr = parse('null');
      expect(expr).to.be.a(ol.expression.Literal);
      expect(expr.evaluate()).to.be(null);
    });

  });

});

goog.require('ol.expression.Expression');
goog.require('ol.expression.Lexer');
goog.require('ol.expression.Math');
goog.require('ol.expression.Parser');
<|endoftext|>


<commit_before>var fs = require('graceful-fs')
var path = require('path')

var mkdirp = require('mkdirp')
var osenv = require('osenv')
var rimraf = require('rimraf')
var test = require('tap').test

var common = require('../common-tap')

var pkg = path.resolve(__dirname, 'scripts-whitespace-windows')
var tmp = path.resolve(pkg, 'tmp')
var cache = path.resolve(pkg, 'cache')
var dep = path.resolve(pkg, 'dep')

var EXEC_OPTS = { cwd: pkg }

var json = {
  name: 'scripts-whitespace-windows',
  version: '1.0.0',
  description: 'a test',
  repository: 'git://github.com/robertkowalski/bogus',
  scripts: {
    foo: 'foo --title \"Analysis of\" --recurse -d report src'
  },
  dependencies: {
    'scripts-whitespace-windows-dep': '0.0.1'
  },
  license: 'WTFPL'
}

var dependency = {
  name: 'scripts-whitespace-windows-dep',
  version: '0.0.1',
  bin: [ 'bin/foo' ]
}

var foo = function () {/*
#!/usr/bin/env node

if (process.argv.length === 8)
  console.log('npm-test-fine')
*/}.toString().split('\n').slice(1, -1).join('\n')

test('setup', function (t) {
  cleanup()
  mkdirp.sync(tmp)
  fs.writeFileSync(
    path.join(pkg, 'package.json'),
    JSON.stringify(json, null, 2)
  )
  fs.writeFileSync(
    path.join(pkg, 'README.md'),
    "### THAT'S RIGHT\n"
  )

  mkdirp.sync(path.join(dep, 'bin'))
  fs.writeFileSync(
    path.join(dep, 'package.json'),
    JSON.stringify(dependency, null, 2)
  )
  fs.writeFileSync(path.join(dep, 'bin', 'foo'), foo)

  common.npm(['i', dep], {
    cwd: pkg,
    env: {
      npm_config_cache: cache,
      npm_config_tmp: tmp,
      npm_config_prefix: pkg,
      npm_config_global: 'false'
    }
  }, function (err, code, stdout, stderr) {
    t.ifErr(err, 'npm i ' + dep + ' finished without error')
    t.equal(code, 0, 'npm i ' + dep + ' exited ok')
    console.log('stderr', stderr)
    t.notOk(stderr, 'no output stderr')
    t.end()
  })
})

test('test', function (t) {
  common.npm(['run', 'foo'], EXEC_OPTS, function (err, code, stdout, stderr) {
    stderr = stderr.trim()
    if (stderr)
      console.error(stderr)
    t.ifErr(err, 'npm run finished without error')
    t.equal(code, 0, 'npm run exited ok')
    t.notOk(stderr, 'no output stderr: ' + stderr)
    stdout = stdout.trim()
    t.ok(/npm-test-fine/.test(stdout))
    t.end()
  })
})

test('cleanup', function (t) {
  cleanup()
  t.end()
})

function cleanup () {
  process.chdir(osenv.tmpdir())
  rimraf.sync(pkg)
}

<commit_msg>test: remove spurious output<commit_after>var fs = require('graceful-fs')
var path = require('path')

var mkdirp = require('mkdirp')
var osenv = require('osenv')
var rimraf = require('rimraf')
var test = require('tap').test

var common = require('../common-tap')

var pkg = path.resolve(__dirname, 'scripts-whitespace-windows')
var tmp = path.resolve(pkg, 'tmp')
var cache = path.resolve(pkg, 'cache')
var dep = path.resolve(pkg, 'dep')

var EXEC_OPTS = { cwd: pkg }

var json = {
  name: 'scripts-whitespace-windows',
  version: '1.0.0',
  description: 'a test',
  repository: 'git://github.com/robertkowalski/bogus',
  scripts: {
    foo: 'foo --title \"Analysis of\" --recurse -d report src'
  },
  dependencies: {
    'scripts-whitespace-windows-dep': '0.0.1'
  },
  license: 'WTFPL'
}

var dependency = {
  name: 'scripts-whitespace-windows-dep',
  version: '0.0.1',
  bin: [ 'bin/foo' ]
}

var foo = function () {/*
#!/usr/bin/env node

if (process.argv.length === 8)
  console.log('npm-test-fine')
*/}.toString().split('\n').slice(1, -1).join('\n')

test('setup', function (t) {
  cleanup()
  mkdirp.sync(tmp)
  fs.writeFileSync(
    path.join(pkg, 'package.json'),
    JSON.stringify(json, null, 2)
  )
  fs.writeFileSync(
    path.join(pkg, 'README.md'),
    "### THAT'S RIGHT\n"
  )

  mkdirp.sync(path.join(dep, 'bin'))
  fs.writeFileSync(
    path.join(dep, 'package.json'),
    JSON.stringify(dependency, null, 2)
  )
  fs.writeFileSync(path.join(dep, 'bin', 'foo'), foo)

  common.npm(['i', dep], {
    cwd: pkg,
    env: {
      npm_config_cache: cache,
      npm_config_tmp: tmp,
      npm_config_prefix: pkg,
      npm_config_global: 'false'
    }
  }, function (err, code, stdout, stderr) {
    t.ifErr(err, 'npm i ' + dep + ' finished without error')
    t.equal(code, 0, 'npm i ' + dep + ' exited ok')
    t.notOk(stderr, 'no output stderr')
    t.end()
  })
})

test('test', function (t) {
  common.npm(['run', 'foo'], EXEC_OPTS, function (err, code, stdout, stderr) {
    stderr = stderr.trim()
    if (stderr) console.error(stderr)
    t.ifErr(err, 'npm run finished without error')
    t.equal(code, 0, 'npm run exited ok')
    t.notOk(stderr, 'no output stderr: ' + stderr)
    stdout = stdout.trim()
    t.ok(/npm-test-fine/.test(stdout))
    t.end()
  })
})

test('cleanup', function (t) {
  cleanup()
  t.end()
})

function cleanup () {
  process.chdir(osenv.tmpdir())
  rimraf.sync(pkg)
}

<|endoftext|>