<commit_before>'use strict';
const fs = require('fs');
const FILE_PATH_FR = './cv.html';
const FILE_PATH_EN = './resume.html'

let fileContentsFr = fs.readFileSync(FILE_PATH_FR, { encoding: 'utf-8' });
let fileContentsEn = fs.readFileSync(FILE_PATH_EN, { encoding: 'utf-8' });

const translations = {
  'About': 'À propos',
  'Work Experience': 'Expérience Professionnelle',
  'Education': 'Formation',
  'Skills': 'Compétences',
  'Languages': 'Langues',
  'Hobbies': 'Intérêts',
  '
Courses
': '',
  'January': 'Janvier',
  'February': 'Février',
  'March': 'Mars',
  'April': 'Avril',
  'May': 'Mai',
  'June': 'Juin',
  'July': 'Juillet',
  'August': 'Août',
  'September': 'Septembre',
  'October': 'Octobre',
  'November': 'Novembre',
  'December': 'Décembre'
};

const fixes = {
  '
Highlights
': '',
  'Resume of Hugo Agbonon': 'Hugo Agbonon'
}

Object.keys(translations).forEach(key => {
  fileContentsFr = fileContentsFr.replace(new RegExp(key, 'g'), translations[key])
});

Object.keys(fixes).forEach(key => {
  fileContentsFr = fileContentsFr.replace(new RegExp(key, 'g'), fixes[key])
  fileContentsEn = fileContentsEn.replace(new RegExp(key, 'g'), fixes[key])
});

const anonScript = ``;

fs.writeFileSync(FILE_PATH_FR, fileContentsFr.concat(anonScript), { encoding: 'utf-8' });
fs.writeFileSync(FILE_PATH_EN, fileContentsEn.concat(anonScript), { encoding: 'utf-8' });
<commit_msg>Update augmentFiles to translate Interests to Centres d'intérêts<commit_after>'use strict';
const fs = require('fs');
const FILE_PATH_FR = './cv.html';
const FILE_PATH_EN = './resume.html'

let fileContentsFr = fs.readFileSync(FILE_PATH_FR, { encoding: 'utf-8' });
let fileContentsEn = fs.readFileSync(FILE_PATH_EN, { encoding: 'utf-8' });

const translations = {
  'About': 'À propos',
  'Work Experience': 'Expérience Professionnelle',
  'Education': 'Formation',
  'Skills': 'Compétences',
  'Languages': 'Langues',
  'Interests': 'Centres d\'intérêts',
  '
Courses
': '',
  'January': 'Janvier',
  'February': 'Février',
  'March': 'Mars',
  'April': 'Avril',
  'May': 'Mai',
  'June': 'Juin',
  'July': 'Juillet',
  'August': 'Août',
  'September': 'Septembre',
  'October': 'Octobre',
  'November': 'Novembre',
  'December': 'Décembre'
};

const fixes = {
  '
Highlights
': '',
  'Resume of Hugo Agbonon': 'Hugo Agbonon'
}

Object.keys(translations).forEach(key => {
  fileContentsFr = fileContentsFr.replace(new RegExp(key, 'g'), translations[key])
});

Object.keys(fixes).forEach(key => {
  fileContentsFr = fileContentsFr.replace(new RegExp(key, 'g'), fixes[key])
  fileContentsEn = fileContentsEn.replace(new RegExp(key, 'g'), fixes[key])
});

const anonScript = ``;

fs.writeFileSync(FILE_PATH_FR, fileContentsFr.concat(anonScript), { encoding: 'utf-8' });
fs.writeFileSync(FILE_PATH_EN, fileContentsEn.concat(anonScript), { encoding: 'utf-8' });
<|endoftext|>


<commit_before>import Vue from 'vue'

Vue.config.productionTip = false

// require all test files (files that ends with .spec.js)
const testsContext = require.context('./specs', true, /\.spec$/)
// const testsContext = require.context('./specs', true, /checkFilter.spec$/)
testsContext.keys().forEach(testsContext)

// require all src files except main.js for coverage.
// you can also change this to match only the subset of files that
// you want coverage for.
const srcContext = require.context('../../src', true, /^\.\/(?!main(\.js)?$)/)
srcContext.keys().forEach(srcContext)
<commit_msg>remove useless require<commit_after>import Vue from 'vue'

Vue.config.productionTip = false

// require all test files (files that ends with .spec.js)
const testsContext = require.context('./specs', true, /\.spec$/)
// const testsContext = require.context('./specs', true, /checkFilter.spec$/)
testsContext.keys().forEach(testsContext)

// require all src files except main.js for coverage.
// you can also change this to match only the subset of files that
// you want coverage for.
// const srcContext = require.context('../../src', true, /^\.\/(?!main(\.js)?$)/)
// srcContext.keys().forEach(srcContext)
<|endoftext|>


<commit_before>const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
const nock = require('nock');
chai.use(chaiAsPromised);
chai.should();
const expect = chai.expect;

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

before(function () {
  let base = 'https://api.pnut.io/v0';

  nock(base)
    .get('/users/1')
    .reply(200, {});

  nock(base)
    .get('/users?ids=4,12,1000')
    .reply(200, {});

  nock(base)
    .get('/users/1/mentions')
    .reply(200, {});

  nock(base)
    .get('/users/1/posts')
    .reply(200, {});

  nock(base)
    .get('/users/1/avatar')
    .reply(200, {});

  nock(base)
    .get('/users/1/cover')
    .reply(200, {});

  nock(base)
    .put('/users/me', { locale: 'de_DE', timezone: 'Europe/Berlin' })
    .reply(200, {});

  nock(base)
    .patch('/users/me', { name: 'pnut-butter user' })
    .reply(200, {});

  nock(base)
    .get('/users/1/following')
    .reply(200, {});

  nock(base)
    .get('/users/1/followers')
    .reply(200, {});

  nock(base)
    .put('/users/2/follow')
    .reply(200, {});

  nock(base)
    .delete('/users/2/follow')
    .reply(200, {});

  nock(base)
    .get('/users/me/muted')
    .reply(200, {});

  nock(base)
    .put('/users/2/mute')
    .reply(200, {});

  nock(base)
    .delete('/users/2/mute')
    .reply(200, {});

  nock(base)
    .get('/users/me/blocked')
    .reply(200, {});

  nock(base)
    .put('/users/2/block')
    .reply(200, {});

  nock(base)
    .delete('/users/2/block')
    .reply(200, {});

  nock(base)
    .get('/presence')
    .reply(200, {});

  nock(base)
    .get('/presence/2')
    .reply(200, {});

  nock(base)
    .put('/users/me/presence')
    .reply(200, {});

  nock(base)
    .put('/users/me/presence', { presence: 'A presence message' })
    .reply(200, {});
});

after(function () {
  nock.cleanAll();
});

describe('User endpoints', () => {

  it('should be able to fetch a user by id', () => {
    return pnut.user(1).should.become({});
  });

  it('should be able to fetch users by their ids', () => {
    return pnut.users(4, 12, 1000).should.become({});
  });

  it('should be able to fetch a users avatar', () => {
    expect(pnut.avatar(1)).to.be.fulfilled;
  });

  it('should be able to fetch a users cover', () => {
    expect(pnut.cover('1')).to.be.fulfilled;
  });

  it('should be able to update the profile with a single object', () => {
    return pnut.replaceProfile({
      locale: 'de_DE',
      timezone: 'Europe/Berlin'
    }).should.become({});
  });

  it('should be able to update only given parts of the profile', () => {
    return pnut.updateProfile({
      name: 'pnut-butter user'
    }).should.become({});
  });

  it('should be able to retrieve a list of people a user follows', () => {
    return pnut.following(1).should.become({});
  });

  it('should be able to retrieve a list of people a user is following', () => {
    return pnut.followers(1).should.become({});
  });

  it('should be able to follow another user', () => {
    return pnut.follow(2).should.become({});
  });

  it('should be able to unfollow a user', () => {
    return pnut.unfollow(2).should.become({});
  });

  it('should be able to get a list of muted users', () => {
    return pnut.muted().should.become({});
  });

  it('should be able to mute a user', () => {
    return pnut.mute(2).should.become({});
  });

  it('should be able to unmute a user', () => {
    return pnut.unmute(2).should.become({});
  });

  it('should be able to get a list of blocked users', () => {
    return pnut.blocked(2).should.become({});
  });

  it('should be able to block a user', () => {
    return pnut.block(2).should.become({});
  });

  it('should be able to unblock a user', () => {
    return pnut.unblock(2).should.become({});
  });

  it('should be able to get presence information for all users', () => {
    return pnut.presence().should.become({});
  });

  it('should be able to get presence information of another user', () => {
    return pnut.presenceOf(2).should.become({});
  });

  it('should be able to update presence', () => {
    return pnut.updatePresence().should.become({});
  });

  it('should be able to update presence with an optional message', () => {
    return pnut.updatePresence("A presence message").should.become({});
  });

});<commit_msg>Reformat<commit_after>const chai = require("chai");
const chaiAsPromised = require("chai-as-promised");
const nock = require("nock");
chai.use(chaiAsPromised);
chai.should();
const expect = chai.expect;

const pnut = require("../lib/pnut");

before(function() {
  let base = "https://api.pnut.io/v0";

  nock(base).get("/users/1").reply(200, {});

  nock(base).get("/users?ids=4,12,1000").reply(200, {});

  nock(base).get("/users/1/mentions").reply(200, {});

  nock(base).get("/users/1/posts").reply(200, {});

  nock(base).get("/users/1/avatar").reply(200, {});

  nock(base).get("/users/1/cover").reply(200, {});

  nock(base)
    .put("/users/me", { locale: "de_DE", timezone: "Europe/Berlin" })
    .reply(200, {});

  nock(base).patch("/users/me", { name: "pnut-butter user" }).reply(200, {});

  nock(base).get("/users/1/following").reply(200, {});

  nock(base).get("/users/1/followers").reply(200, {});

  nock(base).put("/users/2/follow").reply(200, {});

  nock(base).delete("/users/2/follow").reply(200, {});

  nock(base).get("/users/me/muted").reply(200, {});

  nock(base).put("/users/2/mute").reply(200, {});

  nock(base).delete("/users/2/mute").reply(200, {});

  nock(base).get("/users/me/blocked").reply(200, {});

  nock(base).put("/users/2/block").reply(200, {});

  nock(base).delete("/users/2/block").reply(200, {});

  nock(base).get("/presence").reply(200, {});

  nock(base).get("/presence/2").reply(200, {});

  nock(base).put("/users/me/presence").reply(200, {});

  nock(base)
    .put("/users/me/presence", { presence: "A presence message" })
    .reply(200, {});
});

after(function() {
  nock.cleanAll();
});

describe("User endpoints", () => {
  it("should be able to fetch a user by id", () => {
    return pnut.user(1).should.become({});
  });

  it("should be able to fetch users by their ids", () => {
    return pnut.users(4, 12, 1000).should.become({});
  });

  it("should be able to fetch a users avatar", () => {
    expect(pnut.avatar(1)).to.be.fulfilled;
  });

  it("should be able to fetch a users cover", () => {
    expect(pnut.cover("1")).to.be.fulfilled;
  });

  it("should be able to update the profile with a single object", () => {
    return pnut
      .replaceProfile({
        locale: "de_DE",
        timezone: "Europe/Berlin"
      })
      .should.become({});
  });

  it("should be able to update only given parts of the profile", () => {
    return pnut
      .updateProfile({
        name: "pnut-butter user"
      })
      .should.become({});
  });

  it("should be able to retrieve a list of people a user follows", () => {
    return pnut.following(1).should.become({});
  });

  it("should be able to retrieve a list of people a user is following", () => {
    return pnut.followers(1).should.become({});
  });

  it("should be able to follow another user", () => {
    return pnut.follow(2).should.become({});
  });

  it("should be able to unfollow a user", () => {
    return pnut.unfollow(2).should.become({});
  });

  it("should be able to get a list of muted users", () => {
    return pnut.muted().should.become({});
  });

  it("should be able to mute a user", () => {
    return pnut.mute(2).should.become({});
  });

  it("should be able to unmute a user", () => {
    return pnut.unmute(2).should.become({});
  });

  it("should be able to get a list of blocked users", () => {
    return pnut.blocked(2).should.become({});
  });

  it("should be able to block a user", () => {
    return pnut.block(2).should.become({});
  });

  it("should be able to unblock a user", () => {
    return pnut.unblock(2).should.become({});
  });

  it("should be able to get presence information for all users", () => {
    return pnut.presence().should.become({});
  });

  it("should be able to get presence information of another user", () => {
    return pnut.presenceOf(2).should.become({});
  });

  it("should be able to update presence", () => {
    return pnut.updatePresence().should.become({});
  });

  it("should be able to update presence with an optional message", () => {
    return pnut.updatePresence("A presence message").should.become({});
  });
});
<|endoftext|>


