<commit_before>/* global describe */
/* global it */
/* global before */
'use strict'
let assert = require('assert')
let $ = require('meeko')
let Config = require('../config.js')
let db = require('../index')(Config.zc.mysql)
/* let co = require('hprose').co
co(function* () {
  yield $.tools.wait(1000);
  let r = db.test.R({
    "aaa->'$[1].\"2\"'": "22",
    'x': 1
  }).get();
  r = db.test.U({}, {
    aaa: 'json_set(aaa,\'$[0]."1"\\\',18)'
  }, 1).get()
  r = db.test.insert({
    cell: '1',
    'd1': new Date()
  }).get()
  $.log(r)
}); */
describe('mongoDB转MySQL增删改查基础的单元测试', function () {
  before(function * () {
    yield $.tools.wait(2000)
  })
  it('1.find&findone测试', function * () {
    assert.strictEqual(db.test.find().get(), 'select * from `test`;')
    assert.strictEqual(db.test.R().get(), 'select * from `test`;')
    assert.strictEqual(db.test.select().get(), 'select * from `test`;')
    assert.strictEqual(db.test.find({
      'time': {
        '>=': 123,
        '<': 1000
      }
    }).get(), 'select * from `test` where `time`>=123 and `time`<1000;')
    assert.strictEqual(db.test.find({}, {
      cell: 1,
      'min(id)': 1
    }).get(), 'select `cell`,`min(id)` from `test`;')
    assert.strictEqual(db.test.find({}, {}, {
      a: 1,
      b: -1
    }).get(), 'select * from `test` order by `a` asc, `b` desc;')
    assert.strictEqual(db.test.find({}, {}, {}, 5).get(), 'select * from `test` limit 5;')
    assert.strictEqual(db.test.findOne().get(), 'select * from `test` limit 1;')
    assert.strictEqual(db.test.R({
      cell: '13052000000'
    }).get(), "select * from `test` where `cell`='13052000000';", db.test.R({
      cell: '13052000000'
    }).get())
    assert.strictEqual(db.test.R({
      cell: true
    }).get(), 'select * from `test` where `cell`=true;')
  })

  it('2.remove测试', function * () {
    assert.strictEqual(db.test.remove().get(), '[Empty!!]')
    assert.strictEqual(db.test.remove({}, 1).get(), 'delete from `test`;')
    assert.strictEqual(db.test.D({}, 1).get(), 'delete from `test`;')
    assert.strictEqual(db.test.delete({}, 1).get(), 'delete from `test`;')
    assert.strictEqual(db.test.remove({
      'time': {
        '>=': 123,
        '<': 1000
      }
    }).get(), 'delete from `test` where `time`>=123 and `time`<1000;')
  })

  it('3.update测试', function * () {
    assert.strictEqual(db.test.U({
      id: 11
    }).get(), '[Empty!!]')
    assert.strictEqual(db.test.update().get(), '[Empty!!]')
    assert.strictEqual(db.test.update({}, {
      cell: 1,
      'min(id)': 1
    }).get(), '[Empty!!]')
    assert.strictEqual(db.test.update({}, {
      cell: 1,
      'min(id)': 1
    }, 1).get(), 'update `test` set `cell`=1,`min(id)`=1;')
    assert.strictEqual(db.test.U({}, {
      cell: 1,
      'min(id)': 1
    }, 1).get(), 'update `test` set `cell`=1,`min(id)`=1;')
    assert.strictEqual(db.test.update({
      'time': {
        '>=': 123,
        '<': 1000
      }
    }, {
      cell: 1,
      'min(id)': 1
    }).get(), 'update `test` set `cell`=1,`min(id)`=1 where `time`>=123 and `time`<1000;')
  })

  it('4.insert测试', function * () {
    assert.strictEqual(db.test.insert().get(), '[Empty!!]')
    assert.strictEqual(db.test.insert({
      cell: 1,
      'min(id)': 1
    }).get(), 'insert into `test` (`cell`,`min(id)`) values (1,1);')
    assert.strictEqual(db.test.C({
      cell: 1,
      'min(id)': 1
    }).get(), 'insert into `test` (`cell`,`min(id)`) values (1,1);')
    assert.strictEqual(db.test.C({
      cell: 'x',
      'min(id)': 1
    }).get(), 'insert into `test` (`cell`,`min(id)`) values (\'x\',1);')
    assert.strictEqual(db.test.C({
      cell: 'md5(x)',
      'min(id)': 1
    }).get(), 'insert into `test` (`cell`,`min(id)`) values (md5(x),1);')
    assert.strictEqual(db.test.C({
      cell: '\'md5(x)\'',
      'min(id)': 1
    }).get(), 'insert into `test` (`cell`,`min(id)`) values (\'md5(x)\',1);')
    assert.strictEqual(db.test.C({
      cell: 'x=1',
      'min(id)': 1
    }).get(), 'insert into `test` (`cell`,`min(id)`) values (\'x=1\',1);')
    assert.strictEqual(db.test.insert({
      cell: '1',
      'd1': new Date('2017-01-18T12:20:57.240Z')
    }).get(), 'insert into `test` (`cell`,`d1`) values (\'1\', "2017-01-18T12:20:57.240Z");')
    assert.strictEqual(db.test.insert({
      cell: '1',
      'd1': null
    }).get(), 'insert into `test` (`cell`,`d1`) values (\'1\', NULL);')
    assert.strictEqual(db.test.insert({
      cell: '1',
      'd1': undefined
    }).get(), 'insert into `test` (`cell`,`d1`) values (\'1\', NULL);')
    assert.strictEqual(db.test.insert({
      cell: '1',
      'd1': [1, 4]
    }).get(), 'insert into `test` (`cell`,`d1`) values (\'1\', \'[1,4]\');')
    assert.strictEqual(db.test.insert({
      cell: '1',
      'd1': {
        a: 1,
        b: '2'
      }
    }).get(), 'insert into `test` (`cell`,`d1`) values (\'1\', \'{"a":1,"b":"2"}\');')
    assert.strictEqual(db.test.insert({
      cell: '1',
      'd1': /kong+/g
    }).get(), 'insert into `test` (`cell`,`d1`) values (\'1\', \'{}\');')
  })
  it('4-1.insert唯一插入测试', function * () {
    assert.strictEqual(db.test.insert({
      cell: '1',
      'phone': 1
    }, 'phone').get(), 'insert into `test` (`cell`,`phone`) select \'1\',1 from dual WHERE NOT EXISTS(SELECT `phone` FROM `test` WHERE `phone` = 1) limit 1;')
    assert.strictEqual(db.test.insert({
      cell: '1',
      'phone': 1
    }, 'cell').get(), 'insert into `test` (`cell`,`phone`) select \'1\',1 from dual WHERE NOT EXISTS(SELECT `cell` FROM `test` WHERE `cell` = \'1\') limit 1;')
  })
  it('5.cmd测试', function * () {
    assert.strictEqual(db.test.cmd('show databases;').get(), 'show databases;')
    assert.strictEqual(db.test.cmd('show databases').get(), 'show databases;')
    assert.strictEqual(db.cmd('show databases').get(), 'show databases;')
  })
  it('6.特殊类型函数条件测试', function * () {
    assert.strictEqual(db.test.R({
      'ax(id)': 1
    }).get(), 'select * from `test` where `ax(id)`=1;')
    assert.strictEqual(db.test.R({
      'md5': 'md5(id)+max(id)'
    }).get(), 'select * from `test` where `md5`=md5(id)+max(id);')
    assert.strictEqual(db.test.R({
      'md5': '\'md5(id)\''
    }).get(), 'select * from `test` where `md5`=\'md5(id)\';')
    assert.strictEqual(db.test.R({
      'md5': null
    }).get(), 'select * from `test` where `md5` is NULL;')
    assert.strictEqual(db.test.R({
      'time': new Date('2016-01-01 12:12:13')
    }).get(), "select * from `test` where `time`='2016-01-01 12:12:13';")
    assert.strictEqual(db.test.R({
      'name': /%kong/g
    }).get(), "select * from `test` where `name` like '%kong';")
    assert.strictEqual(db.test.R({
      'name': /kong%/g
    }).get(), "select * from `test` where `name` like 'kong%';")
    assert.strictEqual(db.test.R({
      'name': /%kong%/g
    }).get(), "select * from `test` where `name` like '%kong%';")
    assert.strictEqual(db.test.R({
      'name': [1, 'x', 3]
    }).get(), "select * from `test` where `name` in (1,'x',3);", db.test.R({
      'name': [1, 'x', 3]
    }).get())
  })
  it('7.exec测试', function * () {
    let rs = yield db.cmd('select `id` from `test` limit 1;').exec()
    let obj = yield db.test.R({
      id: rs[0].id
    }, {}, {}, 1).exec()
    assert.strictEqual(obj[0].id, rs[0].id)
    obj = yield db.test.R({
      id: rs[0].id
    }, {}, {}, 1).exec(true, true)
    assert.strictEqual(obj[1][0].id, rs[0].id)
    obj = yield db.test.R({
      idx: 1001
    }, {}, {}, 1).exec()
    assert.strictEqual(obj, -1)
    obj = yield db.test.R({
      id: rs[0].id
    }, {}, {}, 1).exec(true)
    assert.strictEqual(obj[1][0].id, rs[0].id)
    obj = yield db.test.R({
      idx: 1001
    }, {}, {}, 1).exec(true, true)
    assert.strictEqual(obj, -1)
    process.exit(0)
  })
})
<commit_msg>增加run函数的覆盖<commit_after>/* global describe */
/* global it */
/* global before */
'use strict'
let assert = require('assert')
let $ = require('meeko')
let Config = require('../config.js')
let db = require('../index')(Config.zc.mysql)
/* let co = require('co')
co(function* () {
  yield $.tools.wait(1000);
  let r = db.test.R({
    "aaa->'$[1].\"2\"'": "22",
    'x': 1
  }).get();
  r = db.test.U({}, {
    aaa: 'json_set(aaa,\'$[0]."1"\\\',18)'
  }, 1).get()
  r = db.test.insert({
    cell: '1',
    'd1': new Date()
  }).get()
  $.log(r)
}); */
function wait (t) {
  return new Promise((resolve, reject) => {
    try {
      setTimeout(() => {
        resolve()
      }, t)
    } catch (err) {
      reject(err)
    }
  })
}
describe('mongoDB转MySQL增删改查基础的单元测试', function () {
  before(async () => {
    await wait(1000)
  })
  it('1.find&findone测试', async () => {
    assert.strictEqual(db.test.find().get(), 'select * from `test`;')
    assert.strictEqual(db.test.R().get(), 'select * from `test`;')
    assert.strictEqual(db.test.select().get(), 'select * from `test`;')
    assert.strictEqual(db.test.find({
      'time': {
        '>=': 123,
        '<': 1000
      }
    }).get(), 'select * from `test` where `time`>=123 and `time`<1000;')
    assert.strictEqual(db.test.find({}, {
      cell: 1,
      'min(id)': 1
    }).get(), 'select `cell`,`min(id)` from `test`;')
    assert.strictEqual(db.test.find({}, {}, {
      a: 1,
      b: -1
    }).get(), 'select * from `test` order by `a` asc, `b` desc;')
    assert.strictEqual(db.test.find({}, {}, {}, 5).get(), 'select * from `test` limit 5;')
    assert.strictEqual(db.test.findOne().get(), 'select * from `test` limit 1;')
    assert.strictEqual(db.test.R({
      cell: '13052000000'
    }).get(), "select * from `test` where `cell`='13052000000';", db.test.R({
      cell: '13052000000'
    }).get())
    assert.strictEqual(db.test.R({
      cell: true
    }).get(), 'select * from `test` where `cell`=true;')
  })

  it('2.remove测试', async () => {
    assert.strictEqual(db.test.remove().get(), '[Empty!!]')
    assert.strictEqual(db.test.remove({}, 1).get(), 'delete from `test`;')
    assert.strictEqual(db.test.D({}, 1).get(), 'delete from `test`;')
    assert.strictEqual(db.test.delete({}, 1).get(), 'delete from `test`;')
    assert.strictEqual(db.test.remove({
      'time': {
        '>=': 123,
        '<': 1000
      }
    }).get(), 'delete from `test` where `time`>=123 and `time`<1000;')
  })

  it('3.update测试', async () => {
    assert.strictEqual(db.test.U({
      id: 11
    }).get(), '[Empty!!]')
    assert.strictEqual(db.test.update().get(), '[Empty!!]')
    assert.strictEqual(db.test.update({}, {
      cell: 1,
      'min(id)': 1
    }).get(), '[Empty!!]')
    assert.strictEqual(db.test.update({}, {
      cell: 1,
      'min(id)': 1
    }, 1).get(), 'update `test` set `cell`=1,`min(id)`=1;')
    assert.strictEqual(db.test.U({}, {
      cell: 1,
      'min(id)': 1
    }, 1).get(), 'update `test` set `cell`=1,`min(id)`=1;')
    assert.strictEqual(db.test.update({
      'time': {
        '>=': 123,
        '<': 1000
      }
    }, {
      cell: 1,
      'min(id)': 1
    }).get(), 'update `test` set `cell`=1,`min(id)`=1 where `time`>=123 and `time`<1000;')
  })

  it('4.insert测试', async () => {
    assert.strictEqual(db.test.insert().get(), '[Empty!!]')
    assert.strictEqual(db.test.insert({
      cell: 1,
      'min(id)': 1
    }).get(), 'insert into `test` (`cell`,`min(id)`) values (1,1);')
    assert.strictEqual(db.test.C({
      cell: 1,
      'min(id)': 1
    }).get(), 'insert into `test` (`cell`,`min(id)`) values (1,1);')
    assert.strictEqual(db.test.C({
      cell: 'x',
      'min(id)': 1
    }).get(), 'insert into `test` (`cell`,`min(id)`) values (\'x\',1);')
    assert.strictEqual(db.test.C({
      cell: 'md5(x)',
      'min(id)': 1
    }).get(), 'insert into `test` (`cell`,`min(id)`) values (md5(x),1);')
    assert.strictEqual(db.test.C({
      cell: '\'md5(x)\'',
      'min(id)': 1
    }).get(), 'insert into `test` (`cell`,`min(id)`) values (\'md5(x)\',1);')
    assert.strictEqual(db.test.C({
      cell: 'x=1',
      'min(id)': 1
    }).get(), 'insert into `test` (`cell`,`min(id)`) values (\'x=1\',1);')
    assert.strictEqual(db.test.insert({
      cell: '1',
      'd1': new Date('2017-01-18T12:20:57.240Z')
    }).get(), 'insert into `test` (`cell`,`d1`) values (\'1\', "2017-01-18T12:20:57.240Z");')
    assert.strictEqual(db.test.insert({
      cell: '1',
      'd1': null
    }).get(), 'insert into `test` (`cell`,`d1`) values (\'1\', NULL);')
    assert.strictEqual(db.test.insert({
      cell: '1',
      'd1': undefined
    }).get(), 'insert into `test` (`cell`,`d1`) values (\'1\', NULL);')
    assert.strictEqual(db.test.insert({
      cell: '1',
      'd1': [1, 4]
    }).get(), 'insert into `test` (`cell`,`d1`) values (\'1\', \'[1,4]\');')
    assert.strictEqual(db.test.insert({
      cell: '1',
      'd1': {
        a: 1,
        b: '2'
      }
    }).get(), 'insert into `test` (`cell`,`d1`) values (\'1\', \'{"a":1,"b":"2"}\');')
    assert.strictEqual(db.test.insert({
      cell: '1',
      'd1': /kong+/g
    }).get(), 'insert into `test` (`cell`,`d1`) values (\'1\', \'{}\');')
  })
  it('4-1.insert唯一插入测试', async () => {
    assert.strictEqual(db.test.insert({
      cell: '1',
      'phone': 1
    }, 'phone').get(), 'insert into `test` (`cell`,`phone`) select \'1\',1 from dual WHERE NOT EXISTS(SELECT `phone` FROM `test` WHERE `phone` = 1) limit 1;')
    assert.strictEqual(db.test.insert({
      cell: '1',
      'phone': 1
    }, 'cell').get(), 'insert into `test` (`cell`,`phone`) select \'1\',1 from dual WHERE NOT EXISTS(SELECT `cell` FROM `test` WHERE `cell` = \'1\') limit 1;')
  })
  it('5.cmd测试', async () => {
    assert.strictEqual(db.test.cmd('show databases;').get(), 'show databases;')
    assert.strictEqual(db.test.cmd('show databases').get(), 'show databases;')
    assert.strictEqual(db.cmd('show databases').get(), 'show databases;')
  })
  it('6.特殊类型函数条件测试', async () => {
    assert.strictEqual(db.test.R({
      'ax(id)': 1
    }).get(), 'select * from `test` where `ax(id)`=1;')
    assert.strictEqual(db.test.R({
      'md5': 'md5(id)+max(id)'
    }).get(), 'select * from `test` where `md5`=md5(id)+max(id);')
    assert.strictEqual(db.test.R({
      'md5': '\'md5(id)\''
    }).get(), 'select * from `test` where `md5`=\'md5(id)\';')
    assert.strictEqual(db.test.R({
      'md5': null
    }).get(), 'select * from `test` where `md5` is NULL;')
    assert.strictEqual(db.test.R({
      'time': new Date('2016-01-01 12:12:13')
    }).get(), "select * from `test` where `time`='2016-01-01 12:12:13';")
    assert.strictEqual(db.test.R({
      'name': /%kong/g
    }).get(), "select * from `test` where `name` like '%kong';")
    assert.strictEqual(db.test.R({
      'name': /kong%/g
    }).get(), "select * from `test` where `name` like 'kong%';")
    assert.strictEqual(db.test.R({
      'name': /%kong%/g
    }).get(), "select * from `test` where `name` like '%kong%';")
    assert.strictEqual(db.test.R({
      'name': [1, 'x', 3]
    }).get(), "select * from `test` where `name` in (1,'x',3);", db.test.R({
      'name': [1, 'x', 3]
    }).get())
  })
  it('7.run测试', async () => {
    let rs = await db.cmd('select `id` from `test` limit 1;').run()
    let obj = await db.test.R({
      id: rs[0].id
    }, {}, {}, 1).run()
    assert.strictEqual(obj[0].id, rs[0].id)
    obj = await db.test.R({
      id: rs[0].id
    }, {}, {}, 1).run(true, true)
    assert.strictEqual(obj[1][0].id, rs[0].id)
    obj = await db.test.R({
      idx: 1001
    }, {}, {}, 1).run()
    assert.strictEqual(obj, -1)
    obj = await db.test.R({
      id: rs[0].id
    }, {}, {}, 1).run(true)
    assert.strictEqual(obj[1][0].id, rs[0].id)
    obj = await db.test.R({
      idx: 1001
    }, {}, {}, 1).run(true, true)
    assert.strictEqual(obj, -1)
  })
  it('8.exec测试', function * () {
    let rs = yield db.cmd('select `id` from `test` limit 1;').exec()
    let obj = yield db.test.R({
      id: rs[0].id
    }, {}, {}, 1).exec()
    assert.strictEqual(obj[0].id, rs[0].id)
    obj = yield db.test.R({
      id: rs[0].id
    }, {}, {}, 1).exec(true, true)
    assert.strictEqual(obj[1][0].id, rs[0].id)
    obj = yield db.test.R({
      idx: 1001
    }, {}, {}, 1).exec()
    assert.strictEqual(obj, -1)
    obj = yield db.test.R({
      id: rs[0].id
    }, {}, {}, 1).exec(true)
    assert.strictEqual(obj[1][0].id, rs[0].id)
    obj = yield db.test.R({
      idx: 1001
    }, {}, {}, 1).exec(true, true)
    assert.strictEqual(obj, -1)
    process.exit(0)
  })
})
<|endoftext|>