<commit_before>"use strict";

const chai = require("chai");
const expect = chai.expect;
const utils = require("../src/utils.js");

describe("utils", () => {
	describe("stringToBytes(str, encoding)", () => {
		it("should return array of char codes for string with encoding UTF8", () => {
			function test(str) {
				let bytes = utils.stringToBytes(str);
				let realBytes = new Array(str.length);
				for (let i = 0; i < str.length; i++) {
					realBytes[i] = str.charCodeAt(i);
				}
				expect(bytes).to.eql(realBytes);
			}
			test("0123");
			test("abbacaba");
			test("d D_0_!_%>");
		});

		it("should return array of char for string with any encoding", () => {
			function test(str, bytesPerChar, realBytes) {
				let bytes = utils.stringToBytes(str, bytesPerChar);
				expect(bytes).to.be.eql(realBytes);
			}
			test("0123", 1, [48, 49, 50, 51]);
			test("топчик", 2, [4, 66, 4, 62, 4, 63, 4, 71, 4, 56, 4, 58]);
			test("自家个測試", 2, [129, 234, 91, 182, 78, 42, 110, 44, 138, 102])

		});
	});

	describe("bytesToString(str, bytesPerChar)", () => {
		it("should convert bytes to string with encoding UTF8(1 byte per character)", () => {
			function test(bytes) {
				let str = utils.bytesToString(bytes);
				let realStr = "";
				for (let i = 0; i < bytes.length; i++) {
					realStr += String.fromCharCode(bytes[i]);
				}
				expect(str).to.equal(realStr);
			}
			test([0, 1, 2, 255]);
			test([0, 100, 56, 48]);
		});

		it("should convert bytes to string with any encoding", () => {
			function test(bytes, bytesPerChar, realStr) {
				let str = utils.bytesToString(bytes, bytesPerChar);
				expect(str).to.be.equal(realStr);
			}
			test([48, 49, 50, 51], 1, "0123");
			test([4, 66, 4, 62, 4, 63, 4, 71, 4, 56, 4, 58], 2, "топчик");
		});
	});
});<commit_msg>Updates utils-test<commit_after>"use strict";

const chai = require("chai");
const expect = chai.expect;
const utils = require("../src/utils.js");

describe("utils", () => {
	describe("stringToBytes(str, encoding)", () => {
		it("should return array of char codes for string with encoding UTF8", () => {
			function test(str) {
				let bytes = utils.stringToBytes(str);
				let realBytes = new Array(str.length);
				for (let i = 0; i < str.length; i++) {
					realBytes[i] = str.charCodeAt(i);
				}
				expect(bytes).to.eql(realBytes);
			}
			test("0123");
			test("abbacaba");
			test("d D_0_!_%>");
		});

		it("should return array of char for string with any encoding", () => {
			function test(str, bytesPerChar, realBytes) {
				let bytes = utils.stringToBytes(str, bytesPerChar);
				expect(bytes).to.be.eql(realBytes);
			}
			test("0123", 1, [48, 49, 50, 51]);
			test("топчик", 2, [4, 66, 4, 62, 4, 63, 4, 71, 4, 56, 4, 58]);
			test("自家个測試", 2, [129, 234, 91, 182, 78, 42, 110, 44, 138, 102])

		});
	});

	describe("bytesToString(str, bytesPerChar)", () => {
		it("should convert bytes to string with encoding UTF8(1 byte per character)", () => {
			function test(bytes) {
				let str = utils.bytesToString(bytes);
				let realStr = "";
				for (let i = 0; i < bytes.length; i++) {
					realStr += String.fromCharCode(bytes[i]);
				}
				expect(str).to.equal(realStr);
			}
			test([0, 1, 2, 255]);
			test([0, 100, 56, 48]);
		});

		it("should convert bytes to string with any encoding", () => {
			function test(bytes, bytesPerChar, realStr) {
				let str = utils.bytesToString(bytes, bytesPerChar);
				expect(str).to.be.equal(realStr);
			}
			test([48, 49, 50, 51], 1, "0123");
			test([4, 66, 4, 62, 4, 63, 4, 71, 4, 56, 4, 58], 2, "топчик");
		});
	});

	describe("detectBytesPerChar(str)", () => {
		it("should return minimal number of bytes that need to code each character", () => {
			function test(str, answer) {
				let bytesPerChar = utils.detectBytesPerChar(str);
				expect(bytesPerChar).to.be.equal(answer);
			}
			test("0123a", 1);
			test("топчик еее", 2);
			test("assa 个 domik kek", 2);
		});
	});
});<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var utils = require('connect/utils'),
    assert = require('assert');

module.exports = {
    'test md5()': function(){
        assert.equal('5JMpgGF2EjbJawLqaqiirQ==', utils.md5('wahoo', 'base64'));
        assert.equal('e493298061761236c96b02ea6aa8a2ad', utils.md5('wahoo'));
    },

    'test toBoolean()': function(){
        assert.strictEqual(true, utils.toBoolean(true));
        assert.strictEqual(true, utils.toBoolean(1));
        assert.strictEqual(true, utils.toBoolean('1'));
        assert.strictEqual(true, utils.toBoolean('true'));
        assert.strictEqual(true, utils.toBoolean('yes'));
        assert.strictEqual(true, utils.toBoolean('y'));

        assert.strictEqual(false, utils.toBoolean(false));
        assert.strictEqual(false, utils.toBoolean(0));
        assert.strictEqual(false, utils.toBoolean('0'));
        assert.strictEqual(false, utils.toBoolean('-1'));
        assert.strictEqual(false, utils.toBoolean('false'));
        assert.strictEqual(false, utils.toBoolean('no'));
        assert.strictEqual(false, utils.toBoolean('n'));
        assert.strictEqual(false, utils.toBoolean('awrasdfasdfas'));
        assert.strictEqual(false, utils.toBoolean(''));
    },

    'test parseCookie()': function(){
        assert.eql({ foo: 'bar' }, utils.parseCookie('foo=bar'));
        assert.eql({ sid: '123' }, utils.parseCookie('SID=123'));
        assert.eql({ sid: '123' }, utils.parseCookie('SID=123;SID=somethingElse'));
        assert.eql({ foo: 'bar', baz: 'raz' }, utils.parseCookie('foo   =  bar; baz = raz'));
        assert.eql({ fbs: 'uid=0987654321&name=Test User' }, utils.parseCookie('fbs="uid=0987654321&name=Test+User"'));
    },

    'test serializeCookie()': function(){
        assert.equal('foo=bar; path=/', utils.serializeCookie('foo', 'bar', { path: '/' }));
        assert.equal('foo=bar; secure', utils.serializeCookie('foo', 'bar', { secure: true }));
        assert.equal('foo=bar', utils.serializeCookie('foo', 'bar', { secure: false }));
        assert.equal('foo=foo%20bar', utils.serializeCookie('foo', 'foo bar'));
    },

    'test mime.type()': function(){
        assert.equal('image/png', utils.mime.type('some.png'));
        assert.equal('image/png', utils.mime.type('some.lame.PNG'));
        assert.equal('image/png', utils.mime.type('some.lame.png'));
        assert.equal('image/png', utils.mime.type('path/to/some/ super lame.png'));
        assert.equal('application/octet-stream', utils.mime.type('foo.bar'));
        assert.equal('application/octet-stream', utils.mime.type(''));
        assert.equal('application/octet-stream', utils.mime.type());

    },

    'test miniMarkdown': function(){
        assert.equal('foo', utils.miniMarkdown('_foo_'));
        assert.equal('foo', utils.miniMarkdown('*foo*'));
        assert.equal('foo', utils.miniMarkdown('**foo**'));
        assert.equal('foo', utils.miniMarkdown('__foo__'));
        assert.equal('foo_', utils.miniMarkdown('_foo__'));
        assert.equal('User Login', utils.miniMarkdown('[User Login](/login)'));
    },

    'test escapeHtml()': function(){
        assert.equal('<p>', utils.htmlEscape('
'));
    }
};<commit_msg>Added tests for util.merge()<commit_after>
/**
 * Module dependencies.
 */

var utils = require('connect/utils'),
    assert = require('assert');

module.exports = {
    'test md5()': function(){
        assert.equal('5JMpgGF2EjbJawLqaqiirQ==', utils.md5('wahoo', 'base64'));
        assert.equal('e493298061761236c96b02ea6aa8a2ad', utils.md5('wahoo'));
    },

    'test merge()': function(){
        assert.eql({ foo: 'bar' }, utils.merge({ foo: 'bar' }));
        assert.eql({ foo: 'bar', bar: 'baz' }, utils.merge({ foo: 'bar' }, { bar: 'baz' }));
        assert.eql({ foo: 'baz' }, utils.merge({ foo: 'bar' }, { foo: 'baz' }));
    },

    'test toBoolean()': function(){
        assert.strictEqual(true, utils.toBoolean(true));
        assert.strictEqual(true, utils.toBoolean(1));
        assert.strictEqual(true, utils.toBoolean('1'));
        assert.strictEqual(true, utils.toBoolean('true'));
        assert.strictEqual(true, utils.toBoolean('yes'));
        assert.strictEqual(true, utils.toBoolean('y'));

        assert.strictEqual(false, utils.toBoolean(false));
        assert.strictEqual(false, utils.toBoolean(0));
        assert.strictEqual(false, utils.toBoolean('0'));
        assert.strictEqual(false, utils.toBoolean('-1'));
        assert.strictEqual(false, utils.toBoolean('false'));
        assert.strictEqual(false, utils.toBoolean('no'));
        assert.strictEqual(false, utils.toBoolean('n'));
        assert.strictEqual(false, utils.toBoolean('awrasdfasdfas'));
        assert.strictEqual(false, utils.toBoolean(''));
    },

    'test parseCookie()': function(){
        assert.eql({ foo: 'bar' }, utils.parseCookie('foo=bar'));
        assert.eql({ sid: '123' }, utils.parseCookie('SID=123'));
        assert.eql({ sid: '123' }, utils.parseCookie('SID=123;SID=somethingElse'));
        assert.eql({ foo: 'bar', baz: 'raz' }, utils.parseCookie('foo   =  bar; baz = raz'));
        assert.eql({ fbs: 'uid=0987654321&name=Test User' }, utils.parseCookie('fbs="uid=0987654321&name=Test+User"'));
    },

    'test serializeCookie()': function(){
        assert.equal('foo=bar; path=/', utils.serializeCookie('foo', 'bar', { path: '/' }));
        assert.equal('foo=bar; secure', utils.serializeCookie('foo', 'bar', { secure: true }));
        assert.equal('foo=bar', utils.serializeCookie('foo', 'bar', { secure: false }));
        assert.equal('foo=foo%20bar', utils.serializeCookie('foo', 'foo bar'));
    },

    'test mime.type()': function(){
        assert.equal('image/png', utils.mime.type('some.png'));
        assert.equal('image/png', utils.mime.type('some.lame.PNG'));
        assert.equal('image/png', utils.mime.type('some.lame.png'));
        assert.equal('image/png', utils.mime.type('path/to/some/ super lame.png'));
        assert.equal('application/octet-stream', utils.mime.type('foo.bar'));
        assert.equal('application/octet-stream', utils.mime.type(''));
        assert.equal('application/octet-stream', utils.mime.type());

    },

    'test miniMarkdown': function(){
        assert.equal('foo', utils.miniMarkdown('_foo_'));
        assert.equal('foo', utils.miniMarkdown('*foo*'));
        assert.equal('foo', utils.miniMarkdown('**foo**'));
        assert.equal('foo', utils.miniMarkdown('__foo__'));
        assert.equal('foo_', utils.miniMarkdown('_foo__'));
        assert.equal('User Login', utils.miniMarkdown('[User Login](/login)'));
    },

    'test escapeHtml()': function(){
        assert.equal('<p>', utils.htmlEscape('
'));
    }
};<|endoftext|>


<commit_before>'use strict';
import shell from 'shelljs';
import bs from 'browser-sync';
import config from '../config.js';
import configLoader from './../config-loader';
import Generator from 'confetti-generator';
import Loader from 'confetti-loader';
import watchAll from './../assets-watchers';
import * as logger from './../logger';
import path from 'path';
import del from 'del';
const loader = new Loader();
/*
 Function to load data and to build the slide deck.
 */
const build = (bs, dev, folder, serveDist, cb) => {
  logger.message('Loading speaker deck data...');
  loader.loadDeck(configLoader, serveDist)
    .then(deckData => {
      const generator = new Generator(deckData.paths, serveDist);
      logger.success('Speaker deck data loaded.');
      logger.message('Generating speaker deck...');
      generator.generate(deckData)
        .then(() => {
          cb(generator, deckData, bs, folder, serveDist, dev);
        })
        .catch(error => {
          logger.error(error);
          shell.exit(1);
        });
    })
    .catch(error => {
      logger.error(error);
      shell.exit(1);
    });
};
/*
 Function called after the slide deck is built.
 */
const callback = (generator, deckData, bs, folder, serveDist, dev) => {
  // Don't call init method if the bs is active yet.
  if (!bs.active) {
    bs.create();
    bs.init({server: folder, open: false});
    /*
     Watch changes on:
     - slide deck settings
     - data slides
     - selected theme config
     */
    bs.watch([
      configLoader.paths.settings,
      configLoader.paths.slides,
      path.join(configLoader.paths.themes, deckData.theme, 'data.yml')
    ]).on('change', () => {
      // If anything is changed rebuild the deck
      build(bs, dev, folder, serveDist, callback);
    });
    bs.watch(configLoader.paths.covers).on('change',
      () => generator.copyCovers().catch(error => logger.error(error)));
    bs.watch(folder).on('change', bs.reload);
    /*
     Watch the theme assets only if the dev mode is switched on.
     */
    if (dev) {
      logger.info('Theme development environment enabled.');
      watchAll(bs, generator, deckData);
    }
  }
};
//--------------
// Serve Command
//--------------
exports.command = 'server';
exports.builder = {
  dev: {
    describe: `Enables watching and reload the browser when theme assets changes.`,
    requiresArg: false
  },
  dist: {
    describe: `Serve the dist folder (${config.DIST_FOLDER}).`,
    requiresArg: false
  }
};
exports.desc = `Serve the compiled deck folder`;
exports.handler = argv => {
  const SERVE_FOLDER = argv.dist ? config.DIST_FOLDER : config.DEV_FOLDER;
  del(SERVE_FOLDER)
    .then(() => {
      const serveDist = Boolean(argv.dist);
      build(bs, argv.dev, SERVE_FOLDER, serveDist, callback);
    })
    .catch(error => {
      logger.error(error);
      shell.exit(1);
    });
};
<commit_msg>Improves code<commit_after>'use strict';
import shell from 'shelljs';
import bs from 'browser-sync';
import config from '../config.js';
import configLoader from './../config-loader';
import Generator from 'confetti-generator';
import Loader from 'confetti-loader';
import watchAll from './../assets-watchers';
import * as logger from './../logger';
import path from 'path';
import del from 'del';
const loader = new Loader();
/*
 Function to load data and to build the slide deck.
 */
const build = (bs, dev, folder, serveDist) => {
  logger.message('Loading speaker deck data...');
  loader.loadDeck(configLoader, serveDist)
    .then(deckData => {
      const generator = new Generator(deckData.paths, serveDist);
      logger.success('Speaker deck data loaded.');
      logger.message('Generating speaker deck...');
      generator.generate(deckData)
        .then(() => {
          if (!bs.active) {
            bs.create();
            bs.init({server: folder, open: false});
            /*
             Watch changes on:
             - slide deck settings
             - data slides
             - selected theme config
             */
            bs.watch([
              configLoader.paths.settings,
              configLoader.paths.slides,
              path.join(configLoader.paths.themes, deckData.theme, 'data.yml')
            ]).on('change', () => {
              // If anything is changed rebuild the deck
              build(bs, dev, folder, serveDist);
            });
            bs.watch(configLoader.paths.covers).on('change',
              () => generator.copyCovers().catch(error => logger.error(error)));
            bs.watch(folder).on('change', bs.reload);
            /*
             Watch the theme assets only if the dev mode is switched on.
             */
            if (dev) {
              logger.info('Theme development environment enabled.');
              watchAll(bs, generator, deckData);
            }
          }
        })
        .catch(error => {
          logger.error(error);
          shell.exit(1);
        });
    })
    .catch(error => {
      logger.error(error);
      shell.exit(1);
    });
};
//--------------
// Serve Command
//--------------
exports.command = 'server';
exports.builder = {
  dev: {
    describe: `Enables watching and reload the browser when theme assets changes.`,
    requiresArg: false
  },
  dist: {
    describe: `Serve the dist folder (${config.DIST_FOLDER}).`,
    requiresArg: false
  }
};
exports.desc = `Serve the compiled deck folder`;
exports.handler = argv => {
  const SERVE_FOLDER = argv.dist ? config.DIST_FOLDER : config.DEV_FOLDER;
  del(SERVE_FOLDER)
    .then(() => {
      const serveDist = Boolean(argv.dist);
      build(bs, argv.dev, SERVE_FOLDER, serveDist);
    })
    .catch(error => {
      logger.error(error);
      shell.exit(1);
    });
};
<|endoftext|>


<commit_before>/**
 *    _____ __
 *   / ___// /_  _____
 *   \__ \/ / / / / _ \
 *  ___/ / / /_/ /  __/
 * /____/_/\__, /\___/
 *       /____/
 *       Copyright 2017 Slye Development Team. All Rights Reserved.
 *       Licence: MIT License
 */
<commit_msg>Test break expression<commit_after>/**
 *    _____ __
 *   / ___// /_  _____
 *   \__ \/ / / / / _ \
 *  ___/ / / /_/ /  __/
 * /____/_/\__, /\___/
 *       /____/
 *       Copyright 2017 Slye Development Team. All Rights Reserved.
 *       Licence: MIT License
 */

const {compile, safeEval}   = require('../tools');

module.exports.$break = function (assert) {
	var code    = `
re = 0;
a:
for(var i = 1; i < 5;i++){
	for(var j = 0;j < 10;j++){
		re += i*j;
		if(j == 7){
			break a;
		}
	}
}
re
	`;
	try {
		var esy = compile(code);
		assert(safeEval(esy) == safeEval(code));
	}catch (e){
		assert(false);
	}
};

module.exports.$break1 = function (assert) {
	var code    = `
re = 0;
a:
for(var i = 1; i < 5;i++){
	for(var j = 0;j < 10;j++){
		re += i*j;
		if(j == 7){
			break
			a;
		}
	}
}
re
	`;
	try {
		var esy = compile(code);
		assert(safeEval(esy) == safeEval(code));
	}catch (e){
		assert(false);
	}
};<|endoftext|>


<commit_before>const moment = require('moment');

/**
 * returns the first and last day of a given date
 *
 * @param date
 * @returns {{start: Date, end: Date}}
 */
function calculateFirstLastDayOfMonth(date) {
    var date = new Date(date);
    const year = date.getFullYear();
    const month = date.getMonth();
    const firstDay = moment(new Date(year, month, 1));
    firstDay.subtract(parseInt(firstDay.format('E')) - 1, 'day');

    const lastDay = moment(new Date(year, month + 1, 0));
    lastDay.add(7 - parseInt(lastDay.format('E')), 'day');

    return { start: firstDay.toDate(), end: lastDay.toDate() };
}

function getHolidaysForDateRange(dateRange) {
    const holidays = {};
    const start = moment(dateRange.start);
    const end = moment(dateRange.end);
    do {
        const yearHolidays = getHolidaysForYear(start.year());

        for (let date in yearHolidays) {
            const holidayDate = moment(date, 'YYYY-MM-DD');
            const holiday = yearHolidays[date];
            if (holidayDate.isBefore(start)) continue;
            if (holidayDate.isAfter(end)) continue;
            holidays[date] = holiday;
        }

        start.add(1, 'year');
    } while (start.isBefore(end, 'year'));

    return holidays;
}

function getHolidaysForYear(year) {
    const holidays = {};
    holidays[`${year}-01-01`] = 'Neujahr';
    holidays[`${year}-01-06`] = 'Hl. Drei Könige';
    holidays[calculateEasterSondayPlusXDate(year, 1)] = 'Ostermontag';
    holidays[`${year}-05-01`] = 'Staatsfeiertag';
    holidays[calculateEasterSondayPlusXDate(year, 39)] = 'Christi Himmelfahrt';
    holidays[calculateEasterSondayPlusXDate(year, 50)] = 'Pfingstmontag';
    holidays[calculateEasterSondayPlusXDate(year, 60)] = 'Fronleichnam';
    holidays[`${year}-08-15`] = 'Mariä Himmelfahrt';
    holidays[`${year}-10-26`] = 'Nationalfeiertag';
    holidays[`${year}-11-01`] = 'Allerheiligen';
    holidays[`${year}-12-08`] = 'Mariä Empfängnis';
    holidays[`${year}-12-24`] = 'Heiliger Abend';
    holidays[`${year}-12-25`] = 'Christtag';
    holidays[`${year}-12-26`] = 'Stefanitag';
    holidays[`${year}-12-31`] = 'Silvester';
    return holidays;
}

/*
 Berechnung Ostersonntag laut Wikipedia

 a = Jahr mod 19
 b = Jahr mod 4
 c = Jahr mod 7
 k = Jahr div 100
 p = (8k + 13) div 25
 q = k div 4
 M = (15 + k − p − q) mod 30
 d = (19a + M) mod 30
 N = (4 + k − q) mod 7
 e = (2b + 4c + 6d + N) mod 7
 Ostern = (22 + d + e)ter März
 (Der 32. März ist der 1. April usf.)
 */

function calculateEasterSondayPlusXDate(year, addDays) {
    addDays = addDays || 0;

    const a = year % 19;
    const b = year % 4;
    const c = year % 7;
    const k = Math.floor(year / 100);

    const p = Math.floor((8 * k + 13) / 25);
    const q = Math.floor(k / 4);
    const M = (15 + k - p - q) % 30;
    const d = (19 * a + M) % 30;
    const N = (4 + k - q) % 7;
    const e = (2 * b + 4 * c + 6 * d + N) % 7;

    let month = 3;
    let day = 22 + d + e;

    // add Days for "x days after Easter"-Holidays
    day += addDays;

    // Theoretical TODO: Fix for 29-day Februaries (not really needed for current holiday calculations)
    const daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

    while (day > daysInMonth[month - 1]) {
        day -= daysInMonth[month - 1];
        month++;
        if (month > 12) month = 1;
    }

    return `${year}-${padout(month)}-${padout(day)}`;
}

function padout(number) {
    return (number < 10) ? `0${number}` : number;
}

// use timeUtils:getDayDuration DUPLICATES!!
function getDayDuration(duration) {
    const week = duration.asMinutes();
    return moment.duration(Math.round(week / 5), 'minutes');
}
function getHalfDayDuration(duration) {
    const week = duration.asMinutes();
    return moment.duration(Math.round(week / 10), 'minutes');
}

exports.calculateFirstLastDayOfMonth = calculateFirstLastDayOfMonth;
exports.getHolidaysForDateRange = getHolidaysForDateRange;

exports.getDayDuration = getDayDuration;
exports.getHalfDayDuration = getHalfDayDuration;
<commit_msg>fix lint error messages<commit_after>const moment = require('moment');

function getHolidaysForDateRange(dateRange) {
    const holidays = {};
    const start = moment(dateRange.start);
    const end = moment(dateRange.end);
    do {
        const yearHolidays = getHolidaysForYear(start.year());

        for (const date in yearHolidays) {
            if (yearHolidays.hasOwnProperty(date)) {
                const holidayDate = moment(date, 'YYYY-MM-DD');
                const holiday = yearHolidays[date];
                if (holidayDate.isBefore(start)) continue;
                if (holidayDate.isAfter(end)) continue;
                holidays[date] = holiday;
            }
        }

        start.add(1, 'year');
    } while (start.isBefore(end, 'year'));

    return holidays;
}

function getHolidaysForYear(year) {
    const holidays = {};
    holidays[`${year}-01-01`] = 'Neujahr';
    holidays[`${year}-01-06`] = 'Hl. Drei Könige';
    holidays[calculateEasterSondayPlusXDate(year, 1)] = 'Ostermontag';
    holidays[`${year}-05-01`] = 'Staatsfeiertag';
    holidays[calculateEasterSondayPlusXDate(year, 39)] = 'Christi Himmelfahrt';
    holidays[calculateEasterSondayPlusXDate(year, 50)] = 'Pfingstmontag';
    holidays[calculateEasterSondayPlusXDate(year, 60)] = 'Fronleichnam';
    holidays[`${year}-08-15`] = 'Mariä Himmelfahrt';
    holidays[`${year}-10-26`] = 'Nationalfeiertag';
    holidays[`${year}-11-01`] = 'Allerheiligen';
    holidays[`${year}-12-08`] = 'Mariä Empfängnis';
    holidays[`${year}-12-24`] = 'Heiliger Abend';
    holidays[`${year}-12-25`] = 'Christtag';
    holidays[`${year}-12-26`] = 'Stefanitag';
    holidays[`${year}-12-31`] = 'Silvester';
    return holidays;
}

/*
 Berechnung Ostersonntag laut Wikipedia

 a = Jahr mod 19
 b = Jahr mod 4
 c = Jahr mod 7
 k = Jahr div 100
 p = (8k + 13) div 25
 q = k div 4
 M = (15 + k − p − q) mod 30
 d = (19a + M) mod 30
 N = (4 + k − q) mod 7
 e = (2b + 4c + 6d + N) mod 7
 Ostern = (22 + d + e)ter März
 (Der 32. März ist der 1. April usf.)
 */

function calculateEasterSondayPlusXDate(year, addDays = 0) {
    const a = year % 19;
    const b = year % 4;
    const c = year % 7;
    const k = Math.floor(year / 100);

    const p = Math.floor((8 * k + 13) / 25);
    const q = Math.floor(k / 4);
    const M = (15 + k - p - q) % 30;
    const d = (19 * a + M) % 30;
    const N = (4 + k - q) % 7;
    const e = (2 * b + 4 * c + 6 * d + N) % 7;

    let month = 3;
    let day = 22 + d + e;

    // add Days for "x days after Easter"-Holidays
    day += addDays;

    // Theoretical TODO: Fix for 29-day Februaries (not really needed for current holiday calculations)
    const daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

    while (day > daysInMonth[month - 1]) {
        day -= daysInMonth[month - 1];
        month++;
        if (month > 12) month = 1;
    }

    return `${year}-${padout(month)}-${padout(day)}`;
}

function padout(number) {
    return (number < 10) ? `0${number}` : number;
}

// use timeUtils:getDayDuration DUPLICATES!!
function getDayDuration(duration) {
    const week = duration.asMinutes();
    return moment.duration(Math.round(week / 5), 'minutes');
}
function getHalfDayDuration(duration) {
    const week = duration.asMinutes();
    return moment.duration(Math.round(week / 10), 'minutes');
}

exports.getHolidaysForDateRange = getHolidaysForDateRange;

exports.getDayDuration = getDayDuration;
exports.getHalfDayDuration = getHalfDayDuration;
<|endoftext|>


<commit_before>"use strict";

( function() {

walContext.Composition = function( wCtx ) {
	this.wCtx = wCtx;
	this.wSamples = [];
	this.lastSample = null;
	this.isPlaying =
	this.isPaused = false;
	this.duration =
	this.startedTime =
	this._currentTime = 0;
	this.fnOnended =
	this.fnOnpaused = function() {};
};

function updateLastSample( compo ) {
	var end, last = null, maxend = 0;
	compo.wSamples.forEach( function( ws ) {
		end = ws.getEndTime();
		if ( end > maxend ) {
			maxend = end;
			last = ws;
		}
	} );
	compo.lastSample = last;
	compo.duration = last ? last.getEndTime() : 0;
}

function updateTimeout( compo ) {
	clearTimeout( compo.playTimeoutId );
	updateLastSample( compo ); // <-- this line is here just for fix a pb in GS...
	var sec = compo.duration && compo.duration - compo.currentTime();
	if ( sec <= 0 ) {
		compo.onended();
	} else {
		compo.playTimeoutId = setTimeout( compo.onended.bind( compo ), sec * 1000 );
	}
}

function startSampleFrom( ws, currentTime ) {
	var start = ws.when - currentTime;
	ws.start( start,
		start > 0 ? ws.offset : ws.offset - start,
		start > 0 ? ws.duration : ws.duration + start
	);
}

function updateInLive( compo, ws, action, oldLast ) {
	var ct = compo.currentTime();
	if ( ws.getEndTime() > ct && action !== "rm" ) {
		ws.load();
		startSampleFrom( ws, ct );
	}
	if ( compo.lastSample !== oldLast || action === "mv" ) {
		updateTimeout( compo );
	}
}

function softStop( compo ) {
	clearTimeout( compo.playTimeoutId );
	compo.wSamples.forEach( function( ws ) {
		ws.stop();
	} );
}

function softLoad( compo ) {
	var ct = compo.currentTime();
	compo.wSamples.forEach( function( ws ) {
		if ( ws.getEndTime() > ct ) {
			ws.load();
		}
	} );
}

function softPlay( compo ) {
	var ct = compo.currentTime();
	compo.wSamples.forEach( function( ws ) {
		if ( ws.getEndTime() > ct ) {
			startSampleFrom( ws, ct );
		}
	} );
	updateTimeout( compo );
}

walContext.Composition.prototype = {
	add: function( waSample ) {
		if ( waSample.forEach ) {
			waSample.forEach( add, this );
		} else {
			add.call( this, waSample );
		}
		return this;
	},
	remove: function( waSample ) {
		if ( waSample.forEach ) {
			waSample.forEach( remove, this );
		} else {
			remove.call( this, waSample );
		}
		return this;
	},
	update: function( ws, action ) {
		var that = this,
			oldLast = this.lastSample,
			save;

		updateLastSample( this );
		if ( this.isPlaying ) {
			if ( ws.started ) {
				save = ws.fnOnended;
				ws.onended( function() {
					updateInLive( that, ws, action, oldLast );
					save();
					ws.onended( save );
				} );
				ws.stop();
			} else {
				updateInLive( this, ws, action, oldLast );
			}
		}
		return this;
	},
	currentTime: function( sec ) {
		if ( !arguments.length ) {
			return this._currentTime +
				( this.isPlaying && this.wCtx.ctx.currentTime - this.startedTime );
		}
		if ( this.isPlaying ) {
			softStop( this );
		}
		this._currentTime = Math.max( 0, Math.min( sec, this.duration ) );
		if ( this.isPlaying ) {
			this.startedTime = this.wCtx.ctx.currentTime;
			softLoad( this );
			softPlay( this );
		}
		return this;
	},
	play: function() {
		if ( !this.isPlaying ) {
			this.isPlaying = true;
			this.isPaused = false;
			this.startedTime = this.wCtx.ctx.currentTime;
			softLoad( this );
			softPlay( this );
		}
		return this;
	},
	stop: function() {
		if ( this.isPlaying || this.isPaused ) {
			softStop( this );
			this.onended();
		}
		return this;
	},
	pause: function() {
		if ( this.isPlaying ) {
			this.isPlaying = false;
			this.isPaused = true;
			this._currentTime += this.wCtx.ctx.currentTime - this.startedTime;
			this.startedTime = 0;
			softStop( this );
			this.fnOnpaused();
		}
	},
	onended: function( fn ) {
		if ( typeof fn === "function" ) {
			this.fnOnended = fn;
		} else {
			this.isPlaying =
			this.isPaused = false;
			this.startedTime =
			this._currentTime = 0;
			this.fnOnended();
		}
		return this;
	}
};

function add( smp ) {
	if ( this.wSamples.indexOf( smp ) < 0 ) {
		this.wSamples.push( smp );
		smp.composition = this;
		this.update( smp );
	}
}

function remove( smp ) {
	var ind = this.wSamples.indexOf( smp );

	if ( ind > -1 ) {
		smp.composition = null;
		this.wSamples.splice( ind, 1 );
		this.update( smp, "rm" );
	}
}

} )();
<commit_msg>composition : coding style<commit_after>"use strict";

( function() {

walContext.Composition = function( wCtx ) {
	this.wCtx = wCtx;
	this.wSamples = [];
	this.lastSample = null;
	this.isPlaying =
	this.isPaused = false;
	this.duration =
	this._startedTime =
	this._currentTime = 0;
	this.fnOnended =
	this.fnOnpaused = function() {};
};

walContext.Composition.prototype = {
	add: function( smp ) {
		if ( smp.forEach ) {
			smp.forEach( add, this );
		} else {
			add.call( this, smp );
		}
		return this;
	},
	remove: function( smp ) {
		if ( smp.forEach ) {
			smp.forEach( remove, this );
		} else {
			remove.call( this, smp );
		}
		return this;
	},
	update: function( smp, action ) {
		var save,
			that = this,
			oldLast = this.lastSample;

		updateLastSample( this );
		if ( this.isPlaying ) {
			if ( smp.started ) {
				save = smp.fnOnended;
				smp.onended( function() {
					updateInLive( that, smp, action, oldLast );
					save();
					smp.onended( save );
				} );
				smp.stop();
			} else {
				updateInLive( this, smp, action, oldLast );
			}
		}
		return this;
	},
	currentTime: function( sec ) {
		if ( !arguments.length ) {
			return this._currentTime +
				( this.isPlaying && this.wCtx.ctx.currentTime - this._startedTime );
		}
		if ( this.isPlaying ) {
			stop( this );
		}
		this._currentTime = Math.max( 0, Math.min( sec, this.duration ) );
		if ( this.isPlaying ) {
			this._startedTime = this.wCtx.ctx.currentTime;
			load( this );
			play( this );
		}
		return this;
	},
	play: function() {
		if ( !this.isPlaying ) {
			this.isPlaying = true;
			this.isPaused = false;
			this._startedTime = this.wCtx.ctx.currentTime;
			load( this );
			play( this );
		}
		return this;
	},
	stop: function() {
		if ( this.isPlaying || this.isPaused ) {
			stop( this );
			this.onended();
		}
		return this;
	},
	pause: function() {
		if ( this.isPlaying ) {
			this.isPlaying = false;
			this.isPaused = true;
			this._currentTime += this.wCtx.ctx.currentTime - this._startedTime;
			this._startedTime = 0;
			stop( this );
			this.fnOnpaused();
		}
		return this;
	},
	onended: function( fn ) {
		if ( typeof fn === "function" ) {
			this.fnOnended = fn;
		} else {
			this.isPlaying =
			this.isPaused = false;
			this._startedTime =
			this._currentTime = 0;
			this.fnOnended();
		}
		return this;
	}
};

function add( smp ) {
	if ( this.wSamples.indexOf( smp ) < 0 ) {
		this.wSamples.push( smp );
		smp.composition = this;
		this.update( smp );
	}
}

function remove( smp ) {
	var ind = this.wSamples.indexOf( smp );

	if ( ind > -1 ) {
		smp.composition = null;
		this.wSamples.splice( ind, 1 );
		this.update( smp, "rm" );
	}
}

function stop( cmp ) {
	clearTimeout( cmp.playTimeoutId );
	cmp.wSamples.forEach( function( smp ) {
		smp.stop();
	} );
}

function load( cmp ) {
	var ct = cmp.currentTime();

	cmp.wSamples.forEach( function( smp ) {
		if ( smp.getEndTime() > ct ) {
			smp.load();
		}
	} );
}

function play( cmp ) {
	var ct = cmp.currentTime();

	cmp.wSamples.forEach( function( smp ) {
		if ( smp.getEndTime() > ct ) {
			startSampleFrom( smp, ct );
		}
	} );
	updateTimeout( cmp );
}

function updateLastSample( cmp ) {
	var end, last = null, maxend = 0;

	cmp.wSamples.forEach( function( ws ) {
		end = ws.getEndTime();
		if ( end > maxend ) {
			maxend = end;
			last = ws;
		}
	} );
	cmp.lastSample = last;
	cmp.duration = last ? last.getEndTime() : 0;
}

function updateTimeout( cmp ) {
	clearTimeout( cmp.playTimeoutId );
	updateLastSample( cmp ); // <-- this line is here just for fix a pb in GS...
	var sec = cmp.duration && cmp.duration - cmp.currentTime();
	if ( sec <= 0 ) {
		cmp.onended();
	} else {
		cmp.playTimeoutId = setTimeout( cmp.onended.bind( cmp ), sec * 1000 );
	}
}

function startSampleFrom( smp, currentTime ) {
	var start = smp.when - currentTime;

	smp.start( start,
		start > 0 ? smp.offset : smp.offset - start,
		start > 0 ? smp.duration : smp.duration + start
	);
}

function updateInLive( cmp, smp, action, oldLast ) {
	var ct = cmp.currentTime();
	if ( smp.getEndTime() > ct && action !== "rm" ) {
		smp.load();
		startSampleFrom( smp, ct );
	}
	if ( cmp.lastSample !== oldLast || action === "mv" ) {
		updateTimeout( cmp );
	}
}

} )();
<|endoftext|>


<commit_before>var snoozedTabs;
var settings;
var bg = chrome.extension.getBackgroundPage();

$(document).ready(function() {
    console.log("Welcome to options.js");

    init();

    function init() {
        console.log("options.js is initializing...");
        snoozedTabs = bg.getSnoozedTabs();
        console.log("snoozedTabs from localStorage", snoozedTabs);
        settings = bg.getSettings();
        console.log("settings from localStorage", settings);

        // Set button click-handlers
        $(".nav-button").click(function(){
            var button = $(this);
            var buttonID = button.attr("id");
            var sectionName = buttonID.slice(0, -7);
            setSection("#" + sectionName);
        });

        setupSnoozedTabs();
        setupSettings();
        setupAbout();

        var startSection = window.location.hash;
        if(!startSection) {
            startSection = "#snoozed-tabs";
        }

        setSection(startSection);

        // Listen to changes to localStorage and update views
        $(window).bind("storage", function() {
            snoozedTabs = bg.getSnoozedTabs();
            settings = bg.getSettings();
            listSnoozedTabs();
            renderSettings();
        });
    }
});

function setupSnoozedTabs() {
    // List snoozed tabs
    listSnoozedTabs();

    // Set Clear-All and Export Button
    if(snoozedTabs["tabCount"] == 0) {
        $("#clear-all").prop('disabled', true);
        $("#export-tabs").prop('disabled', true);
    } else {
        $("#clear-all").click(function() {
            clearAll();
        });

        $("#export-tabs").click(function() {
            exportTabs();
        });
    }
}

function setupSettings() {
    $("#reset-settings").click(function() {
        resetSettings();
    });

    $('#start-day-timepicker').timepicker({
        template: false,
        showInputs: false,
        minuteStep: 30,
        defaultTime: settings["start-day"]
    });

    $('#end-day-timepicker').timepicker({
        template: false,
        showInputs: false,
        minuteStep: 30,
        defaultTime: settings["end-day"]
    });

    $('#start-weekend-timepicker').timepicker({
        template: false,
        showInputs: false,
        minuteStep: 30,
        defaultTime: settings["start-weekend"]
    });

    renderSettings();

    $(".bootstrap-timepicker input").on("changeTime.timepicker", function(e) {
        var id = $(this).attr("id");
        var setting = id.substring(0, id.length - 11);
        var time = e.time.value;

        console.log("" + setting + " = " + time);
        settings[setting] = time;
        bg.setSettings(settings);
        console.log("settings", bg.getSettings());
    });

    $("select.control").change(function(e){
        var setting = $(this).attr("id");
        var value = parseInt($(this).val());
        console.log("Setting " + setting + " to " + value);

        settings[setting] = value;
        bg.setSettings(settings);

        console.log("settings", bg.getSettings());
    });

    $("input[name='badge']").change(function(){
        var badgeVal = $(this).val();
        console.log("Setting badge to " + badgeVal);

        settings["badge"] = badgeVal;
        bg.setSettings(settings);

        console.log("settings", settings);
        bg.updateBadgeText();
    });
}

function renderSettings() {
    $("#start-day-timepicker").timepicker("setTime", settings["start-day"]);
    $("#end-day-timepicker").timepicker("setTime", settings["end-day"]);
    $("#start-weekend-timepicker").timepicker("setTime", settings["start-weekend"]);

    $("#week-begin").val(settings["week-begin"]);
    $("#weekend-begin").val(settings["weekend-begin"]);
    $("#later-today").val(settings["later-today"]);
    $("#someday").val(settings["someday"]);

    $("input[name='badge']").val([settings["badge"]]);
    bg.updateBadgeText();
}

function setupAbout() {

}

function setSection(sectionID) {
    var button = $(sectionID + "-button");
    var buttonListItem = button.parent();
    var section = $(sectionID);

    // Set button
    $("#navigation li").removeClass("selected");
    buttonListItem.addClass("selected");

    // Set section
    $(".options-section").hide();
    section.fadeIn();

    // Set page hash
    window.location.hash = sectionID;
}

function listSnoozedTabs() {
    $("#days-list").empty();

    if(snoozedTabs["tabCount"] == 0) {
        $(".no-tabs").fadeIn();
        return;
    } else {
        $(".no-tabs").hide();
    }

    var alarmTimes = Object.keys(snoozedTabs).sort();
    console.log("alarmTimes", alarmTimes);

    for(var i = 0; i < alarmTimes.length - 1; i++) {
        var alarmTime = alarmTimes[i];
        var alarmSet = snoozedTabs[alarmTime];

        var day = (new Date(parseInt(alarmTime)));
        day.setHours(0, 0, 0, 0);

        var dayHeading = $("#day-" + day.getTime());
        if(dayHeading.length == 0) {
            listDay(day);
        }

        for(var j = 0; j < alarmSet.length; j++) {
            var tab = alarmSet[j];
            listTab(tab, day);
        }
    }
}

function listDay(day) {
    var dayLi = $(document.createElement('li'));

    var dayHeading = $(document.createElement('h3'));
    dayHeading.addClass("day-heading");
    dayHeading.text(formatDay(day));

    var dayTabsList = $(document.createElement('ol'));
    dayTabsList.attr("id", "day-" + day.getTime());
    dayTabsList.addClass("day-tabs-list");

    dayLi.append([dayHeading, dayTabsList]);

    $("#days-list").append(dayLi);
}

function listTab(tab, day) {
    console.log("tab", tab);

    var ol = $("#day-" + day.getTime());

    var entry = $(document.createElement('li'))
    entry.addClass("entry");
    entry.attr("url", tab.url);
    entry.attr("creationTime", tab.creationTime);

    var time = $(document.createElement('time'));
    time.addClass("entry-time");
    time.text(formatTime(tab.alarmTime));

    var favicon = $(document.createElement('span'));
    favicon.addClass("entry-favicon");
    if(tab.favicon) {
        favicon.css("background-image", "url(\"" + tab.favicon +"\")");
    }

    var title = $(document.createElement('a'));
    title.addClass("entry-title");
    title.attr("href", tab.url);
    title.text(tab.title);

    var domain = $(document.createElement('span'));
    domain.addClass("entry-domain");
    var location = document.createElement('a');
    location.href = tab.url;
    domain.text(location.hostname);

    var clear = $(document.createElement('button'));
    clear.addClass("entry-clear custom-appearance");
    clear.attr("title", "Clear Tab");

    clear.click(function(tab, entry) {
        return function() {
            clearEntry(tab, entry);
        }
    }(tab, entry));

    entry.append([time, favicon, title, domain, clear]);

    ol.append(entry);
}

function formatDay(day) {
    var result = "";

    var tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 1);
    tomorrow.setHours(0, 0, 0, 0);
    if(day.getTime() == tomorrow.getTime()) {
        result += "Tomorrow — ";
    }

    var today = new Date();
    today.setHours(0, 0, 0, 0);
    if(day.getTime() == today.getTime()) {
        result += "Today — ";
    }

    var yesterday = new Date();
    yesterday.setDate(yesterday.getDate() - 1);
    yesterday.setHours(0, 0, 0, 0);
    if(day.getTime() == yesterday.getTime()) {
        result += "Yesterday — ";
    }

    var weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday",
                    "Thursday", "Friday", "Saturday"];
    var months = ["January", "February", "March", "April", "May",
                "June", "July", "August", "September", "October",
                "November", "December"];

    var weekday = weekdays[day.getDay()];
    var month = months[day.getMonth()];

    result += weekday + ", " + month + " " + day.getDate() + ", " + day.getFullYear();
    return result;
}

function formatTime(alarmTime) {
    var time = new Date(alarmTime);
    console.log(time);

    var hours = time.getHours() % 12;
    var minutes = time.getMinutes();
    if(minutes < 10) {
        minutes = "0" + minutes;
    }

    var ampm = (time.getHours() < 12) ? "AM" : "PM";

    return ("" + hours + ":" + minutes + " " + ampm);
}

function clearAll() {
    var tabCount = snoozedTabs["tabCount"];
    if(tabCount <= 0) {
        return;
    }

    var confirmText = "Are you sure you want to clear ";
    if(tabCount == 1) {
        confirmText += "1 tab?";
    } else {
        confirmText += "all " + tabCount + " tabs?";
    }
    var canClear = confirm(confirmText);
    if(canClear) {
        snoozedTabs = {};
        snoozedTabs["tabCount"] = 0;
        bg.setSnoozedTabs(snoozedTabs);
        bg.updateBadgeText();

        $("#days-list li").fadeOut(function() {
            $(this).remove();
        });

        $("#clear-all").prop('disabled', true);
    }
}

function clearEntry(tab, entry) {
    console.log("About to clear tab", tab);

    bg.removeSnoozedTab(tab, snoozedTabs);
    bg.setSnoozedTabs(snoozedTabs);
    bg.updateBadgeText();

    var dayList = entry.parent();
    var dayLi = dayList.parent();

    console.log(dayList);
    console.log(dayList.children().length);

    if(dayList.children().length == 1) {
        dayLi.fadeOut(function() {
            $(this).remove();
        });
    } else {
        entry.fadeOut(function() {
            $(this).slideUp(function() {
                $(this).remove();
            });
        });
    }

    if(snoozedTabs["tabCount"] == 0) {
        $("#clear-all").prop('disabled', true);
    }
}

function resetSettings() {
    var canReset = confirm("Are you sure you want to reset all settings?");
    if(!canReset) {
        return;
    }

    settings = JSON.parse(localStorage.getItem("defaultSettings"));
    bg.setSettings(settings);

    console.log("rendering");
    renderSettings();
}

function exportTabs() {
    window.URL = window.URL || window.webkitURL;

    var now = new Date();
    dateString = "" + now.getFullYear() + now.getMonth() + now.getDate() + "-" + now.getHours() + now.getMinutes();

    var exportObject = {
        exportTime: now.getTime(),
        settings: settings,
        snoozedTabs: snoozedTabs
    }

    var blob = new Blob([JSON.stringify(exportObject, undefined, 2)], {type: 'text/plain'});
    var blobURL = window.URL.createObjectURL(blob);

    chrome.downloads.download({
        url: blobURL,
        filename: "tabsnooze-" + dateString + ".json",
        saveAs: true
    });
}

function errorHandler(e) {
    console.log("errorHandler called!", e);
}<commit_msg>Disable export button when 0 tabs<commit_after>var snoozedTabs;
var settings;
var bg = chrome.extension.getBackgroundPage();

$(document).ready(function() {
    console.log("Welcome to options.js");

    init();

    function init() {
        console.log("options.js is initializing...");
        snoozedTabs = bg.getSnoozedTabs();
        console.log("snoozedTabs from localStorage", snoozedTabs);
        settings = bg.getSettings();
        console.log("settings from localStorage", settings);

        // Set button click-handlers
        $(".nav-button").click(function(){
            var button = $(this);
            var buttonID = button.attr("id");
            var sectionName = buttonID.slice(0, -7);
            setSection("#" + sectionName);
        });

        setupSnoozedTabs();
        setupSettings();
        setupAbout();

        var startSection = window.location.hash;
        if(!startSection) {
            startSection = "#snoozed-tabs";
        }

        setSection(startSection);

        // Listen to changes to localStorage and update views
        $(window).bind("storage", function() {
            snoozedTabs = bg.getSnoozedTabs();
            settings = bg.getSettings();
            listSnoozedTabs();
            renderSettings();
        });
    }
});

function setupSnoozedTabs() {
    // List snoozed tabs
    listSnoozedTabs();

    // Set Clear-All and Export Button
    if(snoozedTabs["tabCount"] == 0) {
        $("#clear-all").prop('disabled', true);
        $("#export-tabs").prop('disabled', true);
    } else {
        $("#clear-all").click(function() {
            clearAll();
        });

        $("#export-tabs").click(function() {
            exportTabs();
        });
    }
}

function setupSettings() {
    $("#reset-settings").click(function() {
        resetSettings();
    });

    $('#start-day-timepicker').timepicker({
        template: false,
        showInputs: false,
        minuteStep: 30,
        defaultTime: settings["start-day"]
    });

    $('#end-day-timepicker').timepicker({
        template: false,
        showInputs: false,
        minuteStep: 30,
        defaultTime: settings["end-day"]
    });

    $('#start-weekend-timepicker').timepicker({
        template: false,
        showInputs: false,
        minuteStep: 30,
        defaultTime: settings["start-weekend"]
    });

    renderSettings();

    $(".bootstrap-timepicker input").on("changeTime.timepicker", function(e) {
        var id = $(this).attr("id");
        var setting = id.substring(0, id.length - 11);
        var time = e.time.value;

        console.log("" + setting + " = " + time);
        settings[setting] = time;
        bg.setSettings(settings);
        console.log("settings", bg.getSettings());
    });

    $("select.control").change(function(e){
        var setting = $(this).attr("id");
        var value = parseInt($(this).val());
        console.log("Setting " + setting + " to " + value);

        settings[setting] = value;
        bg.setSettings(settings);

        console.log("settings", bg.getSettings());
    });

    $("input[name='badge']").change(function(){
        var badgeVal = $(this).val();
        console.log("Setting badge to " + badgeVal);

        settings["badge"] = badgeVal;
        bg.setSettings(settings);

        console.log("settings", settings);
        bg.updateBadgeText();
    });
}

function renderSettings() {
    $("#start-day-timepicker").timepicker("setTime", settings["start-day"]);
    $("#end-day-timepicker").timepicker("setTime", settings["end-day"]);
    $("#start-weekend-timepicker").timepicker("setTime", settings["start-weekend"]);

    $("#week-begin").val(settings["week-begin"]);
    $("#weekend-begin").val(settings["weekend-begin"]);
    $("#later-today").val(settings["later-today"]);
    $("#someday").val(settings["someday"]);

    $("input[name='badge']").val([settings["badge"]]);
    bg.updateBadgeText();
}

function setupAbout() {

}

function setSection(sectionID) {
    var button = $(sectionID + "-button");
    var buttonListItem = button.parent();
    var section = $(sectionID);

    // Set button
    $("#navigation li").removeClass("selected");
    buttonListItem.addClass("selected");

    // Set section
    $(".options-section").hide();
    section.fadeIn();

    // Set page hash
    window.location.hash = sectionID;
}

function listSnoozedTabs() {
    $("#days-list").empty();

    if(snoozedTabs["tabCount"] == 0) {
        $(".no-tabs").fadeIn();
        return;
    } else {
        $(".no-tabs").hide();
    }

    var alarmTimes = Object.keys(snoozedTabs).sort();
    console.log("alarmTimes", alarmTimes);

    for(var i = 0; i < alarmTimes.length - 1; i++) {
        var alarmTime = alarmTimes[i];
        var alarmSet = snoozedTabs[alarmTime];

        var day = (new Date(parseInt(alarmTime)));
        day.setHours(0, 0, 0, 0);

        var dayHeading = $("#day-" + day.getTime());
        if(dayHeading.length == 0) {
            listDay(day);
        }

        for(var j = 0; j < alarmSet.length; j++) {
            var tab = alarmSet[j];
            listTab(tab, day);
        }
    }
}

function listDay(day) {
    var dayLi = $(document.createElement('li'));

    var dayHeading = $(document.createElement('h3'));
    dayHeading.addClass("day-heading");
    dayHeading.text(formatDay(day));

    var dayTabsList = $(document.createElement('ol'));
    dayTabsList.attr("id", "day-" + day.getTime());
    dayTabsList.addClass("day-tabs-list");

    dayLi.append([dayHeading, dayTabsList]);

    $("#days-list").append(dayLi);
}

function listTab(tab, day) {
    console.log("tab", tab);

    var ol = $("#day-" + day.getTime());

    var entry = $(document.createElement('li'))
    entry.addClass("entry");
    entry.attr("url", tab.url);
    entry.attr("creationTime", tab.creationTime);

    var time = $(document.createElement('time'));
    time.addClass("entry-time");
    time.text(formatTime(tab.alarmTime));

    var favicon = $(document.createElement('span'));
    favicon.addClass("entry-favicon");
    if(tab.favicon) {
        favicon.css("background-image", "url(\"" + tab.favicon +"\")");
    }

    var title = $(document.createElement('a'));
    title.addClass("entry-title");
    title.attr("href", tab.url);
    title.text(tab.title);

    var domain = $(document.createElement('span'));
    domain.addClass("entry-domain");
    var location = document.createElement('a');
    location.href = tab.url;
    domain.text(location.hostname);

    var clear = $(document.createElement('button'));
    clear.addClass("entry-clear custom-appearance");
    clear.attr("title", "Clear Tab");

    clear.click(function(tab, entry) {
        return function() {
            clearEntry(tab, entry);
        }
    }(tab, entry));

    entry.append([time, favicon, title, domain, clear]);

    ol.append(entry);
}

function formatDay(day) {
    var result = "";

    var tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 1);
    tomorrow.setHours(0, 0, 0, 0);
    if(day.getTime() == tomorrow.getTime()) {
        result += "Tomorrow — ";
    }

    var today = new Date();
    today.setHours(0, 0, 0, 0);
    if(day.getTime() == today.getTime()) {
        result += "Today — ";
    }

    var yesterday = new Date();
    yesterday.setDate(yesterday.getDate() - 1);
    yesterday.setHours(0, 0, 0, 0);
    if(day.getTime() == yesterday.getTime()) {
        result += "Yesterday — ";
    }

    var weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday",
                    "Thursday", "Friday", "Saturday"];
    var months = ["January", "February", "March", "April", "May",
                "June", "July", "August", "September", "October",
                "November", "December"];

    var weekday = weekdays[day.getDay()];
    var month = months[day.getMonth()];

    result += weekday + ", " + month + " " + day.getDate() + ", " + day.getFullYear();
    return result;
}