<commit_before>var fs = require('fs');
var chai = require('chai');
chai.use(require('chai-fuzzy'));
var should = chai.should();
var expect = chai.expect;
var Updater = require('../classes/updater.js');
var TestRepoHelper = require('./testRepoHelper.js');

describe('Updater', function() {
  var self = this;
  var testRepoPath;
  var testRepoHelper = new TestRepoHelper();

  before(function(done) {
    testRepoPath = testRepoHelper.setupAllTestRepos(function(testRepoPath) {
      self.testRepoPath = testRepoPath;
      done();
    });
  });

  after(function(done) {
    testRepoHelper.cleanup(function() {
      done();
    });
  })

  describe('updateData', function() {
    it('should return expected output', function(done) {

      var updater = new Updater(self.testRepoPath);

      updater.updateData(function(data) {
        data.repos.should.be.like(["grunt-init_git", "node-cron_git", "all"]);

        expect(data['grunt-init_git'].latestCommits).to.have.length.of(10);
        expect(data['grunt-init_git'].top10Committers).to.have.length.of(10);
        expect(data['grunt-init_git'].mostRecentTags).to.have.length.of(2);
        expect(data['grunt-init_git'].mostRecentBranches).to.have.length.of(2);

        expect(data['node-cron_git'].latestCommits).to.have.length.of(10);
        expect(data['node-cron_git'].top10Committers).to.have.length.of(10);
        expect(data['node-cron_git'].mostRecentTags).to.have.length.of(5);
        expect(data['node-cron_git'].mostRecentBranches).to.have.length.of(2);

        done();
      });
    });
  });

  describe('getAllRepos', function() {
    it('should return array of all repos', function() {
      var updater = new Updater(self.testRepoPath);

      var repos = updater.getAllRepos();

      expect(repos).to.have.length.of(2);
      expect(repos).to.contain('grunt-init_git');
      expect(repos).to.contain('node-cron_git');
    });
  });

  describe('calculateCombinedStatistics', function() {
    it('should return combined statistics for all repos', function(done) {
      var updater = new Updater(self.testRepoPath);
      updater.updateData(function(data) {
        expect(data.all.latestCommits).to.have.length.of(10);
        expect(data.all.top10Committers).to.have.length.of(10);
        expect(data.all.mostRecentTags).to.have.length.of(5);
        expect(data.all.mostRecentBranches).to.have.length.of(4);

        done();
      });
    });
  });
});<commit_msg>Added 'using strict'<commit_after>'use strict'
const
  fs = require('fs'),
  chai = require('chai'),
  should = chai.should(),
  expect = chai.expect,
  Updater = require('../classes/updater.js'),
  TestRepoHelper = require('./testRepoHelper.js');

chai.use(require('chai-fuzzy'));