function formatTime(alarmTime) {
    var time = new Date(alarmTime);
    console.log(time);

    var hours = time.getHours() % 12;
    var minutes = time.getMinutes();
    if(minutes < 10) {
        minutes = "0" + minutes;
    }

    var ampm = (time.getHours() < 12) ? "AM" : "PM";

    return ("" + hours + ":" + minutes + " " + ampm);
}

function clearAll() {
    var tabCount = snoozedTabs["tabCount"];
    if(tabCount <= 0) {
        return;
    }

    var confirmText = "Are you sure you want to clear ";
    if(tabCount == 1) {
        confirmText += "1 tab?";
    } else {
        confirmText += "all " + tabCount + " tabs?";
    }
    var canClear = confirm(confirmText);
    if(canClear) {
        snoozedTabs = {};
        snoozedTabs["tabCount"] = 0;
        bg.setSnoozedTabs(snoozedTabs);
        bg.updateBadgeText();

        $("#days-list li").fadeOut(function() {
            $(this).remove();
        });

        $("#clear-all").prop('disabled', true);
        $("#export-tabs").prop('disabled', true);
    }
}

function clearEntry(tab, entry) {
    console.log("About to clear tab", tab);

    bg.removeSnoozedTab(tab, snoozedTabs);
    bg.setSnoozedTabs(snoozedTabs);
    bg.updateBadgeText();

    var dayList = entry.parent();
    var dayLi = dayList.parent();

    console.log(dayList);
    console.log(dayList.children().length);

    if(dayList.children().length == 1) {
        dayLi.fadeOut(function() {
            $(this).remove();
        });
    } else {
        entry.fadeOut(function() {
            $(this).slideUp(function() {
                $(this).remove();
            });
        });
    }

    if(snoozedTabs["tabCount"] == 0) {
        $("#clear-all").prop('disabled', true);
        $("#export-tabs").prop('disabled', true);
    }
}

function resetSettings() {
    var canReset = confirm("Are you sure you want to reset all settings?");
    if(!canReset) {
        return;
    }

    settings = JSON.parse(localStorage.getItem("defaultSettings"));
    bg.setSettings(settings);

    console.log("rendering");
    renderSettings();
}

function exportTabs() {
    window.URL = window.URL || window.webkitURL;

    var now = new Date();
    dateString = "" + now.getFullYear() + now.getMonth() + now.getDate() + "-" + now.getHours() + now.getMinutes();

    var exportObject = {
        exportTime: now.getTime(),
        settings: settings,
        snoozedTabs: snoozedTabs
    }

    var blob = new Blob([JSON.stringify(exportObject, undefined, 2)], {type: 'text/plain'});
    var blobURL = window.URL.createObjectURL(blob);

    chrome.downloads.download({
        url: blobURL,
        filename: "tabsnooze-" + dateString + ".json",
        saveAs: true
    });
}

function errorHandler(e) {
    console.log("errorHandler called!", e);
}<|endoftext|>


<commit_before>//machineLearning refers to the machine_learning library from "npm install machine_learning;"
function convertData_machineLearning_to_d3(machineLearningDataType, machineLearningData){
  if(machineLearningDataType!='tree'){
    if(arguments.length>=2) //TEMPORARY SHORTCUT (meant to be without curly brackets)
    return {};
  }
  else{//TEMPORARY SHORTCUT
    machineLearningData = arguments[0];
  }

  //machineLearningData has {data:Array, result:Array, tree:Object}
  var machineLearningData_tree = machineLearningData.tree?  machineLearningData.tree: machineLearningData;
  //Future: check if col,value,results,tb,fb exist

  var d3_decisionTree_tree = {};
  transformAttributes("START", machineLearningData_tree, d3_decisionTree_tree);
  return d3_decisionTree_tree;
}