describe('Updater', function() {
  var self = this;
  var testRepoPath;
  var testRepoHelper = new TestRepoHelper();

  before(function(done) {
    testRepoPath = testRepoHelper.setupAllTestRepos(function(testRepoPath) {
      self.testRepoPath = testRepoPath;
      done();
    });
  });

  after(function(done) {
    testRepoHelper.cleanup(function() {
      done();
    });
  })

  describe('updateData', function() {
    it('should return expected output', function(done) {

      var updater = new Updater(self.testRepoPath);

      updater.updateData(function(data) {
        data.repos.should.be.like(["grunt-init_git", "node-cron_git", "all"]);

        expect(data['grunt-init_git'].latestCommits).to.have.length.of(10);
        expect(data['grunt-init_git'].top10Committers).to.have.length.of(10);
        expect(data['grunt-init_git'].mostRecentTags).to.have.length.of(2);
        expect(data['grunt-init_git'].mostRecentBranches).to.have.length.of(2);

        expect(data['node-cron_git'].latestCommits).to.have.length.of(10);
        expect(data['node-cron_git'].top10Committers).to.have.length.of(10);
        expect(data['node-cron_git'].mostRecentTags).to.have.length.of(5);
        expect(data['node-cron_git'].mostRecentBranches).to.have.length.of(2);

        done();
      });
    });
  });

  describe('getAllRepos', function() {
    it('should return array of all repos', function() {
      var updater = new Updater(self.testRepoPath);

      var repos = updater.getAllRepos();

      expect(repos).to.have.length.of(2);
      expect(repos).to.contain('grunt-init_git');
      expect(repos).to.contain('node-cron_git');
    });
  });

  describe('calculateCombinedStatistics', function() {
    it('should return combined statistics for all repos', function(done) {
      var updater = new Updater(self.testRepoPath);
      updater.updateData(function(data) {
        expect(data.all.latestCommits).to.have.length.of(10);
        expect(data.all.top10Committers).to.have.length.of(10);
        expect(data.all.mostRecentTags).to.have.length.of(5);
        expect(data.all.mostRecentBranches).to.have.length.of(4);

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


<commit_before>/*
 * Test unit
 */
(function() {

    Ext.ns('TestUnit');

    TestUnit = {
        init: function()
        {
            Ext.create('Ext.panel.Panel', {
                id: 'test-panel',
                title: 'Testy',
                width: 800,
                layout: 'auto',
                scroll: true,
                renderTo: 'ext-app'
            });
        },

        group: function(name)
        {
            Ext.getCmp('test-panel').add(Ext.create('Ext.panel.Panel', {
                html: ''+name+':',
                border: 0,
                padding: 5,
                margin: 5,
                style: {
                    'border-bottom': '2px solid #eee'
                }
            }));
        },

        test: function(expression, value, description)
        {
            var
                html = "",
                cls,
                result;

            if (expression === value)
            {
                result = 'OK';
                cls = "ok";
            }
            else
            {
                result = 'Failed';
                cls = "failed";
            }

            html = Ext.String.format('Testig: {0}: {2}', description, cls, result);

            Ext.getCmp('test-panel').add(Ext.create('Ext.panel.Panel', {
                html: html,
                border: 0,
                padding: 5,
                margin: 5,
                style: {
                    'border-bottom': '1px solid #eee'
                }
            }));
        },

        isType: function(object, type, description)
        {
            var
                html = "",
                cls,
                result;

            if (typeof object === type)
            {
                result = 'OK';
                cls = "ok";
            }
            else
            {
                result = 'Failed';
                cls = "failed";
            }

            html = Ext.String.format('Testig Type: {0} should be {1}</e>, is: {2} {4}', description, type, typeof object, cls, result);

            Ext.getCmp('test-panel').add(Ext.create('Ext.panel.Panel', {
                html: html,
                border: 0,
                padding: 5,
                margin: 5,
                style: {
                    'border-bottom': '1px solid #eee'
                }
            }));
        }
    }

})();<commit_msg>UnitTest fixes<commit_after>/*
 * Test unit
 */
(function() {

    Ext.ns('TestUnit');

    var createNew = function(text) {
        Ext.getCmp('test-panel').add(Ext.create('Ext.panel.Panel', {
            html: text,
            border: 0,
            padding: 5,
            margin: 5,
            style: {
                'border-bottom': '1px solid #eee'
            }
        }));
    };

    TestUnit = {
        init: function()
        {
            Ext.create('Ext.panel.Panel', {
                id: 'test-panel',
                title: 'Testy',
                width: 800,
                layout: 'auto',
                scroll: true,
                renderTo: 'ext-app'
            });
        },

        group: function(name)
        {
            Ext.getCmp('test-panel').add(Ext.create('Ext.panel.Panel', {
                html: ''+name+':',
                border: 0,
                padding: 5,
                margin: 5,
                style: {
                    'border-bottom': '2px solid #eee'
                }
            }));
        },

        test: function(expression, value, description)
        {
            var
                html = "",
                cls,
                result;

            if (expression === value)
            {
                result = 'OK';
                cls = "ok";
            }
            else
            {
                result = 'Failed';
                cls = "failed";
            }

            html = Ext.String.format('Testig: {0}: {2}', description, cls, result);

            createNew(html);
        },

        isType: function(object, type, description)
        {
            var
                html = "",
                cls,
                result;

            if (typeof object === type)
            {
                result = 'OK';
                cls = "ok";
            }
            else
            {
                result = 'Failed';
                cls = "failed";
            }

            html = Ext.String.format('Testig Type: {0} should be {1}</e>, is: {2} {4}', description, type, typeof object, cls, result);

            createNew(html);
        }
    }

})();<|endoftext|>


<commit_before>document.addEventListener('DOMContentLoaded', function() {
M.AutoInit();
});

  function createCard(cardType) {
	var newDiv = document.createElement("DIV");
	newDiv.className = "col s12 m6 l3 xl3 cardToDelete";
	newDiv.innerHTML = `

			  <img src="images/`+cardType+`.jpg">
			  `+cardType+`
			  delete

`+cardType+`

				remove
				add

	`;
	cardArea = document.getElementById("cardArea");
    cardArea.appendChild(newDiv);
	$('.closeBtn').on('click', function(){
    $(this).closest(".cardToDelete").remove();
});
 }

// delete a card
$('.closeBtn').on('click', function(){
    $(this).closest(".cardToDelete").remove();
});

//$('.deletePerson').click(function(){ console.log('Delete me'); return false; });

function displayScreen(screenID) {
	$('.TGEscreen').hide();
	$('#'+screenID+'').show();
}
function getRandomPeopleAttributes() {
	return {
		firstNamesMale: ['Jean-Michel','Jean-Pierre','Jean-Philippe','Jean-Paul','Jean-Marcel','Kevin','Killian','Mohammed','Ashton','Brad','Harrison','Bonaventure','Desire','Yunic','Dartagnan'],
		firstNamesFemale: ['Fatima','Barbara','Monica','Priscilia','Stephanie','Kelly','Nicole','Morgan','Jessica','Cindy','Kloe','Kim','Britney','Shakira','Beberly','Merica','Appaloosa','Melanomia','Heaven Lee'],
		lastNames: ['Bjornsonn','Al Belgiki','Dupont','Dugenou','Smith','Gaywad','Trump','Buttz','Ballz','Goodfornothing','Retard','Primitive','Kumar','Singh','Buzzbuzz','Nutgrabber','Ballbuster','Bieber','Van Damme','Van Varenberg','Daerdenne','Bin Batman','Neanderthal','Cromagnon','Uga-uga'],
	}
}

function getInitialState() {
	return {
		people: [
			{name: "denis", gender: "Male",age: "32", photo: "images/denis.jpg", diplomaList : [{diplomaTypeID: 0, diplomaLevel:2},{diplomaTypeID: 1, diplomaLevel:1},{diplomaTypeID: 2, diplomaLevel:0},{diplomaTypeID: 3, diplomaLevel:2},{diplomaTypeID: 4, diplomaLevel:0}]},
			{name: "asal", gender: "Female",age: "28", photo: "images/asal.jpg", diplomaList : [{diplomaTypeID: 0, diplomaLevel:2}]}
		]
	}
}

 function getConfig() {
	var colorList = ['#b87333','#C0C0C0','#FFDF00'];
	return {
		diplomaTypeList: [
			{name: 'General', icon: 'fas fa-graduation-cap', color: colorList},
			{name: 'Engineer', icon: 'fas fa-wrench', color: colorList},
			{name: 'Doctor', icon: 'fas fa-briefcase-medical', color: colorList},
			{name: 'Food', icon: 'fas fa-utensils', color: colorList},
			{name: 'Warrior', icon: 'fas fa-shield-alt', color: colorList},
		]
	}
}

function makeUL(peopleArray) {
    // Create the list element:
    var list = document.createElement('ul');
	list.className = "collection";

	// for each person
    for (var i = 0; i < peopleArray.length; i++) {
        // Create the list item:
        var item = document.createElement('li');
		item.className = 'collection-item avatar'

		// create and append the thumbnail
		var thumb = document.createElement('IMG');
		thumb.src = peopleArray[i].photo;
		thumb.className = "circle"
		item.appendChild(thumb);

		// Create the title
		var title = document.createElement('span');
		title.className = 'title';
		title.appendChild(document.createTextNode(peopleArray[i].name + ' '));
		// gender logo
		var genderLogo = document.createElement('i');
		if (peopleArray[i].gender == 'Male') {genderLogo.className = "fas fa-mars"} else {genderLogo.className = "fas fa-venus"}
		title.appendChild(genderLogo);
		item.appendChild(title);

		// create and append the second line content
		var secondLineContent = document.createElement('p');
		// sort the list of detained diplomaList alphabetically, so the icons align
		peopleArray[i].diplomaList.sort(function(a, b){return a - b});
			// badges education
			// for all entries in diploma
			for (var j = 0; j < peopleArray[i].diplomaList.length; j++) {
				diplomaType = config.diplomaTypeList[peopleArray[i].diplomaList[j].diplomaTypeID]
				console.log('Iteration '+j+' of loop over diplomaList of '+peopleArray[i].name+' found '+diplomaType.name+' level'+peopleArray[i].diplomaList[j].diplomaLevel+' corresponding to color '+diplomaType.color[peopleArray[i].diplomaList[j].diplomaLevel]);
				var diplomaLogo = document.createElement('i');
				diplomaLogo.className = diplomaType.icon;
				diplomaLogo.style.color = diplomaType.color[peopleArray[i].diplomaList[j].diplomaLevel];
				secondLineContent.appendChild(diplomaLogo);
				// insert a space after each logo
				secondLineContent.appendChild(document.createTextNode(" "))
			}
		item.appendChild(secondLineContent);

		// append the text content
        //item.appendChild(document.createTextNode(peopleArray[i].name));

		// append the delete icon
		var linkDelete = document.createElement('a');
		linkDelete.className = 'secondary-content deletePerson';
		linkDelete.href = '#!'
		//linkDelete.onclick = "test"
		linkDelete.addEventListener("click", test, false);
		var deleteIcon = document.createElement('i');
		deleteIcon.className = 'material-icons';
		deleteIcon.appendChild(document.createTextNode('delete'))
		linkDelete.appendChild(deleteIcon);
		item.appendChild(linkDelete);

        // Add it to the list:
        list.appendChild(item);
    }

    // Finally, return the constructed list:
    return list;
}

// Add the contents of options[0] to #jobsScreen:
function generatePeopleDOM(divID) {
	document.getElementById(divID).appendChild(makeUL(state.people));
}

function clearPeopleDOM(divID) {
	var myNode = document.getElementById(divID);
	while (myNode.firstChild) {
		myNode.removeChild(myNode.firstChild);
	}
}

function addPerson_BE() {
	var newPerson = {name: "harry", gender: "Male",age: "15"};
	state.people.push(newPerson);
}

function addRandomPerson_BE() {
	// get the list of random names
	var randomPeopleAttributes = getRandomPeopleAttributes();
	// pick a random last name
	var randomIndex = Math.round(Math.random()*(randomPeopleAttributes.lastNames.length-1))
	var lastName = randomPeopleAttributes.lastNames[randomIndex]
	// decide whether the person is male or female
	if (Math.random() > 0.5) {
		var gender = 'Male'
		// pick a random picture in the images
		randomIndex = Math.round(Math.random()*65)+1
		var imgName='images/People/Males/image-'+randomIndex+'.jpg'
		// pick a random first name
		randomIndex = Math.round(Math.random()*(randomPeopleAttributes.firstNamesMale.length-1));
		var firstName = randomPeopleAttributes.firstNamesMale[randomIndex];
	} else {
		var gender = 'Female'
		// pick a random picture in the images
		randomIndex = Math.round(Math.random()*65)+1
		var imgName='images/People/Females/image-'+randomIndex+'.jpg'
		// pick a random first name
		randomIndex = Math.round(Math.random()*(randomPeopleAttributes.firstNamesFemale.length-1));
		var firstName = randomPeopleAttributes.firstNamesFemale[randomIndex];
	}

	var newPerson = {name: firstName + ' ' +lastName, gender: gender,age: "15", photo: imgName, diplomaList : [{diplomaTypeID: 0, diplomaLevel:0}]};
	state.people.push(newPerson);
}

function addAndRefresh(divID) {
	addRandomPerson_BE();
	refreshPeopleList_FE();
}

function refreshPeopleList_FE() {
	divID = 'peopleListArea';
	clearPeopleDOM(divID);
	generatePeopleDOM(divID);
}

function test() {
	alert('Yeah you clicked');
}

// initialization
var state = getInitialState();
var config = getConfig();
generatePeopleDOM('peopleListArea');<commit_msg>Bit of cleanup<commit_after>document.addEventListener('DOMContentLoaded', function() {
M.AutoInit();
});

  function createCard(cardType) {
	var newDiv = document.createElement("DIV");
	newDiv.className = "col s12 m6 l3 xl3 cardToDelete";
	newDiv.innerHTML = `

			  <img src="images/`+cardType+`.jpg">
			  `+cardType+`
			  delete

`+cardType+`

				remove
				add

	`;
	cardArea = document.getElementById("cardArea");
    cardArea.appendChild(newDiv);
	$('.closeBtn').on('click', function(){
    $(this).closest(".cardToDelete").remove();
});
 }

// delete a card
$('.closeBtn').on('click', function(){
    $(this).closest(".cardToDelete").remove();
});

//$('.deletePerson').click(function(){ console.log('Delete me'); return false; });

function displayScreen(screenID) {
	$('.TGEscreen').hide();
	$('#'+screenID+'').show();
}
function getRandomPeopleAttributes() {
	return {
		firstNamesMale: ['Jean-Michel','Jean-Pierre','Jean-Philippe','Jean-Paul','Jean-Marcel','Kevin','Killian','Mohammed','Ashton','Brad','Harrison','Bonaventure','Desire','Yunic','Dartagnan'],
		firstNamesFemale: ['Fatima','Barbara','Monica','Priscilia','Stephanie','Kelly','Nicole','Morgan','Jessica','Cindy','Kloe','Kim','Britney','Shakira','Beberly','Merica','Appaloosa','Melanomia','Heaven Lee'],
		lastNames: ['Bjornsonn','Al Belgiki','Dupont','Dugenou','Smith','Gaywad','Trump','Buttz','Ballz','Goodfornothing','Retard','Primitive','Kumar','Singh','Buzzbuzz','Nutgrabber','Ballbuster','Bieber','Van Damme','Van Varenberg','Daerdenne','Bin Batman','Neanderthal','Cromagnon','Uga-uga'],
	}
}

function getInitialState() {
	return {
		people: [
			{name: "denis", gender: "Male",age: "32", photo: "images/denis.jpg", diplomaList : [{diplomaTypeID: 0, diplomaLevel:2},{diplomaTypeID: 1, diplomaLevel:1},{diplomaTypeID: 2, diplomaLevel:0},{diplomaTypeID: 3, diplomaLevel:2},{diplomaTypeID: 4, diplomaLevel:0}]},
			{name: "asal", gender: "Female",age: "28", photo: "images/asal.jpg", diplomaList : [{diplomaTypeID: 0, diplomaLevel:2}]}
		]
	}
}

 function getConfig() {
	var colorList = ['#b87333','#C0C0C0','#FFDF00'];
	return {
		diplomaTypeList: [
			{name: 'General', icon: 'fas fa-graduation-cap', color: colorList},
			{name: 'Engineer', icon: 'fas fa-wrench', color: colorList},
			{name: 'Doctor', icon: 'fas fa-briefcase-medical', color: colorList},
			{name: 'Food', icon: 'fas fa-utensils', color: colorList},
			{name: 'Warrior', icon: 'fas fa-shield-alt', color: colorList},
		]
	}
}

function makeUL(peopleArray) {
    // Create the list element:
    var list = document.createElement('ul');
	list.className = "collection";

	// for each person
    for (var i = 0; i < peopleArray.length; i++) {
        var person = peopleArray[i];
		// Create the list item:
        var item = document.createElement('li');
		item.className = 'collection-item avatar'

		// create and append the thumbnail
		var thumb = document.createElement('IMG');
		thumb.src = person.photo;
		thumb.className = "circle"
		item.appendChild(thumb);

		// Create the title with person's name
		var title = document.createElement('span');
		title.className = 'title';
		title.appendChild(document.createTextNode(person.name + ' '));

		// gender logo
		var genderLogo = document.createElement('i');
		if (person.gender == 'Male') {genderLogo.className = "fas fa-mars"} else {genderLogo.className = "fas fa-venus"}
		title.appendChild(genderLogo);
		item.appendChild(title);

		// create and append the second line content
		var secondLineContent = document.createElement('p');
			// sort the list of detained diplomaList alphabetically, so the icons align
			//person.diplomaList.sort(function(a, b){return a - b});
			// badges education
			// for all entries in diploma
			for (var j = 0; j < person.diplomaList.length; j++) {
				diplomaType = config.diplomaTypeList[person.diplomaList[j].diplomaTypeID]
				//console.log('Iteration '+j+' of loop over diplomaList of '+person.name+' found '+diplomaType.name+' level'+person.diplomaList[j].diplomaLevel+' corresponding to color '+diplomaType.color[person.diplomaList[j].diplomaLevel]);
				var diplomaLogo = document.createElement('i');
				diplomaLogo.className = diplomaType.icon;
				diplomaLogo.style.color = diplomaType.color[person.diplomaList[j].diplomaLevel];
				secondLineContent.appendChild(diplomaLogo);
				// insert a space after each logo
				secondLineContent.appendChild(document.createTextNode(" "))
			}
		item.appendChild(secondLineContent);

		// append the text content
        //item.appendChild(document.createTextNode(person.name));

		// append the delete icon
		var linkDelete = document.createElement('a');
		linkDelete.className = 'secondary-content deletePerson';
		linkDelete.href = '#!'
		//linkDelete.onclick = "test"
		linkDelete.addEventListener("click", test, false);
		var deleteIcon = document.createElement('i');
		deleteIcon.className = 'material-icons';
		deleteIcon.appendChild(document.createTextNode('delete'))
		linkDelete.appendChild(deleteIcon);
		item.appendChild(linkDelete);

        // Add it to the list:
        list.appendChild(item);
    }

    // Finally, return the constructed list:
    return list;
}

// Add the contents of options[0] to #jobsScreen:
function generatePeopleDOM(divID) {
	document.getElementById(divID).appendChild(makeUL(state.people));
}

function clearPeopleDOM(divID) {
	var myNode = document.getElementById(divID);
	while (myNode.firstChild) {
		myNode.removeChild(myNode.firstChild);
	}
}

function addPerson_BE() {
	var newPerson = {name: "harry", gender: "Male",age: "15"};
	state.people.push(newPerson);
}

function addRandomPerson_BE() {
	// get the list of random names
	var randomPeopleAttributes = getRandomPeopleAttributes();
	// pick a random last name
	var randomIndex = Math.round(Math.random()*(randomPeopleAttributes.lastNames.length-1))
	var lastName = randomPeopleAttributes.lastNames[randomIndex]
	// decide whether the person is male or female
	if (Math.random() > 0.5) {
		var gender = 'Male'
		// pick a random picture in the images
		randomIndex = Math.round(Math.random()*65)+1
		var imgName='images/People/Males/image-'+randomIndex+'.jpg'
		// pick a random first name
		randomIndex = Math.round(Math.random()*(randomPeopleAttributes.firstNamesMale.length-1));
		var firstName = randomPeopleAttributes.firstNamesMale[randomIndex];
	} else {
		var gender = 'Female'
		// pick a random picture in the images
		randomIndex = Math.round(Math.random()*65)+1
		var imgName='images/People/Females/image-'+randomIndex+'.jpg'
		// pick a random first name
		randomIndex = Math.round(Math.random()*(randomPeopleAttributes.firstNamesFemale.length-1));
		var firstName = randomPeopleAttributes.firstNamesFemale[randomIndex];
	}

	var newPerson = {name: firstName + ' ' +lastName, gender: gender,age: "15", photo: imgName, diplomaList : [{diplomaTypeID: 0, diplomaLevel:0}]};
	state.people.push(newPerson);
}

function addAndRefresh(divID) {
	addRandomPerson_BE();
	refreshPeopleList_FE();
}

function refreshPeopleList_FE() {
	divID = 'peopleListArea';
	clearPeopleDOM(divID);
	generatePeopleDOM(divID);
}

function test() {
	alert('Yeah you clicked');
}

// initialization
var state = getInitialState();
var config = getConfig();
generatePeopleDOM('peopleListArea');<|endoftext|>


<commit_before>var shuffle = require('shuffle-array');
var models = require('../models/index');
var ZiviService = require('./../services/zivi.service.js');
var SocketService = require('./../services/socket.service');

var ZiviTimer = {};
const TIMER_SOCKET_NAME = 'timer';
ZiviTimer.ZIVI_TIMER_INTERVAL = 600;
ZiviTimer.remainingSeconds = ZiviTimer.ZIVI_TIMER_INTERVAL;

ZiviTimer.pushTimerData = function () {
  SocketService.writeToSocket(TIMER_SOCKET_NAME, {
    remaining: ZiviTimer.remainingSeconds
  });
};

ZiviTimer.shuffleZivisAndSaveOrder = function () {
  ZiviService.findAll(function (zivis) {
    var ziviCount = zivis.length;
    var selectedZivis = [];
    for (var i = 0; i <= ziviCount; i++) {
      var zivi = selectZiviFairly(createFairArray(getMaxFirstZiviCount(zivis), zivis));
      selectedZivis.push(zivi);
      zivis = zivis.filter(function (element) {
        return element._id !== zivi._id;
      });
    }
    if (selectedZivis.length > 0) {
      selectedZivis[0].first += 1;
      for (var j = 0; j < selectedZivis.length; j++) {
        if (selectedZivis[j] === undefined) { // idk
          continue;
        }
        selectedZivis[j].order = j + 1;
        selectedZivis[j].save();
      }
    }
  });
};

function getMaxFirstZiviCount(zivis) {
  var max = -1;
  zivis.forEach(function (zivi) {
    if (zivi.first > max) {
      max = zivi.first;
    }
  });
  return max;
}

function createFairArray(max, zivis) {
  var fairArray = [];
  zivis.forEach(function (zivi) {
    for (var i = 0; i < max - zivi.first + 1; i++) {
      fairArray.push(zivi);
    }
  });
  return fairArray;
}

function selectZiviFairly(fairArray) {
  shuffle(fairArray);
  return fairArray[0];
}

function tickTimer() {
  ZiviTimer.remainingSeconds--;
  if (ZiviTimer.remainingSeconds === 0) {
    ZiviTimer.remainingSeconds = ZiviTimer.ZIVI_TIMER_INTERVAL;
    ZiviTimer.shuffleZivisAndSaveOrder();
  }
  ZiviTimer.pushTimerData();
}

ZiviTimer.shuffleZivisAndSaveOrder();
setInterval(tickTimer, 1000);

module.exports = ZiviTimer;
<commit_msg>Fix Zivi timer never reaching zero; Fixes realzimon/ng-zimon#12<commit_after>var shuffle = require('shuffle-array');
var models = require('../models/index');
var ZiviService = require('./../services/zivi.service.js');
var SocketService = require('./../services/socket.service');

var ZiviTimer = {};
const TIMER_SOCKET_NAME = 'timer';
ZiviTimer.ZIVI_TIMER_INTERVAL = 600;
ZiviTimer.remainingSeconds = ZiviTimer.ZIVI_TIMER_INTERVAL;

ZiviTimer.pushTimerData = function () {
  SocketService.writeToSocket(TIMER_SOCKET_NAME, {
    remaining: ZiviTimer.remainingSeconds
  });
};

ZiviTimer.shuffleZivisAndSaveOrder = function () {
  ZiviService.findAll(function (zivis) {
    var ziviCount = zivis.length;
    var selectedZivis = [];
    for (var i = 0; i <= ziviCount; i++) {
      var zivi = selectZiviFairly(createFairArray(getMaxFirstZiviCount(zivis), zivis));
      selectedZivis.push(zivi);
      zivis = zivis.filter(function (element) {
        return element._id !== zivi._id;
      });
    }
    if (selectedZivis.length > 0) {
      selectedZivis[0].first += 1;
      for (var j = 0; j < selectedZivis.length; j++) {
        if (selectedZivis[j] === undefined) { // idk
          continue;
        }
        selectedZivis[j].order = j + 1;
        selectedZivis[j].save();
      }
    }
  });
};

function getMaxFirstZiviCount(zivis) {
  var max = -1;
  zivis.forEach(function (zivi) {
    if (zivi.first > max) {
      max = zivi.first;
    }
  });
  return max;
}

function createFairArray(max, zivis) {
  var fairArray = [];
  zivis.forEach(function (zivi) {
    for (var i = 0; i < max - zivi.first + 1; i++) {
      fairArray.push(zivi);
    }
  });
  return fairArray;
}

function selectZiviFairly(fairArray) {
  shuffle(fairArray);
  return fairArray[0];
}

function tickTimer() {
  ZiviTimer.remainingSeconds--;
  ZiviTimer.pushTimerData();
  if (ZiviTimer.remainingSeconds === 0) {
    ZiviTimer.remainingSeconds = ZiviTimer.ZIVI_TIMER_INTERVAL;
    ZiviTimer.shuffleZivisAndSaveOrder();
  }
}

ZiviTimer.shuffleZivisAndSaveOrder();
setInterval(tickTimer, 1000);

module.exports = ZiviTimer;
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2012 John Judnich
 * Released as open-source under The MIT Licence.
 *
 * This module provides a parser which loads an entire TML file into memory as nested lists of strings.
 * This also provides functions to convert nested lists-of-strings objects back into TML code, pattern
 * matching functions, and searching functions (to easily locate subtrees that match a given pattern).
 */

var TML = (function () {
    "use strict";
    var me = {};

    var collapsed_OpenBracket = "\\o",
        collapsed_CloseBracket = "\\c",
        collapsed_Divider = "\\d";

    var convertIntermediateEscapeCodes = function (str) {
        var result = str.replace(/\\./g, function (code) {
            if (code === "\\[") return collapsed_OpenBracket;
            if (code === "\\]") return collapsed_CloseBracket;
            if (code === "\\|") return collapsed_Divider;
            return code;
        });
        return result;
    };

    var convertFinalEscapeCodes = function (str) {
        var result = str.replace(/\\./g, function (code) {
            if (code === collapsed_Divider) return "|";
            if (code === collapsed_OpenBracket) return "[";
            if (code === collapsed_Divider) return "]";
            if (code === "\\s") return " ";
            if (code === "\\t") return "\t";
            if (code === "\\n") return "\n";
            if (code === "\\r") return "\r";
            if (code === "\\\\") return "\\";
            return code;
        });
        return result;
    };

    // Parses list "... ]" where the open bracket has already been read.
    // If endAtBar is true, this will let "|" terminate the list.
    var parseList = function (tokens, index, endAtBar) {
        var tokLen = tokens.length;
        var list = [];
        var i = index;

        while (i < tokLen) {
            var tok = tokens[i++];

            if (tok === "[") {
                // append sublist
                var ret = parseList(tokens, i);
                i = ret.index;
                list.push(ret.result);
            }
            else if (tok === "|") {
                if (endAtBar)
                    return {index: i, result: list};

                // nest-ify
                list = [list];
                while (i < tokLen) {
                    var ret = parseList(tokens, i, true);
                    i = ret.index;

                    list.push(ret.result);

                    if (tokens[i - 1] === "]")
                        return {index: i, result: list};
                }
                break; // expected closing bracket, reached EOF
            }
            else if (tok === "]") {
                // close this list
                return {index: i, result: list};
            }
            else {
                // append word
                if (tok !== "")
                    list.push(convertFinalEscapeCodes(tok));
            }
        }

        throw "TML: Expected close bracket";
    };

    var parseRoot = function (tokens) {
        var tokLen = tokens.length;
        if (tokLen === 0 || tokens[0] !== "[")
            throw "TML: Expected open bracket";

        var ret = parseList(tokens, 1, false);
        var tree = ret.result;

        if (ret.index < tokLen)
            throw "TML: Expected end of file after root node";

        return tree;
    };

    var treeToStringGen = function (tmlTree, brackets) {
        if (typeof tmlTree === "string") return tmlTree;

        var len = tmlTree.length, str = "";
        if (brackets) str = "[";

        for (var i = 0; i < len; ++i) {
            var v = tmlTree[i];

            if (typeof(v) === "string")
                str += v;
            else
                str += treeToStringGen(v, brackets);

            if (i < len-1) str += " ";
        }

        if (brackets) str += "]";
        return str;
    };

    // Parses the given TML string and returns the result a a "tree" (nested Javascript lists and strings).
    me.parse = function (tmlString) {
        var rawString = convertIntermediateEscapeCodes(tmlString);
        var tokens = rawString.match(/((\w|\\.)+|\[|\]|\|)/g);
        return parseRoot(tokens);
    };

    // Converts a given Javascript nested lists/strings "tree" object into valid TML code
    me.toMarkupString = function (tmlTree) {
        return treeToStringGen(tmlTree, true);
    };

    // Converts a given Javascript nested lists/strings "tree" object into a string with each item separated by a space
    me.toString = function (tmlTree) {
        return treeToStringGen(tmlTree, false);
    };

    // Compares a candidate TML tree against a given pattern. If the pattern contains no wildcards, this
    // simply compares the two trees and returns true if identical. Alternately, the pattern may contain
    // the "\?" wildcard to match any node (any list or string), or the "\*" wildcard to match any zero
    // or more nodes up to the end of the list.
    me.compare = function (candidate, pattern) {
        if (pattern === "\\?")
            return true;
        if (typeof candidate === "string")
            return (candidate === pattern);
        if (typeof pattern === "string")
            return false;

        var cLen = candidate.length, pLen = pattern.length, c;
        for (c = 0; c < cLen; ++c) {
            if (c >= pLen)
                return false;
            if (pattern[c] === "\\*")
                return true;
            if (!me.compare(candidate[c], pattern[c]))
                return false;
        }

        if (c < pLen) {
            if (pattern[c] === "\\*")
                return true;
            else
                return false;
        }

        return true;
    };

    // Returns the first child under node which matches the given pattern (as determined by TML.compare).
    // Returns null if no match is found.
    me.find = function (node, pattern) {
        var len = node.length;
        for (var i = 0; i < len; ++i) {
            if (me.compare(node[i], pattern))
                return node[i];
        }
        return null;
    };

    // Returns a list of all children under node which match the given pattern (as determined by TML.compare).
    // Returns [] if no match is found.
    me.findAll = function (node, pattern) {
        var results = [];
        var len = node.length;
        for (var i = 0; i < len; ++i) {
            if (me.compare(node[i], pattern))
                results.push(node[i]);
        }
        return results;
    };

    return me;
}());

<commit_msg>Updated js documentation<commit_after>/*
 * Copyright (C) 2012 John Judnich
 * Released as open-source under The MIT Licence.
 *
 * This module provides a parser which loads an entire TML file into memory as nested lists of strings.
 * This also provides functions to convert nested lists-of-strings objects back into TML code, pattern
 * matching functions, and searching functions (to easily locate subtrees that match a given pattern).
 */

var TML = (function () {
    "use strict";
    var me = {};

    var collapsed_OpenBracket = "\\o",
        collapsed_CloseBracket = "\\c",
        collapsed_Divider = "\\d";

    var convertIntermediateEscapeCodes = function (str) {
        var result = str.replace(/\\./g, function (code) {
            if (code === "\\[") return collapsed_OpenBracket;
            if (code === "\\]") return collapsed_CloseBracket;
            if (code === "\\|") return collapsed_Divider;
            return code;
        });
        return result;
    };

    var convertFinalEscapeCodes = function (str) {
        var result = str.replace(/\\./g, function (code) {
            if (code === collapsed_Divider) return "|";
            if (code === collapsed_OpenBracket) return "[";
            if (code === collapsed_Divider) return "]";
            if (code === "\\s") return " ";
            if (code === "\\t") return "\t";
            if (code === "\\n") return "\n";
            if (code === "\\r") return "\r";
            if (code === "\\\\") return "\\";
            return code;
        });
        return result;
    };

    // Parses list "... ]" where the open bracket has already been read.
    // If endAtBar is true, this will let "|" terminate the list.
    var parseList = function (tokens, index, endAtBar) {
        var tokLen = tokens.length;
        var list = [];
        var i = index;

        while (i < tokLen) {
            var tok = tokens[i++];

            if (tok === "[") {
                // append sublist
                var ret = parseList(tokens, i);
                i = ret.index;
                list.push(ret.result);
            }
            else if (tok === "|") {
                if (endAtBar)
                    return {index: i, result: list};

                // nest-ify
                list = [list];
                while (i < tokLen) {
                    var ret = parseList(tokens, i, true);
                    i = ret.index;

                    list.push(ret.result);

                    if (tokens[i - 1] === "]")
                        return {index: i, result: list};
                }
                break; // expected closing bracket, reached EOF
            }
            else if (tok === "]") {
                // close this list
                return {index: i, result: list};
            }
            else {
                // append word
                if (tok !== "")
                    list.push(convertFinalEscapeCodes(tok));
            }
        }

        throw "TML: Expected close bracket";
    };

    var parseRoot = function (tokens) {
        var tokLen = tokens.length;
        if (tokLen === 0 || tokens[0] !== "[")
            throw "TML: Expected open bracket";

        var ret = parseList(tokens, 1, false);
        var tree = ret.result;

        if (ret.index < tokLen)
            throw "TML: Expected end of file after root node";

        return tree;
    };

    var treeToStringGen = function (tmlTree, brackets) {
        if (typeof tmlTree === "string") return tmlTree;

        var len = tmlTree.length, str = "";
        if (brackets) str = "[";

        for (var i = 0; i < len; ++i) {
            var v = tmlTree[i];

            if (typeof(v) === "string")
                str += v;
            else
                str += treeToStringGen(v, brackets);

            if (i < len-1) str += " ";
        }

        if (brackets) str += "]";
        return str;
    };

    // Parses the given TML string and returns the result a a "tree" (nested Javascript lists and strings).
    me.parse = function (tmlString) {
        var rawString = convertIntermediateEscapeCodes(tmlString);
        var tokens = rawString.match(/((\w|\\.)+|\[|\]|\|)/g);
        return parseRoot(tokens);
    };

    // Converts a given Javascript nested lists/strings "tree" object into valid TML code
    me.toMarkupString = function (tmlTree) {
        return treeToStringGen(tmlTree, true);
    };

    // Converts a given Javascript nested lists/strings "tree" object into a string with each item separated by a space
    me.toString = function (tmlTree) {
        return treeToStringGen(tmlTree, false);
    };

    // Compares a candidate TML tree against a given pattern. If the pattern contains no wildcards, this
    // simply compares the two trees and returns true if identical. Alternately, the pattern may contain
    // the "\?" wildcard to match any node (any list or string), or the "\*" wildcard to match any zero
    // or more nodes up to the end of the list. NOTE: Both "candidate" and "pattern" are expected to be
    // parsed data trees, i.e. results from TML.parse (or your own nested lists/strings if you want).
    me.compare = function (candidate, pattern) {
        if (pattern === "\\?")
            return true;
        if (typeof candidate === "string")
            return (candidate === pattern);
        if (typeof pattern === "string")
            return false;

        var cLen = candidate.length, pLen = pattern.length, c;
        for (c = 0; c < cLen; ++c) {
            if (c >= pLen)
                return false;
            if (pattern[c] === "\\*")
                return true;
            if (!me.compare(candidate[c], pattern[c]))
                return false;
        }

        if (c < pLen) {
            if (pattern[c] === "\\*")
                return true;
            else
                return false;
        }

        return true;
    };

    // Returns the first child under node which matches the given pattern (as determined by TML.compare).
    // Returns null if no match is found. NOTE: Both "node" and "pattern" are expected to be
    // parsed data trees, i.e. results from TML.parse (or your own nested lists/strings if you want).
    me.find = function (node, pattern) {
        var len = node.length;
        for (var i = 0; i < len; ++i) {
            if (me.compare(node[i], pattern))
                return node[i];
        }
        return null;
    };

    // Returns a list of all children under node which match the given pattern (as determined by TML.compare).
    // Returns [] if no match is found. NOTE: Both "node" and "pattern" are expected to be
    // parsed data trees, i.e. results from TML.parse (or your own nested lists/strings if you want).
    me.findAll = function (node, pattern) {
        var results = [];
        var len = node.length;
        for (var i = 0; i < len; ++i) {
            if (me.compare(node[i], pattern))
                results.push(node[i]);
        }
        return results;
    };

    return me;
}());

<|endoftext|>


<commit_before>/*!
 * Copyright (c) 2015-2017 Cisco Systems, Inc. See LICENSE file.
 */

const debug = require(`debug`)(`tooling:build`);
const {
  exec,
  mkdirp,
  rimraf,
  transformFile
} = require(`../lib/async`);
const g = require(`../lib/async`).glob;
const path = require(`path`);
const {rename, writeFile} = require(`fs-promise`);
const {glob} = require(`../util/package`);
const S = require(`string`);

exports.buildFile = async function buildFile({src, dest}) {
  debug(`transforming ${src}`);
  const {code, map} = await transformFile(src);
  debug(`transformFileed ${src}`);
  await mkdirp(path.dirname(dest));
  debug(`writing ${dest}`);
  await writeFile(dest, code);
  await writeFile(`${dest}.map`, JSON.stringify(map));
  debug(`wrote ${dest}`);
};

exports.buildPackage = async function buildPackage(packageName) {
  debug(`building package ${packageName}`);
  const files = await glob(`src/**/*.js`, {packageName});
  debug(`building files `, files);
  const mapped = files
  .map((filename) => path.join(`packages`, `node_modules`, packageName, filename))
  .map((filename) => ({
    src: filename,
    dest: filename.replace(`src`, `dist`)
  }));

  for (const file of mapped) {
    await exports.buildFile(file);
  }
};

exports.buildSamples = async function buildSamples() {
  await rimraf(`packages/node_modules/samples/bundle*`);
  await exec(`webpack`);
  await rename(`bundle.js`, `packages/node_modules/samples/bundle.js`);
  await rename(`bundle.js.map`, `packages/node_modules/samples/bundle.js.map`);

  const samples = await g(`browser-*`, {cwd: path.resolve(process.cwd(), `packages/node_modules/samples`)});

  const out = `<!DOCTYPE html>

  <title>Samples</title>

Hosted Samples

${samples.filter((s) => !s.includes(`auth`)).map((s) => `<li><a href="${s}">${S(s).humanize().capitalize().s}</a><li>`)}

  There's a working authorization sample in the git repository, though we don't have it hosted just yet (but it's coming soon).

`;

  await writeFile(`packages/node_modules/samples/index.html`, out);
};
<commit_msg>fix(tooling): filter blanks from samples list<commit_after>/*!
 * Copyright (c) 2015-2017 Cisco Systems, Inc. See LICENSE file.
 */

const debug = require(`debug`)(`tooling:build`);
const {
  exec,
  mkdirp,
  rimraf,
  transformFile
} = require(`../lib/async`);
const g = require(`../lib/async`).glob;
const path = require(`path`);
const {rename, writeFile} = require(`fs-promise`);
const {glob} = require(`../util/package`);
const S = require(`string`);

exports.buildFile = async function buildFile({src, dest}) {
  debug(`transforming ${src}`);
  const {code, map} = await transformFile(src);
  debug(`transformFileed ${src}`);
  await mkdirp(path.dirname(dest));
  debug(`writing ${dest}`);
  await writeFile(dest, code);
  await writeFile(`${dest}.map`, JSON.stringify(map));
  debug(`wrote ${dest}`);
};

exports.buildPackage = async function buildPackage(packageName) {
  debug(`building package ${packageName}`);
  const files = await glob(`src/**/*.js`, {packageName});
  debug(`building files `, files);
  const mapped = files
  .map((filename) => path.join(`packages`, `node_modules`, packageName, filename))
  .map((filename) => ({
    src: filename,
    dest: filename.replace(`src`, `dist`)
  }));

  for (const file of mapped) {
    await exports.buildFile(file);
  }
};

exports.buildSamples = async function buildSamples() {
  await rimraf(`packages/node_modules/samples/bundle*`);
  await exec(`webpack`);
  await rename(`bundle.js`, `packages/node_modules/samples/bundle.js`);
  await rename(`bundle.js.map`, `packages/node_modules/samples/bundle.js.map`);

  const samples = await g(`browser-*`, {cwd: path.resolve(process.cwd(), `packages/node_modules/samples`)});

  const out = `<!DOCTYPE html>

  <title>Samples</title>

Hosted Samples

${samples.filter((s) => !s.includes(`auth`)).filter(Boolean).map((s) => `<li><a href="${s}">${S(s).humanize().capitalize().s}</a><li>`)}

  There's a working authorization sample in the git repository, though we don't have it hosted just yet (but it's coming soon).

`;

  await writeFile(`packages/node_modules/samples/index.html`, out);
};
<|endoftext|>


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

'use strict';

var fs = require('fs');
// or more concisely
var util = require('util')
var exec = require('child_process').exec;
var QueueDAO = require('../dao/QueuesDAO');

/**
 * Dialplan reloader V2.
 * @param switchboard_data
 * @constructor
 */
function MOHReloader(company_id, moh) {
    this.moh = moh;
    this.companyId = company_id;
    this.generateAsterisk();
};

/**
 * Generate ASterisk dialplan.
 * @param rootModule
 * @param modules
 */
MOHReloader.prototype.generateAsterisk = function generateAsterisk() {
    var finalConf = "; MOH " +this.moh[i].switchboard_id  + "\n";

    for (var i = 0, t = this.moh.length; i < t; i++) {
        finalConf += "[SWI_" + this.moh[i].switchboard_id  + "_" + this.moh[i].group_name + "]" + "\n"
            + "mode=files" + "\n"
            + "directory=/usr/scotip/usermoh/files/" + this.moh[i].mohgroup_id + "\n\n";

    }

    this.writeConf(finalConf);
};

MOHReloader.prototype.writeConf = function writeConf(configuration) {
    if (typeof process.env.PROD_SERVER !== "undefined" && process.env.PROD_SERVER == 1) {
        var basepath = "/usr/scotip/usermoh/conf/";
    } else {
        // Other's computer
        var basepath = "./generated/";
    }

    var filename = "moh_" + this.companyId + ".conf";
    var totalFilepath = basepath + filename;

    /**
     * To write file.
     * @param callback
     */
    function createFile(callback) {
        // create file
        fs.writeFile(totalFilepath, configuration, null, function (err) {
            if (err) {
                console.log("ERREUR :");
                console.log(err);
            } else {
                console.log("Conf OK");

                if (callback) {
                    callback();
                }
            }
        });
    }

    /**
     * It creates file...
     */
    createFile(this.reloadAsterisk);
};

/**
 * Try to reload SIP USERS asterisk.
 */
MOHReloader.prototype.reloadAsterisk = function reloadAsterisk() {

    exec("asterisk -rx \"moh reload\"", function (error, stdout, stderr) {
        if (error) {
            console.log("ERROR! " + error);
        }
        else {
            console.log(stdout);
        }
    });

};

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

'use strict';

var fs = require('fs');
// or more concisely
var util = require('util')
var exec = require('child_process').exec;
var QueueDAO = require('../dao/QueuesDAO');

/**
 * Dialplan reloader V2.
 * @param switchboard_data
 * @constructor
 */
function MOHReloader(company_id, moh) {
    this.moh = moh;
    this.companyId = company_id;
    this.generateAsterisk();
};

/**
 * Generate ASterisk dialplan.
 * @param rootModule
 * @param modules
 */
MOHReloader.prototype.generateAsterisk = function generateAsterisk() {
    var finalConf = "; MOH " + "\n";

    for (var i = 0, t = this.moh.length; i < t; i++) {
        finalConf += "[SWI_" + this.moh[i].switchboard_id  + "_" + this.moh[i].group_name + "]" + "\n"
            + "mode=files" + "\n"
            + "directory=/usr/scotip/usermoh/files/" + this.moh[i].mohgroup_id + "\n\n";

    }

    this.writeConf(finalConf);
};

MOHReloader.prototype.writeConf = function writeConf(configuration) {
    if (typeof process.env.PROD_SERVER !== "undefined" && process.env.PROD_SERVER == 1) {
        var basepath = "/usr/scotip/usermoh/conf/";
    } else {
        // Other's computer
        var basepath = "./generated/";
    }

    var filename = "moh_" + this.companyId + ".conf";
    var totalFilepath = basepath + filename;

    /**
     * To write file.
     * @param callback
     */
    function createFile(callback) {
        // create file
        fs.writeFile(totalFilepath, configuration, null, function (err) {
            if (err) {
                console.log("ERREUR :");
                console.log(err);
            } else {
                console.log("Conf OK");

                if (callback) {
                    callback();
                }
            }
        });
    }

    /**
     * It creates file...
     */
    createFile(this.reloadAsterisk);
};

/**
 * Try to reload SIP USERS asterisk.
 */
MOHReloader.prototype.reloadAsterisk = function reloadAsterisk() {

    exec("asterisk -rx \"moh reload\"", function (error, stdout, stderr) {
        if (error) {
            console.log("ERROR! " + error);
        }
        else {
            console.log(stdout);
        }
    });

};

module.exports = MOHReloader;
<|endoftext|>


<commit_before>var Fiber = require("fibers");
var fs = require("fs");
var path = require("path");
var Future = require("fibers/future");
var _ = require('underscore');
var sourcemap_support = require('source-map-support');

var bootUtils = require('./boot-utils.js');

// This code is duplicated in tools/main.js.
var MIN_NODE_VERSION = 'v0.10.33';

if (require('semver').lt(process.version, MIN_NODE_VERSION)) {
  process.stderr.write(
    'Meteor requires Node ' + MIN_NODE_VERSION + ' or later.\n');
  process.exit(1);
}

// read our control files
var serverJsonPath = path.resolve(process.argv[2]);
var serverDir = path.dirname(serverJsonPath);
var serverJson = JSON.parse(fs.readFileSync(serverJsonPath, 'utf8'));
var configJson =
  JSON.parse(fs.readFileSync(path.resolve(serverDir, 'config.json'), 'utf8'));

// Set up environment
__meteor_bootstrap__ = {
  startupHooks: [],
  serverDir: serverDir,
  configJson: configJson };
__meteor_runtime_config__ = { meteorRelease: configJson.meteorRelease };

// connect (and some other NPM modules) use $NODE_ENV to make some decisions;
// eg, if $NODE_ENV is not production, they send stack traces on error. connect
// considers 'development' to be the default mode, but that's less safe than
// assuming 'production' to be the default. If you really want development mode,
// set it in your wrapper script (eg, run-app.js).
if (!process.env.NODE_ENV)
  process.env.NODE_ENV = 'production';

// Map from load path to its source map.
var parsedSourceMaps = {};

// Read all the source maps into memory once.
_.each(serverJson.load, function (fileInfo) {
  if (fileInfo.sourceMap) {
    var rawSourceMap = fs.readFileSync(
      path.resolve(serverDir, fileInfo.sourceMap), 'utf8');
    // Parse the source map only once, not each time it's needed. Also remove
    // the anti-XSSI header if it's there.
    var parsedSourceMap = JSON.parse(rawSourceMap.replace(/^\)\]\}'/, ''));
    // source-map-support doesn't ever look at the sourcesContent field, so
    // there's no point in keeping it in memory.
    delete parsedSourceMap.sourcesContent;
    var url;
    if (fileInfo.sourceMapRoot) {
      // Add the specified root to any root that may be in the file.
      parsedSourceMap.sourceRoot = path.join(
        fileInfo.sourceMapRoot, parsedSourceMap.sourceRoot || '');
    }
    parsedSourceMaps[path.resolve(__dirname, fileInfo.path)] = parsedSourceMap;
  }
});

var retrieveSourceMap = function (pathForSourceMap) {
  if (_.has(parsedSourceMaps, pathForSourceMap))
    return { map: parsedSourceMaps[pathForSourceMap] };
  return null;
};

sourcemap_support.install({
  // Use the source maps specified in program.json instead of parsing source
  // code for them.
  retrieveSourceMap: retrieveSourceMap,
  // For now, don't fix the source line in uncaught exceptions, because we
  // haven't fixed handleUncaughtExceptions in source-map-support to properly
  // locate the source files.
  handleUncaughtExceptions: false
});

// Only enabled by default in development.
if (process.env.METEOR_SHELL_DIR) {
  require('./shell.js').listen(process.env.METEOR_SHELL_DIR);
}

// As a replacement to the old keepalives mechanism, check for a running
// parent every few seconds. Exit if the parent is not running.
//
// Two caveats to this strategy:
// * Doesn't catch the case where the parent is CPU-hogging (but maybe we
//   don't want to catch that case anyway, since the bundler not yielding
//   is what caused #2536).
// * Could be fooled by pid re-use, i.e. if another process comes up and
//   takes the parent process's place before the child process dies.
var startCheckForLiveParent = function (parentPid) {
  if (parentPid) {
    if (! bootUtils.validPid(parentPid)) {
      console.error("METEOR_PARENT_PID must be a valid process ID.");
      process.exit(1);
    }

    setInterval(function () {
      try {
        process.kill(parentPid, 0);
      } catch (err) {
        console.error("Parent process is dead! Exiting.");
        process.exit(1);
      }
    }, 3000);
  }
};

Fiber(function () {
  _.each(serverJson.load, function (fileInfo) {
    var code = fs.readFileSync(path.resolve(serverDir, fileInfo.path));

    var Npm = {
      /**
       * @summary Require a package that was specified using
       * `Npm.depends()`.
       * @param  {String} name The name of the package to require.
       * @locus Server
       * @memberOf Npm
       */
      require: function (name) {
        if (! fileInfo.node_modules) {
          return require(name);
        }

        var nodeModuleDir =
          path.resolve(serverDir, fileInfo.node_modules, name);

        if (fs.existsSync(nodeModuleDir)) {
          return require(nodeModuleDir);
          }
        try {
          return require(name);
        } catch (e) {
          // Try to guess the package name so we can print a nice
          // error message
          var filePathParts = fileInfo.path.split(path.sep);
          var packageName = filePathParts[1].replace(/\.js$/, '');

          // XXX better message
          throw new Error(
            "Can't find npm module '" + name +
              "'. Did you forget to call 'Npm.depends' in package.js " +
              "within the '" + packageName + "' package?");
          }
      }
    };
    var getAsset = function (assetPath, encoding, callback) {
      var fut;
      if (! callback) {
        fut = new Future();
        callback = fut.resolver();
      }
      // This assumes that we've already loaded the meteor package, so meteor
      // itself (and weird special cases like js-analyze) can't call
      // Assets.get*. (We could change this function so that it doesn't call
      // bindEnvironment if you don't pass a callback if we need to.)
      var _callback = Package.meteor.Meteor.bindEnvironment(function (err, result) {
        if (result && ! encoding)
          // Sadly, this copies in Node 0.10.
          result = new Uint8Array(result);
        callback(err, result);
      }, function (e) {
        console.log("Exception in callback of getAsset", e.stack);
      });

      // Convert a DOS-style path to Unix-style in case the application code was
      // written on Windows.
      // XXX note that we can't always correctly convert #WindowsPathApi
      if (assetPath.indexOf('/') !== -1) {
        // it is already a Unix-style path most likely
      } else {
        assetPath = assetPath.replace(/\\/g, '/');
      }

      if (!fileInfo.assets || !_.has(fileInfo.assets, assetPath)) {
        _callback(new Error("Unknown asset: " + assetPath));
      } else {
        var filePath = path.join(serverDir, fileInfo.assets[assetPath]);
        fs.readFile(filePath, encoding, _callback);
      }
      if (fut)
        return fut.wait();
    };

    var Assets = {
      getText: function (assetPath, callback) {
        return getAsset(assetPath, "utf8", callback);
      },
      getBinary: function (assetPath, callback) {
        return getAsset(assetPath, undefined, callback);
      }
    };

    // \n is necessary in case final line is a //-comment
    var wrapped = "(function(Npm, Assets){" + code + "\n})";

    // It is safer to use the absolute path when source map is present as
    // different tooling, such as node-inspector, can get confused on relative
    // urls.
    var absoluteFilePath = path.resolve(__dirname, fileInfo.path);
    var scriptPath =
      parsedSourceMaps[absoluteFilePath] ? absoluteFilePath : fileInfo.path;
    // The final 'true' is an undocumented argument to runIn[Foo]Context that
    // causes it to print out a descriptive error message on parse error. It's
    // what require() uses to generate its errors.
    var func = require('vm').runInThisContext(wrapped, scriptPath, true);
    func.call(global, Npm, Assets); // Coffeescript
  });

  // run the user startup hooks.  other calls to startup() during this can still
  // add hooks to the end.
  while (__meteor_bootstrap__.startupHooks.length) {
    var hook = __meteor_bootstrap__.startupHooks.shift();
    hook();
  }
  // Setting this to null tells Meteor.startup to call hooks immediately.
  __meteor_bootstrap__.startupHooks = null;

  // find and run main()
  // XXX hack. we should know the package that contains main.
  var mains = [];
  var globalMain;
  if ('main' in global) {
    mains.push(main);
    globalMain = main;
  }
  typeof Package !== 'undefined' && _.each(Package, function (p, n) {
    if ('main' in p && p.main !== globalMain) {
      mains.push(p.main);
    }
  });
  if (! mains.length) {
    process.stderr.write("Program has no main() function.\n");
    process.exit(1);
  }
  if (mains.length > 1) {
    process.stderr.write("Program has more than one main() function?\n");
    process.exit(1);
  }
  var exitCode = mains[0].call({}, process.argv.slice(3));
  // XXX hack, needs a better way to keep alive
  if (exitCode !== 'DAEMON')
    process.exit(exitCode);

  if (process.env.METEOR_PARENT_PID) {
    startCheckForLiveParent(process.env.METEOR_PARENT_PID);
  }
}).run();
<commit_msg>Be careful about paths in boot.js<commit_after>var Fiber = require("fibers");
var fs = require("fs");
var path = require("path");
var Future = require("fibers/future");
var _ = require('underscore');
var sourcemap_support = require('source-map-support');

var bootUtils = require('./boot-utils.js');
var files = require('./mini-files.js');

// This code is duplicated in tools/main.js.
var MIN_NODE_VERSION = 'v0.10.33';

if (require('semver').lt(process.version, MIN_NODE_VERSION)) {
  process.stderr.write(
    'Meteor requires Node ' + MIN_NODE_VERSION + ' or later.\n');
  process.exit(1);
}

// read our control files
var serverJsonPath = path.resolve(process.argv[2]);
var serverDir = path.dirname(serverJsonPath);
var serverJson = JSON.parse(fs.readFileSync(serverJsonPath, 'utf8'));
var configJson =
  JSON.parse(fs.readFileSync(path.resolve(serverDir, 'config.json'), 'utf8'));

// Set up environment
__meteor_bootstrap__ = {
  startupHooks: [],
  serverDir: serverDir,
  configJson: configJson };
__meteor_runtime_config__ = { meteorRelease: configJson.meteorRelease };

// connect (and some other NPM modules) use $NODE_ENV to make some decisions;
// eg, if $NODE_ENV is not production, they send stack traces on error. connect
// considers 'development' to be the default mode, but that's less safe than
// assuming 'production' to be the default. If you really want development mode,
// set it in your wrapper script (eg, run-app.js).
if (!process.env.NODE_ENV)
  process.env.NODE_ENV = 'production';

// Map from load path to its source map.
var parsedSourceMaps = {};

// Read all the source maps into memory once.
_.each(serverJson.load, function (fileInfo) {
  if (fileInfo.sourceMap) {
    var rawSourceMap = fs.readFileSync(
      path.resolve(serverDir, fileInfo.sourceMap), 'utf8');
    // Parse the source map only once, not each time it's needed. Also remove
    // the anti-XSSI header if it's there.
    var parsedSourceMap = JSON.parse(rawSourceMap.replace(/^\)\]\}'/, ''));
    // source-map-support doesn't ever look at the sourcesContent field, so
    // there's no point in keeping it in memory.
    delete parsedSourceMap.sourcesContent;
    var url;
    if (fileInfo.sourceMapRoot) {
      // Add the specified root to any root that may be in the file.
      parsedSourceMap.sourceRoot = path.join(
        fileInfo.sourceMapRoot, parsedSourceMap.sourceRoot || '');
    }
    parsedSourceMaps[path.resolve(__dirname, fileInfo.path)] = parsedSourceMap;
  }
});

var retrieveSourceMap = function (pathForSourceMap) {
  if (_.has(parsedSourceMaps, pathForSourceMap))
    return { map: parsedSourceMaps[pathForSourceMap] };
  return null;
};

sourcemap_support.install({
  // Use the source maps specified in program.json instead of parsing source
  // code for them.
  retrieveSourceMap: retrieveSourceMap,
  // For now, don't fix the source line in uncaught exceptions, because we
  // haven't fixed handleUncaughtExceptions in source-map-support to properly
  // locate the source files.
  handleUncaughtExceptions: false
});

// Only enabled by default in development.
if (process.env.METEOR_SHELL_DIR) {
  require('./shell.js').listen(process.env.METEOR_SHELL_DIR);
}

// As a replacement to the old keepalives mechanism, check for a running
// parent every few seconds. Exit if the parent is not running.
//
// Two caveats to this strategy:
// * Doesn't catch the case where the parent is CPU-hogging (but maybe we
//   don't want to catch that case anyway, since the bundler not yielding
//   is what caused #2536).
// * Could be fooled by pid re-use, i.e. if another process comes up and
//   takes the parent process's place before the child process dies.
var startCheckForLiveParent = function (parentPid) {
  if (parentPid) {
    if (! bootUtils.validPid(parentPid)) {
      console.error("METEOR_PARENT_PID must be a valid process ID.");
      process.exit(1);
    }

    setInterval(function () {
      try {
        process.kill(parentPid, 0);
      } catch (err) {
        console.error("Parent process is dead! Exiting.");
        process.exit(1);
      }
    }, 3000);
  }
};

Fiber(function () {
  _.each(serverJson.load, function (fileInfo) {
    var code = fs.readFileSync(path.resolve(serverDir, fileInfo.path));

    var Npm = {
      /**
       * @summary Require a package that was specified using
       * `Npm.depends()`.
       * @param  {String} name The name of the package to require.
       * @locus Server
       * @memberOf Npm
       */
      require: function (name) {
        if (! fileInfo.node_modules) {
          return require(name);
        }

        var nodeModuleDir =
          path.resolve(serverDir, fileInfo.node_modules,
            files.convertToOSPath(name));

        if (fs.existsSync(nodeModuleDir)) {
          return require(nodeModuleDir);
        }

        try {
          return require(name);
        } catch (e) {
          // Try to guess the package name so we can print a nice
          // error message
          // fileInfo.path is a standard path, use files.pathSep
          var filePathParts = fileInfo.path.split(files.pathSep);
          var packageName = filePathParts[1].replace(/\.js$/, '');

          // XXX better message
          throw new Error(
            "Can't find npm module '" + name +
              "'. Did you forget to call 'Npm.depends' in package.js " +
              "within the '" + packageName + "' package?");
          }
      }
    };
    var getAsset = function (assetPath, encoding, callback) {
      var fut;
      if (! callback) {
        fut = new Future();
        callback = fut.resolver();
      }
      // This assumes that we've already loaded the meteor package, so meteor
      // itself (and weird special cases like js-analyze) can't call
      // Assets.get*. (We could change this function so that it doesn't call
      // bindEnvironment if you don't pass a callback if we need to.)
      var _callback = Package.meteor.Meteor.bindEnvironment(function (err, result) {
        if (result && ! encoding)
          // Sadly, this copies in Node 0.10.
          result = new Uint8Array(result);
        callback(err, result);
      }, function (e) {
        console.log("Exception in callback of getAsset", e.stack);
      });

      // Convert a DOS-style path to Unix-style in case the application code was
      // written on Windows.
      assetPath = files.convertToStandardPath(assetPath);

      if (!fileInfo.assets || !_.has(fileInfo.assets, assetPath)) {
        _callback(new Error("Unknown asset: " + assetPath));
      } else {
        var filePath = path.join(serverDir, fileInfo.assets[assetPath]);
        fs.readFile(files.convertToOSPath(filePath), encoding, _callback);
      }
      if (fut)
        return fut.wait();
    };

    var Assets = {
      getText: function (assetPath, callback) {
        return getAsset(assetPath, "utf8", callback);
      },
      getBinary: function (assetPath, callback) {
        return getAsset(assetPath, undefined, callback);
      }
    };

    // \n is necessary in case final line is a //-comment
    var wrapped = "(function(Npm, Assets){" + code + "\n})";

    // It is safer to use the absolute path when source map is present as
    // different tooling, such as node-inspector, can get confused on relative
    // urls.

    // fileInfo.path is a standard path, convert it to OS path to join with
    // __dirname
    var fileInfoOSPath = files.convertToOSPath(fileInfo.path);
    var absoluteFilePath = path.resolve(__dirname, fileInfoOSPath);

    var scriptPath =
      parsedSourceMaps[absoluteFilePath] ? absoluteFilePath : fileInfoOSPath;
    // The final 'true' is an undocumented argument to runIn[Foo]Context that
    // causes it to print out a descriptive error message on parse error. It's
    // what require() uses to generate its errors.
    var func = require('vm').runInThisContext(wrapped, scriptPath, true);
    func.call(global, Npm, Assets); // Coffeescript
  });

  // run the user startup hooks.  other calls to startup() during this can still
  // add hooks to the end.
  while (__meteor_bootstrap__.startupHooks.length) {
    var hook = __meteor_bootstrap__.startupHooks.shift();
    hook();
  }
  // Setting this to null tells Meteor.startup to call hooks immediately.
  __meteor_bootstrap__.startupHooks = null;

  // find and run main()
  // XXX hack. we should know the package that contains main.
  var mains = [];
  var globalMain;
  if ('main' in global) {
    mains.push(main);
    globalMain = main;
  }
  typeof Package !== 'undefined' && _.each(Package, function (p, n) {
    if ('main' in p && p.main !== globalMain) {
      mains.push(p.main);
    }
  });
  if (! mains.length) {
    process.stderr.write("Program has no main() function.\n");
    process.exit(1);
  }
  if (mains.length > 1) {
    process.stderr.write("Program has more than one main() function?\n");
    process.exit(1);
  }
  var exitCode = mains[0].call({}, process.argv.slice(3));
  // XXX hack, needs a better way to keep alive
  if (exitCode !== 'DAEMON')
    process.exit(exitCode);

  if (process.env.METEOR_PARENT_PID) {
    startCheckForLiveParent(process.env.METEOR_PARENT_PID);
  }
}).run();
<|endoftext|>


<commit_before>var selftest = require('../selftest.js');
var Sandbox = selftest.Sandbox;
var testUtils = require('../test-utils.js');

var commandTimeoutSecs = testUtils.accountsCommandTimeoutSecs;
var loginTimeoutSecs = 2;

selftest.define("login", ['net'], function () {
  var s = new Sandbox;

  var run = s.run("whoami");
  run.matchErr("Not logged in");
  run.expectExit(1);

  // Username and password prompts happen on stderr so that scripts can
  // run commands that do login interactively and still save the command
  // output with the login prompts appearing in it.
  //
  // Do this twice to confirm that the login command prints a prompt
  // even if you are already logged in.
  for (var i = 0; i < 2; i++) {
    run = s.run("login");
    run.waitSecs(loginTimeoutSecs);
    run.matchErr("Username:");
    run.write("test\n");
    run.matchErr("Password:");
    run.write("testtest\n");
    run.waitSecs(commandTimeoutSecs);
    run.matchErr("Logged in as test.");
    run.expectExit(0);
  }

  // Leaving username blank, or getting the password wrong, doesn't
  // reprompt. It also doesn't log you out.
  run = s.run("login");
  run.waitSecs(loginTimeoutSecs);
  run.matchErr("Username:");
  run.write("\n");
  run.matchErr("Password:");
  run.write("whatever\n");
  run.waitSecs(commandTimeoutSecs);
  run.matchErr("failed");
  run.expectExit(1);

  run = s.run("login");
  run.waitSecs(loginTimeoutSecs);
  run.matchErr("Username:");
  run.write("test\n");
  run.matchErr("Password:");
  run.write("whatever\n");
  run.waitSecs(commandTimeoutSecs);
  run.matchErr("failed");
  run.expectExit(1);

  run = s.run('login');
  run.waitSecs(loginTimeoutSecs);
  run.matchErr("Username:");
  run.write("test\n");
  run.matchErr("Password:");
  run.write("testtest\n");
  run.waitSecs(commandTimeoutSecs);
  run.matchErr("Logged in as test.");
  run.expectExit(0);

  // XXX test login by email

  run = s.run("whoami");
  run.read("test\n");
  run.expectEnd();
  run.expectExit(0);

  run = s.run("logout");
  run.waitSecs(commandTimeoutSecs);
  run.matchErr("Logged out");
  run.expectExit(0);

  run = s.run("logout");
  run.waitSecs(commandTimeoutSecs);
  run.matchErr("Not logged in");
  run.expectExit(0);

  run = s.run("whoami");
  run.matchErr("Not logged in");
  run.expectExit(1);

  // Test login failure
  run = s.run("login");
  run.waitSecs(loginTimeoutSecs);
  run.matchErr("Username:");
  run.write("test\n");
  run.matchErr("Password:");
  run.write("badpassword\n");
  run.waitSecs(commandTimeoutSecs);
  run.matchErr("Login failed");
  run.expectExit(1);

  // Logging in with a capitalized username should work (usernames are
  // case-insensitive).
  run = s.run("login");
  run.waitSecs(loginTimeoutSecs);
  run.matchErr("Username:");
  run.write("TeSt\n");
  run.matchErr("Password:");
  run.write("testtest\n");
  run.waitSecs(commandTimeoutSecs);
  run.matchErr("Logged in as test.");
  run.expectExit(0);

  run = s.run("logout");
  run.waitSecs(commandTimeoutSecs);
  run.matchErr("Logged out");
  run.expectExit(0);

  // Logging in with a capitalized password should NOT work (can't be
  // too safe...)
  run = s.run("login");
  run.waitSecs(loginTimeoutSecs);
  run.matchErr("Username:");
  run.write("test\n");
  run.matchErr("Password:");
  run.write("TesTTesT\n");
  run.waitSecs(commandTimeoutSecs);
  run.matchErr("Login failed");
  run.expectExit(1);
});

selftest.define('whoami - no username', ['net', 'slow'], function () {
  var s = new Sandbox;
  var email = testUtils.randomUserEmail();
  var username = testUtils.randomString(10);
  var appName = testUtils.randomAppName();
  var token = testUtils.deployWithNewEmail(s, email, appName);

  var run = s.run('whoami');
  run.waitSecs(commandTimeoutSecs);
  run.matchErr('You haven\'t chosen your username yet');
  run.matchErr(testUtils.registrationUrlRegexp);
  run.expectExit(1);
  testUtils.registerWithToken(token, username, 'test', email);

  run = s.run('whoami');
  run.waitSecs(commandTimeoutSecs);
  run.read(username);
  run.expectExit(0);

  testUtils.cleanUpApp(s, appName);
  testUtils.logout(s);
});
<commit_msg>Remove 'expectEnd' from login test.<commit_after>var selftest = require('../selftest.js');
var Sandbox = selftest.Sandbox;
var testUtils = require('../test-utils.js');

var commandTimeoutSecs = testUtils.accountsCommandTimeoutSecs;
var loginTimeoutSecs = 2;

selftest.define("login", ['net'], function () {
  var s = new Sandbox;

  var run = s.run("whoami");
  run.matchErr("Not logged in");
  run.expectExit(1);

  // Username and password prompts happen on stderr so that scripts can
  // run commands that do login interactively and still save the command
  // output with the login prompts appearing in it.
  //
  // Do this twice to confirm that the login command prints a prompt
  // even if you are already logged in.
  for (var i = 0; i < 2; i++) {
    run = s.run("login");
    run.waitSecs(loginTimeoutSecs);
    run.matchErr("Username:");
    run.write("test\n");
    run.matchErr("Password:");
    run.write("testtest\n");
    run.waitSecs(commandTimeoutSecs);
    run.matchErr("Logged in as test.");
    run.expectExit(0);
  }

  // Leaving username blank, or getting the password wrong, doesn't
  // reprompt. It also doesn't log you out.
  run = s.run("login");
  run.waitSecs(loginTimeoutSecs);
  run.matchErr("Username:");
  run.write("\n");
  run.matchErr("Password:");
  run.write("whatever\n");
  run.waitSecs(commandTimeoutSecs);
  run.matchErr("failed");
  run.expectExit(1);

  run = s.run("login");
  run.waitSecs(loginTimeoutSecs);
  run.matchErr("Username:");
  run.write("test\n");
  run.matchErr("Password:");
  run.write("whatever\n");
  run.waitSecs(commandTimeoutSecs);
  run.matchErr("failed");
  run.expectExit(1);

  run = s.run('login');
  run.waitSecs(loginTimeoutSecs);
  run.matchErr("Username:");
  run.write("test\n");
  run.matchErr("Password:");
  run.write("testtest\n");
  run.waitSecs(commandTimeoutSecs);
  run.matchErr("Logged in as test.");
  run.expectExit(0);

  // XXX test login by email

  run = s.run("whoami");
  run.read("test\n");
  run.expectExit(0);

  run = s.run("logout");
  run.waitSecs(commandTimeoutSecs);
  run.matchErr("Logged out");
  run.expectExit(0);

  run = s.run("logout");
  run.waitSecs(commandTimeoutSecs);
  run.matchErr("Not logged in");
  run.expectExit(0);

  run = s.run("whoami");
  run.matchErr("Not logged in");
  run.expectExit(1);

  // Test login failure
  run = s.run("login");
  run.waitSecs(loginTimeoutSecs);
  run.matchErr("Username:");
  run.write("test\n");
  run.matchErr("Password:");
  run.write("badpassword\n");
  run.waitSecs(commandTimeoutSecs);
  run.matchErr("Login failed");
  run.expectExit(1);

  // Logging in with a capitalized username should work (usernames are
  // case-insensitive).
  run = s.run("login");
  run.waitSecs(loginTimeoutSecs);
  run.matchErr("Username:");
  run.write("TeSt\n");
  run.matchErr("Password:");
  run.write("testtest\n");
  run.waitSecs(commandTimeoutSecs);
  run.matchErr("Logged in as test.");
  run.expectExit(0);

  run = s.run("logout");
  run.waitSecs(commandTimeoutSecs);
  run.matchErr("Logged out");
  run.expectExit(0);

  // Logging in with a capitalized password should NOT work (can't be
  // too safe...)
  run = s.run("login");
  run.waitSecs(loginTimeoutSecs);
  run.matchErr("Username:");
  run.write("test\n");
  run.matchErr("Password:");
  run.write("TesTTesT\n");
  run.waitSecs(commandTimeoutSecs);
  run.matchErr("Login failed");
  run.expectExit(1);
});

selftest.define('whoami - no username', ['net', 'slow'], function () {
  var s = new Sandbox;
  var email = testUtils.randomUserEmail();
  var username = testUtils.randomString(10);
  var appName = testUtils.randomAppName();
  var token = testUtils.deployWithNewEmail(s, email, appName);

  var run = s.run('whoami');
  run.waitSecs(commandTimeoutSecs);
  run.matchErr('You haven\'t chosen your username yet');
  run.matchErr(testUtils.registrationUrlRegexp);
  run.expectExit(1);
  testUtils.registerWithToken(token, username, 'test', email);

  run = s.run('whoami');
  run.waitSecs(commandTimeoutSecs);
  run.read(username);
  run.expectExit(0);

  testUtils.cleanUpApp(s, appName);
  testUtils.logout(s);
});
<|endoftext|>