function transformAttributes(nodeName, src_machineLearningTreeData, dst_d3TreeData){
  // console.log(nodeName, src_machineLearningTreeData, dst_d3TreeData);
  dst_d3TreeData.name = dst_d3TreeData.name ||nodeName;
  if(src_machineLearningTreeData['tb'] || src_machineLearningTreeData['fb']){
    dst_d3TreeData.children = dst_d3TreeData.children ||[]; //define .children as an array if there is no .children defined yet --> need to check and avoid overwrites because this function is likely called twice for each level due to recursion
  }

  var src_mlTreeData_branchNames = [];
  // ['tb','fb'].forEach(function(branchName){
  //   if(src_machineLearningTreeData[branchName]){
  //     src_mlTreeData_branchNames.push(branchName);
  //   }
  // });
  src_machineLearningTreeData['tb']?  src_mlTreeData_branchNames.push('tb'): '';
  src_machineLearningTreeData['fb']?  src_mlTreeData_branchNames.push('fb'): '';

  src_mlTreeData_branchNames.forEach(function(branchName){
    var d3Data_childNode = {};
    dst_d3TreeData.children.push(d3Data_childNode);

    var childNodeName = (branchName=='tb'?  '': "NOT ")+src_machineLearningTreeData.value  +" [col"+src_machineLearningTreeData.col+"]";
    transformAttributes(childNodeName, src_machineLearningTreeData[branchName], d3Data_childNode);
  });
}

<commit_msg>if case<commit_after>//machineLearning refers to the machine_learning library from "npm install machine_learning;"
function convertData_machineLearning_to_d3(machineLearningDataType, machineLearningData){
  if(machineLearningDataType!='tree'){
    if(arguments.length>=2) //TEMPORARY SHORTCUT (meant to be without curly brackets)
      return {};
    //else //TEMPORARY SHORTCUT
    machineLearningData = arguments[0];
  }

  //machineLearningData has {data:Array, result:Array, tree:Object}
  console.log(machineLearningData)
  var machineLearningData_tree = machineLearningData.tree?  machineLearningData.tree: machineLearningData;
  //Future: check if col,value,results,tb,fb exist

  var d3_decisionTree_tree = {};
  transformAttributes("START", machineLearningData_tree, d3_decisionTree_tree);
  return d3_decisionTree_tree;
}

function transformAttributes(nodeName, src_machineLearningTreeData, dst_d3TreeData){
  // console.log(nodeName, src_machineLearningTreeData, dst_d3TreeData);
  dst_d3TreeData.name = dst_d3TreeData.name ||nodeName;
  if(src_machineLearningTreeData['tb'] || src_machineLearningTreeData['fb']){
    dst_d3TreeData.children = dst_d3TreeData.children ||[]; //define .children as an array if there is no .children defined yet --> need to check and avoid overwrites because this function is likely called twice for each level due to recursion
  }

  var src_mlTreeData_branchNames = [];
  // ['tb','fb'].forEach(function(branchName){
  //   if(src_machineLearningTreeData[branchName]){
  //     src_mlTreeData_branchNames.push(branchName);
  //   }
  // });
  src_machineLearningTreeData['tb']?  src_mlTreeData_branchNames.push('tb'): '';
  src_machineLearningTreeData['fb']?  src_mlTreeData_branchNames.push('fb'): '';

  src_mlTreeData_branchNames.forEach(function(branchName){
    var d3Data_childNode = {};
    dst_d3TreeData.children.push(d3Data_childNode);

    var childNodeName = (branchName=='tb'?  '': "NOT ")+src_machineLearningTreeData.value  +" [col"+src_machineLearningTreeData.col+"]";
    transformAttributes(childNodeName, src_machineLearningTreeData[branchName], d3Data_childNode);
  });
}

<|endoftext|>


<commit_before>/**
* The `Matter.Plugin` module contains functions for registering and installing plugins on modules.
*
* @class Plugin
*/

var Plugin = {};

module.exports = Plugin;

var Common = require('./Common');

(function() {

    Plugin._registry = {};

    /**
     * Registers a plugin object so it can be resolved later by name.
     * @method register
     * @param plugin {} The plugin to register.
     * @return {object} The plugin.
     */
    Plugin.register = function(plugin) {
        if (!Plugin.isPlugin(plugin)) {
            Common.warn('Plugin.register:', Plugin.toString(plugin), 'does not implement all required fields.');
        }

        if (plugin.name in Plugin._registry) {
            var registered = Plugin._registry[plugin.name];

            if (Plugin.versionParse(plugin.version).number >= Plugin.versionParse(registered.version).number) {
                Common.warn('Plugin.register:', Plugin.toString(registered), 'was upgraded to', Plugin.toString(plugin));
                Plugin._registry[plugin.name] = plugin;
            } else {
                Common.warn('Plugin.register:', Plugin.toString(registered), 'can not be downgraded to', Plugin.toString(plugin));
            }
        } else {
            Plugin._registry[plugin.name] = plugin;
        }

        return plugin;
    };

    /**
     * Resolves a dependency to a plugin object from the registry if it exists.
     * The `dependency` may contain a version, but only the name matters when resolving.
     * @method resolve
     * @param dependency {string} The dependency.
     * @return {object} The plugin if resolved, otherwise `undefined`.
     */
    Plugin.resolve = function(dependency) {
        return Plugin._registry[Plugin.dependencyParse(dependency).name];
    };

    /**
     * Returns a pretty printed plugin name and version.
     * @method toString
     * @param plugin {} The plugin.
     * @return {string} Pretty printed plugin name and version.
     */
    Plugin.toString = function(plugin) {
        return (plugin.name || 'anonymous') + '@' + (plugin.version || plugin.range || '0.0.0');
    };

    /**
     * Returns `true` if the object meets the minimum standard to be considered a plugin.
     * This means it must define the following properties:
     * - `name`
     * - `version`
     * - `install`
     * @method isPlugin
     * @param obj {} The obj to test.
     * @return {boolean} `true` if the object can be considered a plugin otherwise `false`.
     */
    Plugin.isPlugin = function(obj) {
        return obj && obj.name && obj.version && obj.install;
    };

    /**
     * Returns `true` if a plugin with the given `name` been installed on `module`.
     * @method isUsed
     * @param module {} The module.
     * @param name {string} The plugin name.
     * @return {boolean} `true` if a plugin with the given `name` been installed on `module`, otherwise `false`.
     */
    Plugin.isUsed = function(module, name) {
        return module.used.indexOf(name) > -1;
    };

    /**
     * Returns `true` if `plugin.for` is applicable to `module` by comparing against `module.name` and `module.version`.
     * If `plugin.for` is not specified then it is assumed to be applicable.
     * The value of `plugin.for` is a string of the format `'module-name'` or `'module-name@version'`.
     * @method isFor
     * @param plugin {} The plugin.
     * @param module {} The module.
     * @return {boolean} `true` if `plugin.for` is applicable to `module`, otherwise `false`.
     */
    Plugin.isFor = function(plugin, module) {
        var parsed = plugin.for && Plugin.dependencyParse(plugin.for);
        return !plugin.for || (module.name === parsed.name && Plugin.versionSatisfies(module.version, parsed.range));
    };

    /**
     * Installs the plugins by calling `plugin.install` on each plugin specified in `plugins` if passed, otherwise `module.uses`.
     * For installing plugins on `Matter` see the convenience function `Matter.use`.
     * Plugins may be specified either by their name or a reference to the plugin object.
     * Plugins themselves may specify further dependencies, but each plugin is installed only once.
     * Order is important, a topological sort is performed to find the best resulting order of installation.
     * This sorting attempts to satisfy every dependency's requested ordering, but may not be exact in all cases.
     * This function logs the resulting status of each dependency in the console, along with any warnings.
     * - A green tick ✅ indicates a dependency was resolved and installed.
     * - An orange diamond 🔶 indicates a dependency was resolved but a warning was thrown for it or one if its dependencies.
     * - A red cross ❌ indicates a dependency could not be resolved.
     * Avoid calling this function multiple times on the same module unless you intend to manually control installation order.
     * @method use
     * @param module {} The module install plugins on.
     * @param [plugins=module.uses] {} The plugins to install on module (optional, defaults to `module.uses`).
     */
    Plugin.use = function(module, plugins) {
        module.uses = (module.uses || []).concat(plugins || []);

        if (module.uses.length === 0) {
            Common.warn('Plugin.use:', Plugin.toString(module), 'does not specify any dependencies to install.');
            return;
        }

        var dependencies = Plugin.dependencies(module),
            sortedDependencies = Common.topologicalSort(dependencies),
            status = [];

        for (var i = 0; i < sortedDependencies.length; i += 1) {
            if (sortedDependencies[i] === module.name) {
                continue;
            }

            var plugin = Plugin.resolve(sortedDependencies[i]);

            if (!plugin) {
                status.push('❌ ' + sortedDependencies[i]);
                continue;
            }

            if (Plugin.isUsed(module, plugin.name)) {
                continue;
            }

            if (!Plugin.isFor(plugin, module)) {
                Common.warn('Plugin.use:', Plugin.toString(plugin), 'is for', plugin.for, 'but installed on', Plugin.toString(module) + '.');
                plugin._warned = true;
            }

            if (plugin.install) {
                plugin.install(module);
            } else {
                Common.warn('Plugin.use:', Plugin.toString(plugin), 'does not specify an install function.');
                plugin._warned = true;
            }

            if (plugin._warned) {
                status.push('🔶 ' + Plugin.toString(plugin));
                delete plugin._warned;
            } else {
                status.push('✅ ' + Plugin.toString(plugin));
            }

            module.used.push(plugin.name);
        }

        if (status.length > 0) {
            Common.info(status.join('  '));
        }
    };

    /**
     * Recursively finds all of a module's dependencies and returns a flat dependency graph.
     * @method dependencies
     * @param module {} The module.
     * @return {object} A dependency graph.
     */
    Plugin.dependencies = function(module, tracked) {
        var parsedBase = Plugin.dependencyParse(module),
            name = parsedBase.name;

        tracked = tracked || {};

        if (name in tracked) {
            return;
        }

        module = Plugin.resolve(module) || module;

        tracked[name] = Common.map(module.uses || [], function(dependency) {
            var parsed = Plugin.dependencyParse(dependency),
                resolved = Plugin.resolve(dependency);

            if (resolved && !Plugin.versionSatisfies(resolved.version, parsed.range)) {
                Common.warn(
                    'Plugin.dependencies:', Plugin.toString(resolved), 'does not satisfy',
                    Plugin.toString(parsed), 'used by', Plugin.toString(parsedBase) + '.'
                );

                resolved._warned = true;
                module._warned = true;
            } else if (!resolved) {
                Common.warn(
                    'Plugin.dependencies:', dependency, 'used by',
                    Plugin.toString(parsedBase), 'could not be resolved.'
                );

                module._warned = true;
            }

            return parsed.name;
        });

        for (var i = 0; i < tracked[name].length; i += 1) {
            Plugin.dependencies(tracked[name][i], tracked);
        }

        return tracked;
    };

    /**
     * Parses a dependency string into its components.
     * The `dependency` is a string of the format `'module-name'` or `'module-name@version'`.
     * See documentation for `Plugin.versionParse` for a description of the format.
     * This function can also handle dependencies that are already resolved (e.g. a module object).
     * @method dependencyParse
     * @param dependency {string} The dependency of the format `'module-name'` or `'module-name@version'`.
     * @return {object} The dependency parsed into its components.
     */
    Plugin.dependencyParse = function(dependency) {
        if (Common.isString(dependency)) {
            var pattern = /^[\w-]+(@(\*|[\^~]?\d+\.\d+\.\d+(-[0-9A-Za-z-]+)?))?$/;

            if (!pattern.test(dependency)) {
                Common.warn('Plugin.dependencyParse:', dependency, 'is not a valid dependency string.');
            }

            return {
                name: dependency.split('@')[0],
                range: dependency.split('@')[1] || '*'
            };
        }

        return {
            name: dependency.name,
            range: dependency.range || dependency.version
        };
    };

    /**
     * Parses a version string into its components.
     * Versions are strictly of the format `x.y.z` (as in [semver](http://semver.org/)).
     * Versions may optionally have a prerelease tag in the format `x.y.z-alpha`.
     * Ranges are a strict subset of [npm ranges](https://docs.npmjs.com/misc/semver#advanced-range-syntax).
     * Only the following range types are supported:
     * - Tilde ranges e.g. `~1.2.3`
     * - Caret ranges e.g. `^1.2.3`
     * - Exact version e.g. `1.2.3`
     * - Any version `*`
     * @method versionParse
     * @param range {string} The version string.
     * @return {object} The version range parsed into its components.
     */
    Plugin.versionParse = function(range) {
        var pattern = /^\*|[\^~]?\d+\.\d+\.\d+(-[0-9A-Za-z-]+)?$/;

        if (!pattern.test(range)) {
            Common.warn('Plugin.versionParse:', range, 'is not a valid version or range.');
        }

        var identifiers = range.split('-');
        range = identifiers[0];

        var isRange = isNaN(Number(range[0])),
            version = isRange ? range.substr(1) : range,
            parts = Common.map(version.split('.'), function(part) {
                return Number(part);
            });

        return {
            isRange: isRange,
            version: version,
            range: range,
            operator: isRange ? range[0] : '',
            parts: parts,
            prerelease: identifiers[1],
            number: parts[0] * 1e8 + parts[1] * 1e4 + parts[2]
        };
    };

    /**
     * Returns `true` if `version` satisfies the given `range`.
     * See documentation for `Plugin.versionParse` for a description of the format.
     * If a version or range is not specified, then any version (`*`) is assumed to satisfy.
     * @method versionSatisfies
     * @param version {string} The version string.
     * @param range {string} The range string.
     * @return {boolean} `true` if `version` satisfies `range`, otherwise `false`.
     */
    Plugin.versionSatisfies = function(version, range) {
        range = range || '*';

        var rangeParsed = Plugin.versionParse(range),
            rangeParts = rangeParsed.parts,
            versionParsed = Plugin.versionParse(version),
            versionParts = versionParsed.parts;

        if (rangeParsed.isRange) {
            if (rangeParsed.operator === '*' || version === '*') {
                return true;
            }

            if (rangeParsed.operator === '~') {
                return versionParts[0] === rangeParts[0] && versionParts[1] === rangeParts[1] && versionParts[2] >= rangeParts[2];
            }

            if (rangeParsed.operator === '^') {
                if (rangeParts[0] > 0) {
                    return versionParts[0] === rangeParts[0] && versionParsed.number >= rangeParsed.number;
                }

                if (rangeParts[1] > 0) {
                    return versionParts[1] === rangeParts[1] && versionParts[2] >= rangeParts[2];
                }

                return versionParts[2] === rangeParts[2];
            }
        }

        return version === range || version === '*';
    };

})();
<commit_msg>fixed various Matter.Plugin issues<commit_after>/**
* The `Matter.Plugin` module contains functions for registering and installing plugins on modules.
*
* @class Plugin
*/

var Plugin = {};

module.exports = Plugin;

var Common = require('./Common');

(function() {

    Plugin._registry = {};

    /**
     * Registers a plugin object so it can be resolved later by name.
     * @method register
     * @param plugin {} The plugin to register.
     * @return {object} The plugin.
     */
    Plugin.register = function(plugin) {
        if (!Plugin.isPlugin(plugin)) {
            Common.warn('Plugin.register:', Plugin.toString(plugin), 'does not implement all required fields.');
        }

        if (plugin.name in Plugin._registry) {
            var registered = Plugin._registry[plugin.name],
                pluginVersion = Plugin.versionParse(plugin.version).number,
                registeredVersion = Plugin.versionParse(registered.version).number;

            if (pluginVersion > registeredVersion) {
                Common.warn('Plugin.register:', Plugin.toString(registered), 'was upgraded to', Plugin.toString(plugin));
                Plugin._registry[plugin.name] = plugin;
            } else if (pluginVersion < registeredVersion) {
                Common.warn('Plugin.register:', Plugin.toString(registered), 'can not be downgraded to', Plugin.toString(plugin));
            } else if (plugin !== registered) {
                Common.warn('Plugin.register:', Plugin.toString(plugin), 'is already registered to different plugin object');
            }
        } else {
            Plugin._registry[plugin.name] = plugin;
        }

        return plugin;
    };

    /**
     * Resolves a dependency to a plugin object from the registry if it exists.
     * The `dependency` may contain a version, but only the name matters when resolving.
     * @method resolve
     * @param dependency {string} The dependency.
     * @return {object} The plugin if resolved, otherwise `undefined`.
     */
    Plugin.resolve = function(dependency) {
        return Plugin._registry[Plugin.dependencyParse(dependency).name];
    };

    /**
     * Returns a pretty printed plugin name and version.
     * @method toString
     * @param plugin {} The plugin.
     * @return {string} Pretty printed plugin name and version.
     */
    Plugin.toString = function(plugin) {
        return typeof plugin === 'string' ? plugin : (plugin.name || 'anonymous') + '@' + (plugin.version || plugin.range || '0.0.0');
    };

    /**
     * Returns `true` if the object meets the minimum standard to be considered a plugin.
     * This means it must define the following properties:
     * - `name`
     * - `version`
     * - `install`
     * @method isPlugin
     * @param obj {} The obj to test.
     * @return {boolean} `true` if the object can be considered a plugin otherwise `false`.
     */
    Plugin.isPlugin = function(obj) {
        return obj && obj.name && obj.version && obj.install;
    };

    /**
     * Returns `true` if a plugin with the given `name` been installed on `module`.
     * @method isUsed
     * @param module {} The module.
     * @param name {string} The plugin name.
     * @return {boolean} `true` if a plugin with the given `name` been installed on `module`, otherwise `false`.
     */
    Plugin.isUsed = function(module, name) {
        return module.used.indexOf(name) > -1;
    };

    /**
     * Returns `true` if `plugin.for` is applicable to `module` by comparing against `module.name` and `module.version`.
     * If `plugin.for` is not specified then it is assumed to be applicable.
     * The value of `plugin.for` is a string of the format `'module-name'` or `'module-name@version'`.
     * @method isFor
     * @param plugin {} The plugin.
     * @param module {} The module.
     * @return {boolean} `true` if `plugin.for` is applicable to `module`, otherwise `false`.
     */
    Plugin.isFor = function(plugin, module) {
        var parsed = plugin.for && Plugin.dependencyParse(plugin.for);
        return !plugin.for || (module.name === parsed.name && Plugin.versionSatisfies(module.version, parsed.range));
    };

    /**
     * Installs the plugins by calling `plugin.install` on each plugin specified in `plugins` if passed, otherwise `module.uses`.
     * For installing plugins on `Matter` see the convenience function `Matter.use`.
     * Plugins may be specified either by their name or a reference to the plugin object.
     * Plugins themselves may specify further dependencies, but each plugin is installed only once.
     * Order is important, a topological sort is performed to find the best resulting order of installation.
     * This sorting attempts to satisfy every dependency's requested ordering, but may not be exact in all cases.
     * This function logs the resulting status of each dependency in the console, along with any warnings.
     * - A green tick ✅ indicates a dependency was resolved and installed.
     * - An orange diamond 🔶 indicates a dependency was resolved but a warning was thrown for it or one if its dependencies.
     * - A red cross ❌ indicates a dependency could not be resolved.
     * Avoid calling this function multiple times on the same module unless you intend to manually control installation order.
     * @method use
     * @param module {} The module install plugins on.
     * @param [plugins=module.uses] {} The plugins to install on module (optional, defaults to `module.uses`).
     */
    Plugin.use = function(module, plugins) {
        module.uses = (module.uses || []).concat(plugins || []);

        if (module.uses.length === 0) {
            Common.warn('Plugin.use:', Plugin.toString(module), 'does not specify any dependencies to install.');
            return;
        }

        var dependencies = Plugin.dependencies(module),
            sortedDependencies = Common.topologicalSort(dependencies),
            status = [];

        for (var i = 0; i < sortedDependencies.length; i += 1) {
            if (sortedDependencies[i] === module.name) {
                continue;
            }

            var plugin = Plugin.resolve(sortedDependencies[i]);

            if (!plugin) {
                status.push('❌ ' + sortedDependencies[i]);
                continue;
            }

            if (Plugin.isUsed(module, plugin.name)) {
                continue;
            }

            if (!Plugin.isFor(plugin, module)) {
                Common.warn('Plugin.use:', Plugin.toString(plugin), 'is for', plugin.for, 'but installed on', Plugin.toString(module) + '.');
                plugin._warned = true;
            }

            if (plugin.install) {
                plugin.install(module);
            } else {
                Common.warn('Plugin.use:', Plugin.toString(plugin), 'does not specify an install function.');
                plugin._warned = true;
            }

            if (plugin._warned) {
                status.push('🔶 ' + Plugin.toString(plugin));
                delete plugin._warned;
            } else {
                status.push('✅ ' + Plugin.toString(plugin));
            }

            module.used.push(plugin.name);
        }

        if (status.length > 0) {
            Common.info(status.join('  '));
        }
    };

    /**
     * Recursively finds all of a module's dependencies and returns a flat dependency graph.
     * @method dependencies
     * @param module {} The module.
     * @return {object} A dependency graph.
     */
    Plugin.dependencies = function(module, tracked) {
        var parsedBase = Plugin.dependencyParse(module),
            name = parsedBase.name;

        tracked = tracked || {};

        if (name in tracked) {
            return;
        }

        module = Plugin.resolve(module) || module;

        tracked[name] = Common.map(module.uses || [], function(dependency) {
            if (Plugin.isPlugin(dependency)) {
                Plugin.register(dependency);
            }

            var parsed = Plugin.dependencyParse(dependency),
                resolved = Plugin.resolve(dependency);

            if (resolved && !Plugin.versionSatisfies(resolved.version, parsed.range)) {
                Common.warn(
                    'Plugin.dependencies:', Plugin.toString(resolved), 'does not satisfy',
                    Plugin.toString(parsed), 'used by', Plugin.toString(parsedBase) + '.'
                );

                resolved._warned = true;
                module._warned = true;
            } else if (!resolved) {
                Common.warn(
                    'Plugin.dependencies:', Plugin.toString(dependency), 'used by',
                    Plugin.toString(parsedBase), 'could not be resolved.'
                );

                module._warned = true;
            }

            return parsed.name;
        });

        for (var i = 0; i < tracked[name].length; i += 1) {
            Plugin.dependencies(tracked[name][i], tracked);
        }

        return tracked;
    };

    /**
     * Parses a dependency string into its components.
     * The `dependency` is a string of the format `'module-name'` or `'module-name@version'`.
     * See documentation for `Plugin.versionParse` for a description of the format.
     * This function can also handle dependencies that are already resolved (e.g. a module object).
     * @method dependencyParse
     * @param dependency {string} The dependency of the format `'module-name'` or `'module-name@version'`.
     * @return {object} The dependency parsed into its components.
     */
    Plugin.dependencyParse = function(dependency) {
        if (Common.isString(dependency)) {
            var pattern = /^[\w-]+(@(\*|[\^~]?\d+\.\d+\.\d+(-[0-9A-Za-z-]+)?))?$/;

            if (!pattern.test(dependency)) {
                Common.warn('Plugin.dependencyParse:', dependency, 'is not a valid dependency string.');
            }

            return {
                name: dependency.split('@')[0],
                range: dependency.split('@')[1] || '*'
            };
        }

        return {
            name: dependency.name,
            range: dependency.range || dependency.version
        };
    };

    /**
     * Parses a version string into its components.
     * Versions are strictly of the format `x.y.z` (as in [semver](http://semver.org/)).
     * Versions may optionally have a prerelease tag in the format `x.y.z-alpha`.
     * Ranges are a strict subset of [npm ranges](https://docs.npmjs.com/misc/semver#advanced-range-syntax).
     * Only the following range types are supported:
     * - Tilde ranges e.g. `~1.2.3`
     * - Caret ranges e.g. `^1.2.3`
     * - Exact version e.g. `1.2.3`
     * - Any version `*`
     * @method versionParse
     * @param range {string} The version string.
     * @return {object} The version range parsed into its components.
     */
    Plugin.versionParse = function(range) {
        var pattern = /^\*|[\^~]?\d+\.\d+\.\d+(-[0-9A-Za-z-]+)?$/;

        if (!pattern.test(range)) {
            Common.warn('Plugin.versionParse:', range, 'is not a valid version or range.');
        }

        var identifiers = range.split('-');
        range = identifiers[0];

        var isRange = isNaN(Number(range[0])),
            version = isRange ? range.substr(1) : range,
            parts = Common.map(version.split('.'), function(part) {
                return Number(part);
            });

        return {
            isRange: isRange,
            version: version,
            range: range,
            operator: isRange ? range[0] : '',
            parts: parts,
            prerelease: identifiers[1],
            number: parts[0] * 1e8 + parts[1] * 1e4 + parts[2]
        };
    };

    /**
     * Returns `true` if `version` satisfies the given `range`.
     * See documentation for `Plugin.versionParse` for a description of the format.
     * If a version or range is not specified, then any version (`*`) is assumed to satisfy.
     * @method versionSatisfies
     * @param version {string} The version string.
     * @param range {string} The range string.
     * @return {boolean} `true` if `version` satisfies `range`, otherwise `false`.
     */
    Plugin.versionSatisfies = function(version, range) {
        range = range || '*';

        var rangeParsed = Plugin.versionParse(range),
            rangeParts = rangeParsed.parts,
            versionParsed = Plugin.versionParse(version),
            versionParts = versionParsed.parts;

        if (rangeParsed.isRange) {
            if (rangeParsed.operator === '*' || version === '*') {
                return true;
            }

            if (rangeParsed.operator === '~') {
                return versionParts[0] === rangeParts[0] && versionParts[1] === rangeParts[1] && versionParts[2] >= rangeParts[2];
            }

            if (rangeParsed.operator === '^') {
                if (rangeParts[0] > 0) {
                    return versionParts[0] === rangeParts[0] && versionParsed.number >= rangeParsed.number;
                }

                if (rangeParts[1] > 0) {
                    return versionParts[1] === rangeParts[1] && versionParts[2] >= rangeParts[2];
                }

                return versionParts[2] === rangeParts[2];
            }
        }

        return version === range || version === '*';
    };

})();
<|endoftext|>