<commit_before>
/*
---
script: InPlaceEditor.js
license: MIT-style license.
description: inplace editor.
copyright: Copyright (c) 2010 Thierry Bela
authors: [Thierry Bela]

requires:
  core:1.3.1
  more:1.3.1
provides: [InPlaceEditor]
...
*/

var InPlaceEditor = new Class({

		options: {

			//property: html/text
			property: 'text',
			element: 'textarea',
			toColor: "#e1ecf5",
			fColor: "#fff",
			newLine: true,
			//function that take user input as parameter and return true or false to indicate whether the input is valid
			validate: function (value) { return !!value.trim() },
			properties: {

				rows: 2,
				cols: 32
			}
		},

		Implements: [Events, Options],
		initialize: function() {

			var params = Array.link(arguments, {options: Type.isObject, elements: function(obj) { return (obj != null) } });

			this.setOptions(params.options);

			this.events = this.getEvents();

			if(params.elements) this.attach(params.elements)
		},

		getEvents: function () {

			var self = this,
				options = this.options,
				property = 'backgroundColor';

			return {
						mouseenter: function() { this.tween(property, options.toColor) },
						mouseleave: function() { this.tween(property, options.fColor).get('tween').chain(function () { this.setStyle(property, this.retrieve('eip-color')) }.bind(this)) },
						click: function(e) {

							e.stop();
							self.build(this)
						}
					}

		},
		build: function (el) {

			var options = this.options,
				oldValue = el.get(options.property),
				container = new Element('span').injectAfter(el),
				textarea = new Element(options.element, options.properties).set('value', oldValue).inject(container);

			el.setStyles({display:'none', backgroundColor: options.fColor});

			//new line
			if(options.newLine) new Element('br').inject(container);

			//cancel
			new Element('a', {

							href: 'javascript:;',
							html: 'Cancel',
							events:{
									click: function() {

									el.style.display = el.retrieve('eip-display');
									container.destroy()
								}
							}

						}).inject(container);

			//seperator
			new Element('span', {html: ' '}).inject(container);

			//save
			new Element('a', {

				href: 'javascript:;', html: 'Save',
				events: {

					click: function() {

						el.style.display = el.retrieve('eip-display');

						//validate input
						if(options.validate(textarea.value) && textarea.value != oldValue) this.fireEvent('change', [el.set(options.property, textarea.value), textarea.value, oldValue]);
						container.destroy()

					}.bind(this)
				}

			}).inject(container);

			return this
		},
		attach: function (elements) {

			$$(elements).each(function (el) {

				el.store('eip-color', el.getStyle('backgroundColor')).
					store('eip-display', el.style.display).
					set({tween: {link: 'chain'}, events: this.events})

				}, this);

			return this
		},
		detach: function (elements) {

			$$(elements).removeEvents(this.events);

			return this
		}
});
<commit_msg>update for the forge<commit_after>
/*
---
script: InPlaceEditor.js
license: MIT-style license.
description: inplace editor.
copyright: Copyright (c) 2010 Thierry Bela
authors: [Thierry Bela]

requires:
  core:1.3.1:*
  more:1.3.1:*

provides: [InPlaceEditor]
...
*/

var InPlaceEditor = new Class({

		options: {

			//property: html/text
			property: 'text',
			element: 'textarea',
			toColor: "#e1ecf5",
			fColor: "#fff",
			newLine: true,
			//function that take user input as parameter and return true or false to indicate whether the input is valid
			validate: function (value) { return !!value.trim() },
			properties: {

				rows: 2,
				cols: 32
			}
		},

		Implements: [Events, Options],
		initialize: function() {

			var params = Array.link(arguments, {options: Type.isObject, elements: function(obj) { return (obj != null) } });

			this.setOptions(params.options);

			this.events = this.getEvents();

			if(params.elements) this.attach(params.elements)
		},

		getEvents: function () {

			var self = this,
				options = this.options,
				property = 'backgroundColor';

			return {
						mouseenter: function() { this.tween(property, options.toColor) },
						mouseleave: function() { this.tween(property, options.fColor).get('tween').chain(function () { this.setStyle(property, this.retrieve('eip-color')) }.bind(this)) },
						click: function(e) {

							e.stop();
							self.build(this)
						}
					}

		},
		build: function (el) {

			var options = this.options,
				oldValue = el.get(options.property),
				container = new Element('span').injectAfter(el),
				textarea = new Element(options.element, options.properties).set('value', oldValue).inject(container);

			el.setStyles({display:'none', backgroundColor: options.fColor});

			//new line
			if(options.newLine) new Element('br').inject(container);

			//cancel
			new Element('a', {

							href: 'javascript:;',
							html: 'Cancel',
							events:{
									click: function() {

									el.style.display = el.retrieve('eip-display');
									container.destroy()
								}
							}

						}).inject(container);

			//seperator
			new Element('span', {html: ' '}).inject(container);

			//save
			new Element('a', {

				href: 'javascript:;', html: 'Save',
				events: {

					click: function() {

						el.style.display = el.retrieve('eip-display');

						//validate input
						if(options.validate(textarea.value) && textarea.value != oldValue) this.fireEvent('change', [el.set(options.property, textarea.value), textarea.value, oldValue]);
						container.destroy()

					}.bind(this)
				}

			}).inject(container);

			return this
		},
		attach: function (elements) {

			$$(elements).each(function (el) {

				el.store('eip-color', el.getStyle('backgroundColor')).
					store('eip-display', el.style.display).
					set({tween: {link: 'chain'}, events: this.events})

				}, this);

			return this
		},
		detach: function (elements) {

			$$(elements).removeEvents(this.events);

			return this
		}
});
<|endoftext|>


<commit_before>/*global defineSuite*/
defineSuite([
             'Core/Clock',
             'Core/ClockStep',
             'Core/ClockRange',
             'Core/JulianDate'
            ], function(
              Clock,
              ClockStep,
              ClockRange,
              JulianDate) {
    "use strict";
    /*global it,expect*/

    it('constructor sets default parameters', function() {
        var clock = new Clock();
        expect(clock.stopTime).toEqual(clock.startTime.addDays(1));
        expect(clock.startTime).toEqual(clock.currentTime.addDays(-0.5));
        expect(clock.clockStep).toEqual(ClockStep.SYSTEM_CLOCK_DEPENDENT);
        expect(clock.clockRange).toEqual(ClockRange.UNBOUNDED);
        expect(clock.multiplier).toEqual(1.0);
    });

    it('constructor sets provided parameters correctly', function() {
        var start = JulianDate.fromTotalDays(12);
        var stop = JulianDate.fromTotalDays(112);
        var currentTime = JulianDate.fromTotalDays(13);
        var step = ClockStep.TICK_DEPENDENT;
        var range = ClockRange.LOOP;
        var multiplier = 1.5;
        var clock = new Clock({
            currentTime : currentTime,
            clockStep : step,
            multiplier : multiplier,
            startTime : start,
            stopTime : stop,
            clockRange : range
        });
        expect(clock.startTime).toEqual(start);
        expect(clock.stopTime).toEqual(stop);
        expect(clock.currentTime).toEqual(currentTime);
        expect(clock.clockStep).toEqual(step);
        expect(clock.clockRange).toEqual(range);
        expect(clock.multiplier).toEqual(multiplier);
    });

    it('constructor works with no currentTime parameter', function() {
        var start = JulianDate.fromTotalDays(12);
        var stop = JulianDate.fromTotalDays(112);
        var currentTime = JulianDate.fromTotalDays(62);
        var step = ClockStep.TICK_DEPENDENT;
        var range = ClockRange.LOOP;
        var multiplier = 1.5;
        var clock = new Clock({
            clockStep : step,
            multiplier : multiplier,
            startTime : start,
            stopTime : stop,
            clockRange : range
        });
        expect(clock.startTime).toEqual(start);
        expect(clock.stopTime).toEqual(stop);
        expect(clock.currentTime).toEqual(currentTime);
        expect(clock.clockStep).toEqual(step);
        expect(clock.clockRange).toEqual(range);
        expect(clock.multiplier).toEqual(multiplier);
    });

    it('constructor works with no startTime parameter', function() {
        var stop = JulianDate.fromTotalDays(112);
        var currentTime = JulianDate.fromTotalDays(13);
        var step = ClockStep.TICK_DEPENDENT;
        var range = ClockRange.LOOP;
        var multiplier = 1.5;
        var clock = new Clock({
            currentTime : currentTime,
            clockStep : step,
            multiplier : multiplier,
            stopTime : stop,
            clockRange : range
        });
        expect(clock.startTime).toEqual(clock.currentTime.addDays(-0.5));
        expect(clock.stopTime).toEqual(stop);
        expect(clock.currentTime).toEqual(currentTime);
        expect(clock.clockStep).toEqual(step);
        expect(clock.clockRange).toEqual(range);
        expect(clock.multiplier).toEqual(multiplier);
    });

    it('constructor works with no start or stop time', function() {
        var start = JulianDate.fromTotalDays(12);
        var stop = JulianDate.fromTotalDays(13);
        var currentTime = JulianDate.fromTotalDays(12.5);
        var step = ClockStep.TICK_DEPENDENT;
        var range = ClockRange.LOOP;
        var multiplier = 1.5;
        var clock = new Clock({
            currentTime : currentTime,
            clockStep : step,
            multiplier : multiplier,
            clockRange : range
        });
        expect(clock.startTime).toEqual(start);
        expect(clock.stopTime).toEqual(stop);
        expect(clock.currentTime).toEqual(currentTime);
        expect(clock.clockStep).toEqual(step);
        expect(clock.clockRange).toEqual(range);
        expect(clock.multiplier).toEqual(multiplier);
    });

    it('constructor works with no start or current time', function() {
        var start = JulianDate.fromTotalDays(12);
        var stop = JulianDate.fromTotalDays(13);
        var currentTime = JulianDate.fromTotalDays(12.5);
        var step = ClockStep.TICK_DEPENDENT;
        var range = ClockRange.LOOP;
        var multiplier = 1.5;
        var clock = new Clock({
            clockStep : step,
            multiplier : multiplier,
            stopTime : stop,
            clockRange : range
        });
        expect(clock.startTime).toEqual(start);
        expect(clock.stopTime).toEqual(stop);
        expect(clock.currentTime).toEqual(currentTime);
        expect(clock.clockStep).toEqual(step);
        expect(clock.clockRange).toEqual(range);
        expect(clock.multiplier).toEqual(multiplier);
    });

    it('constructor works with no current or stop time', function() {
        var start = JulianDate.fromTotalDays(12);
        var stop = JulianDate.fromTotalDays(13);
        var currentTime = JulianDate.fromTotalDays(12.5);
        var step = ClockStep.TICK_DEPENDENT;
        var range = ClockRange.LOOP;
        var multiplier = 1.5;
        var clock = new Clock({
            clockStep : step,
            multiplier : multiplier,
            startTime : start,
            clockRange : range
        });
        expect(clock.startTime).toEqual(start);
        expect(clock.stopTime).toEqual(stop);
        expect(clock.currentTime).toEqual(currentTime);
        expect(clock.clockStep).toEqual(step);
        expect(clock.clockRange).toEqual(range);
        expect(clock.multiplier).toEqual(multiplier);
    });

    it('constructor works with no stopTime parameter', function() {
        var start = JulianDate.fromTotalDays(12);
        var stop = JulianDate.fromTotalDays(13);
        var currentTime = JulianDate.fromTotalDays(12.5);
        var step = ClockStep.TICK_DEPENDENT;
        var range = ClockRange.LOOP;
        var multiplier = 1.5;
        var clock = new Clock({
            currentTime : currentTime,
            clockStep : step,
            multiplier : multiplier,
            startTime : start,
            clockRange : range
        });
        expect(clock.startTime).toEqual(start);
        expect(clock.stopTime).toEqual(stop);
        expect(clock.currentTime).toEqual(currentTime);
        expect(clock.clockStep).toEqual(step);
        expect(clock.clockRange).toEqual(range);
        expect(clock.multiplier).toEqual(multiplier);
    });

    it('Tick dependant clock step works animating forward.', function() {
        var start = JulianDate.fromTotalDays(0);
        var stop = JulianDate.fromTotalDays(1);
        var currentTime = JulianDate.fromTotalDays(0.5);
        var step = ClockStep.TICK_DEPENDENT;
        var range = ClockRange.LOOP;
        var multiplier = 1.5;
        var clock = new Clock({
            currentTime : currentTime,
            clockStep : step,
            multiplier : multiplier,
            startTime : start,
            stopTime : stop,
            clockRange : range
        });
        expect(clock.currentTime).toEqual(currentTime);

        currentTime = currentTime.addSeconds(multiplier);
        expect(currentTime).toEqual(clock.tick());
        expect(clock.currentTime).toEqual(currentTime);

        currentTime = currentTime.addSeconds(multiplier);
        expect(currentTime).toEqual(clock.tick());
        expect(clock.currentTime).toEqual(currentTime);
    });

    it('Tick dependant clock step works animating backwards.', function() {
        var start = JulianDate.fromTotalDays(0);
        var stop = JulianDate.fromTotalDays(1);
        var currentTime = JulianDate.fromTotalDays(0.5);
        var step = ClockStep.TICK_DEPENDENT;
        var range = ClockRange.LOOP;
        var multiplier = -1.5;
        var clock = new Clock({
            currentTime : currentTime,
            clockStep : step,
            multiplier : multiplier,
            startTime : start,
            stopTime : stop,
            clockRange : range
        });
        expect(clock.currentTime).toEqual(currentTime);

        currentTime = currentTime.addSeconds(multiplier);
        expect(currentTime).toEqual(clock.tick());
        expect(clock.currentTime).toEqual(currentTime);

        currentTime = currentTime.addSeconds(multiplier);
        expect(currentTime).toEqual(clock.tick());
        expect(clock.currentTime).toEqual(currentTime);
    });

    it('Tick dependant clock step works unbounded animating forward.', function() {
        var start = JulianDate.fromTotalDays(0);
        var stop = JulianDate.fromTotalDays(1);
        var currentTime = JulianDate.fromTotalDays(1);
        var step = ClockStep.TICK_DEPENDENT;
        var range = ClockRange.UNBOUNDED;
        var multiplier = 1.5;
        var clock = new Clock({
            currentTime : currentTime,
            clockStep : step,
            multiplier : multiplier,
            startTime : start,
            stopTime : stop,
            clockRange : range
        });
        expect(clock.currentTime).toEqual(currentTime);

        currentTime = currentTime.addSeconds(multiplier);
        expect(currentTime).toEqual(clock.tick());
        expect(clock.currentTime).toEqual(currentTime);

        currentTime = currentTime.addSeconds(multiplier);
        expect(currentTime).toEqual(clock.tick());
        expect(clock.currentTime).toEqual(currentTime);
    });

    it('Tick dependant clock step works unbounded animating backwards.', function() {
        var start = JulianDate.fromTotalDays(0);
        var stop = JulianDate.fromTotalDays(1);
        var currentTime = JulianDate.fromTotalDays(0);
        var step = ClockStep.TICK_DEPENDENT;
        var range = ClockRange.UNBOUNDED;
        var multiplier = -1.5;
        var clock = new Clock({
            currentTime : currentTime,
            clockStep : step,
            multiplier : multiplier,
            startTime : start,
            stopTime : stop,
            clockRange : range
        });
        expect(clock.currentTime).toEqual(currentTime);

        currentTime = currentTime.addSeconds(multiplier);
        expect(currentTime).toEqual(clock.tick());
        expect(clock.currentTime).toEqual(currentTime);

        currentTime = currentTime.addSeconds(multiplier);
        expect(currentTime).toEqual(clock.tick());
        expect(clock.currentTime).toEqual(currentTime);
    });

    it('Tick dependant clock loops animating forward.', function() {
        var start = JulianDate.fromTotalDays(0);
        var stop = JulianDate.fromTotalDays(1);
        var currentTime = JulianDate.fromTotalDays(1);
        var step = ClockStep.TICK_DEPENDENT;
        var range = ClockRange.LOOP;
        var multiplier = 1.5;
        var clock = new Clock({
            currentTime : currentTime,
            clockStep : step,
            multiplier : multiplier,
            startTime : start,
            stopTime : stop,
            clockRange : range
        });
        expect(clock.currentTime).toEqual(currentTime);

        currentTime = start.addSeconds(multiplier);
        expect(currentTime).toEqual(clock.tick());
        expect(clock.currentTime).toEqual(currentTime);

        currentTime = currentTime.addSeconds(multiplier);
        expect(currentTime).toEqual(clock.tick());
        expect(clock.currentTime).toEqual(currentTime);
    });

    it('Tick dependant clock step loops animating backwards.', function() {
        var start = JulianDate.fromTotalDays(0);
        var stop = JulianDate.fromTotalDays(1);
        var currentTime = JulianDate.fromTotalDays(0);
        var step = ClockStep.TICK_DEPENDENT;
        var range = ClockRange.LOOP;
        var multiplier = -1.5;
        var clock = new Clock({
            currentTime : currentTime,
            clockStep : step,
            multiplier : multiplier,
            startTime : start,
            stopTime : stop,
            clockRange : range
        });
        expect(clock.currentTime).toEqual(currentTime);

        currentTime = stop.addSeconds(multiplier);
        expect(currentTime).toEqual(clock.tick());
        expect(clock.currentTime).toEqual(currentTime);

        currentTime = currentTime.addSeconds(multiplier);
        expect(currentTime).toEqual(clock.tick());
        expect(clock.currentTime).toEqual(currentTime);
    });

    it('Tick dependant clock step stops at end when animating .', function() {
        var start = JulianDate.fromTotalDays(0);
        var stop = JulianDate.fromTotalDays(1);

        var currentTime = JulianDate.fromTotalDays(1);
        var step = ClockStep.TICK_DEPENDENT;
        var range = ClockRange.CLAMPED;
        var multiplier = 100.0;
        var clock = new Clock({
            currentTime : currentTime,
            clockStep : step,
            multiplier : multiplier,
            startTime : start,
            stopTime : stop,
            clockRange : range
        });

        expect(clock.currentTime).toEqual(currentTime);
        expect(stop).toEqual(clock.tick());
        expect(stop).toEqual(clock.currentTime);
    });

    it('Tick dependant clock step stops at start animating backwards.', function() {
        var start = JulianDate.fromTotalDays(0);
        var stop = JulianDate.fromTotalDays(1);

        var currentTime = JulianDate.fromTotalDays(0);
        var step = ClockStep.TICK_DEPENDENT;
        var range = ClockRange.CLAMPED;
        var multiplier = -100.0;
        var clock = new Clock({
            currentTime : currentTime,
            clockStep : step,
            multiplier : multiplier,
            startTime : start,
            stopTime : stop,
            clockRange : range
        });

        expect(clock.currentTime).toEqual(currentTime);
        expect(start).toEqual(clock.tick());
        expect(start).toEqual(clock.currentTime);
    });

    it('Tick followed by tickReverse gets you back to the same time.', function() {
        var start = JulianDate.fromTotalDays(0);
        var stop = JulianDate.fromTotalDays(1);
        var currentTime = JulianDate.fromTotalDays(0);
        var step = ClockStep.TICK_DEPENDENT;
        var range = ClockRange.UNBOUNDED;
        var multiplier = 1.5;
        var clock = new Clock({
            currentTime : currentTime,
            clockStep : step,
            multiplier : multiplier,
            startTime : start,
            stopTime : stop,
            clockRange : range
        });

        expect(clock.currentTime).toEqual(currentTime);
        currentTime = currentTime.addSeconds(multiplier);
        clock.tick();
        expect(clock.currentTime).toEqual(currentTime);
        clock.reverseTick();
        currentTime = currentTime.addSeconds(-multiplier);
        expect(clock.currentTime).toEqual(currentTime);
    });

    it('Passing parameter to tick ticks that many seconds.', function() {
        var start = JulianDate.fromTotalDays(0);
        var stop = JulianDate.fromTotalDays(1);
        var currentTime = JulianDate.fromTotalDays(0);
        var step = ClockStep.SYSTEM_CLOCK_DEPENDENT;
        var range = ClockRange.UNBOUNDED;
        var multiplier = 10000;
        var clock = new Clock({
            currentTime : currentTime,
            clockStep : step,
            multiplier : multiplier,
            startTime : start,
            stopTime : stop,
            clockRange : range
        });

        expect(clock.currentTime).toEqual(currentTime);
        currentTime = currentTime.addSeconds(5);
        clock.tick(5);
        expect(clock.currentTime).toEqual(currentTime);
        clock.tick(-5);
        currentTime = currentTime.addSeconds(-5);
        expect(clock.currentTime).toEqual(currentTime);
    });

    it('throws if start time is after stop time.', function() {
        var start = JulianDate.fromTotalDays(1);
        var stop = JulianDate.fromTotalDays(0);
        expect(function() {
            return new Clock({
                startTime : start,
                stopTime : stop
            });
        }).toThrow();
    });
});
<commit_msg>Bring clock up to 100% code coverage.<commit_after>/*global defineSuite*/
defineSuite([
             'Core/Clock',
             'Core/ClockStep',
             'Core/ClockRange',
             'Core/JulianDate'
            ], function(
              Clock,
              ClockStep,
              ClockRange,
              JulianDate) {
    "use strict";
    /*global it,expect,waitsFor*/

    it('constructor sets default parameters', function() {
        var clock = new Clock();
        expect(clock.stopTime).toEqual(clock.startTime.addDays(1));
        expect(clock.startTime).toEqual(clock.currentTime.addDays(-0.5));
        expect(clock.clockStep).toEqual(ClockStep.SYSTEM_CLOCK_DEPENDENT);
        expect(clock.clockRange).toEqual(ClockRange.UNBOUNDED);
        expect(clock.multiplier).toEqual(1.0);
    });

    it('constructor sets provided parameters correctly', function() {
        var start = JulianDate.fromTotalDays(12);
        var stop = JulianDate.fromTotalDays(112);
        var currentTime = JulianDate.fromTotalDays(13);
        var step = ClockStep.TICK_DEPENDENT;
        var range = ClockRange.LOOP;
        var multiplier = 1.5;
        var clock = new Clock({
            currentTime : currentTime,
            clockStep : step,
            multiplier : multiplier,
            startTime : start,
            stopTime : stop,
            clockRange : range
        });
        expect(clock.startTime).toEqual(start);
        expect(clock.stopTime).toEqual(stop);
        expect(clock.currentTime).toEqual(currentTime);
        expect(clock.clockStep).toEqual(step);
        expect(clock.clockRange).toEqual(range);
        expect(clock.multiplier).toEqual(multiplier);
    });

    it('constructor works with no currentTime parameter', function() {
        var start = JulianDate.fromTotalDays(12);
        var stop = JulianDate.fromTotalDays(112);
        var currentTime = JulianDate.fromTotalDays(62);
        var step = ClockStep.TICK_DEPENDENT;
        var range = ClockRange.LOOP;
        var multiplier = 1.5;
        var clock = new Clock({
            clockStep : step,
            multiplier : multiplier,
            startTime : start,
            stopTime : stop,
            clockRange : range
        });
        expect(clock.startTime).toEqual(start);
        expect(clock.stopTime).toEqual(stop);
        expect(clock.currentTime).toEqual(currentTime);
        expect(clock.clockStep).toEqual(step);
        expect(clock.clockRange).toEqual(range);
        expect(clock.multiplier).toEqual(multiplier);
    });

    it('constructor works with no startTime parameter', function() {
        var stop = JulianDate.fromTotalDays(112);
        var currentTime = JulianDate.fromTotalDays(13);
        var step = ClockStep.TICK_DEPENDENT;
        var range = ClockRange.LOOP;
        var multiplier = 1.5;
        var clock = new Clock({
            currentTime : currentTime,
            clockStep : step,
            multiplier : multiplier,
            stopTime : stop,
            clockRange : range
        });
        expect(clock.startTime).toEqual(clock.currentTime.addDays(-0.5));
        expect(clock.stopTime).toEqual(stop);
        expect(clock.currentTime).toEqual(currentTime);
        expect(clock.clockStep).toEqual(step);
        expect(clock.clockRange).toEqual(range);
        expect(clock.multiplier).toEqual(multiplier);
    });

    it('constructor works with no start or stop time', function() {
        var start = JulianDate.fromTotalDays(12);
        var stop = JulianDate.fromTotalDays(13);
        var currentTime = JulianDate.fromTotalDays(12.5);
        var step = ClockStep.TICK_DEPENDENT;
        var range = ClockRange.LOOP;
        var multiplier = 1.5;
        var clock = new Clock({
            currentTime : currentTime,
            clockStep : step,
            multiplier : multiplier,
            clockRange : range
        });
        expect(clock.startTime).toEqual(start);
        expect(clock.stopTime).toEqual(stop);
        expect(clock.currentTime).toEqual(currentTime);
        expect(clock.clockStep).toEqual(step);
        expect(clock.clockRange).toEqual(range);
        expect(clock.multiplier).toEqual(multiplier);
    });

    it('constructor works with no start or current time', function() {
        var start = JulianDate.fromTotalDays(12);
        var stop = JulianDate.fromTotalDays(13);
        var currentTime = JulianDate.fromTotalDays(12.5);
        var step = ClockStep.TICK_DEPENDENT;
        var range = ClockRange.LOOP;
        var multiplier = 1.5;
        var clock = new Clock({
            clockStep : step,
            multiplier : multiplier,
            stopTime : stop,
            clockRange : range
        });
        expect(clock.startTime).toEqual(start);
        expect(clock.stopTime).toEqual(stop);
        expect(clock.currentTime).toEqual(currentTime);
        expect(clock.clockStep).toEqual(step);
        expect(clock.clockRange).toEqual(range);
        expect(clock.multiplier).toEqual(multiplier);
    });

    it('constructor works with no current or stop time', function() {
        var start = JulianDate.fromTotalDays(12);
        var stop = JulianDate.fromTotalDays(13);
        var currentTime = JulianDate.fromTotalDays(12.5);
        var step = ClockStep.TICK_DEPENDENT;
        var range = ClockRange.LOOP;
        var multiplier = 1.5;
        var clock = new Clock({
            clockStep : step,
            multiplier : multiplier,
            startTime : start,
            clockRange : range
        });
        expect(clock.startTime).toEqual(start);
        expect(clock.stopTime).toEqual(stop);
        expect(clock.currentTime).toEqual(currentTime);
        expect(clock.clockStep).toEqual(step);
        expect(clock.clockRange).toEqual(range);
        expect(clock.multiplier).toEqual(multiplier);
    });

    it('constructor works with no stopTime parameter', function() {
        var start = JulianDate.fromTotalDays(12);
        var stop = JulianDate.fromTotalDays(13);
        var currentTime = JulianDate.fromTotalDays(12.5);
        var step = ClockStep.TICK_DEPENDENT;
        var range = ClockRange.LOOP;
        var multiplier = 1.5;
        var clock = new Clock({
            currentTime : currentTime,
            clockStep : step,
            multiplier : multiplier,
            startTime : start,
            clockRange : range
        });
        expect(clock.startTime).toEqual(start);
        expect(clock.stopTime).toEqual(stop);
        expect(clock.currentTime).toEqual(currentTime);
        expect(clock.clockStep).toEqual(step);
        expect(clock.clockRange).toEqual(range);
        expect(clock.multiplier).toEqual(multiplier);
    });

    it('Tick dependant clock step works animating forward.', function() {
        var start = JulianDate.fromTotalDays(0);
        var stop = JulianDate.fromTotalDays(1);
        var currentTime = JulianDate.fromTotalDays(0.5);
        var step = ClockStep.TICK_DEPENDENT;
        var range = ClockRange.LOOP;
        var multiplier = 1.5;
        var clock = new Clock({
            currentTime : currentTime,
            clockStep : step,
            multiplier : multiplier,
            startTime : start,
            stopTime : stop,
            clockRange : range
        });
        expect(clock.currentTime).toEqual(currentTime);

        currentTime = currentTime.addSeconds(multiplier);
        expect(currentTime).toEqual(clock.tick());
        expect(clock.currentTime).toEqual(currentTime);

        currentTime = currentTime.addSeconds(multiplier);
        expect(currentTime).toEqual(clock.tick());
        expect(clock.currentTime).toEqual(currentTime);
    });

    it('Tick dependant clock step works animating backwards.', function() {
        var start = JulianDate.fromTotalDays(0);
        var stop = JulianDate.fromTotalDays(1);
        var currentTime = JulianDate.fromTotalDays(0.5);
        var step = ClockStep.TICK_DEPENDENT;
        var range = ClockRange.LOOP;
        var multiplier = -1.5;
        var clock = new Clock({
            currentTime : currentTime,
            clockStep : step,
            multiplier : multiplier,
            startTime : start,
            stopTime : stop,
            clockRange : range
        });
        expect(clock.currentTime).toEqual(currentTime);

        currentTime = currentTime.addSeconds(multiplier);
        expect(currentTime).toEqual(clock.tick());
        expect(clock.currentTime).toEqual(currentTime);

        currentTime = currentTime.addSeconds(multiplier);
        expect(currentTime).toEqual(clock.tick());
        expect(clock.currentTime).toEqual(currentTime);
    });

    it('Tick dependant clock step works unbounded animating forward.', function() {
        var start = JulianDate.fromTotalDays(0);
        var stop = JulianDate.fromTotalDays(1);
        var currentTime = JulianDate.fromTotalDays(1);
        var step = ClockStep.TICK_DEPENDENT;
        var range = ClockRange.UNBOUNDED;
        var multiplier = 1.5;
        var clock = new Clock({
            currentTime : currentTime,
            clockStep : step,
            multiplier : multiplier,
            startTime : start,
            stopTime : stop,
            clockRange : range
        });
        expect(clock.currentTime).toEqual(currentTime);

        currentTime = currentTime.addSeconds(multiplier);
        expect(currentTime).toEqual(clock.tick());
        expect(clock.currentTime).toEqual(currentTime);

        currentTime = currentTime.addSeconds(multiplier);
        expect(currentTime).toEqual(clock.tick());
        expect(clock.currentTime).toEqual(currentTime);
    });

    it('Tick dependant clock step works unbounded animating backwards.', function() {
        var start = JulianDate.fromTotalDays(0);
        var stop = JulianDate.fromTotalDays(1);
        var currentTime = JulianDate.fromTotalDays(0);
        var step = ClockStep.TICK_DEPENDENT;
        var range = ClockRange.UNBOUNDED;
        var multiplier = -1.5;
        var clock = new Clock({
            currentTime : currentTime,
            clockStep : step,
            multiplier : multiplier,
            startTime : start,
            stopTime : stop,
            clockRange : range
        });
        expect(clock.currentTime).toEqual(currentTime);

        currentTime = currentTime.addSeconds(multiplier);
        expect(currentTime).toEqual(clock.tick());
        expect(clock.currentTime).toEqual(currentTime);

        currentTime = currentTime.addSeconds(multiplier);
        expect(currentTime).toEqual(clock.tick());
        expect(clock.currentTime).toEqual(currentTime);
    });

    it('Tick dependant clock loops animating forward.', function() {
        var start = JulianDate.fromTotalDays(0);
        var stop = JulianDate.fromTotalDays(1);
        var currentTime = JulianDate.fromTotalDays(1);
        var step = ClockStep.TICK_DEPENDENT;
        var range = ClockRange.LOOP;
        var multiplier = 1.5;
        var clock = new Clock({
            currentTime : currentTime,
            clockStep : step,
            multiplier : multiplier,
            startTime : start,
            stopTime : stop,
            clockRange : range
        });
        expect(clock.currentTime).toEqual(currentTime);

        currentTime = start.addSeconds(multiplier);
        expect(currentTime).toEqual(clock.tick());
        expect(clock.currentTime).toEqual(currentTime);

        currentTime = currentTime.addSeconds(multiplier);
        expect(currentTime).toEqual(clock.tick());
        expect(clock.currentTime).toEqual(currentTime);
    });

    it('Tick dependant clock step loops animating backwards.', function() {
        var start = JulianDate.fromTotalDays(0);
        var stop = JulianDate.fromTotalDays(1);
        var currentTime = JulianDate.fromTotalDays(0);
        var step = ClockStep.TICK_DEPENDENT;
        var range = ClockRange.LOOP;
        var multiplier = -1.5;
        var clock = new Clock({
            currentTime : currentTime,
            clockStep : step,
            multiplier : multiplier,
            startTime : start,
            stopTime : stop,
            clockRange : range
        });
        expect(clock.currentTime).toEqual(currentTime);

        currentTime = stop.addSeconds(multiplier);
        expect(currentTime).toEqual(clock.tick());
        expect(clock.currentTime).toEqual(currentTime);

        currentTime = currentTime.addSeconds(multiplier);
        expect(currentTime).toEqual(clock.tick());
        expect(clock.currentTime).toEqual(currentTime);
    });

    it('Tick dependant clock step stops at end when animating .', function() {
        var start = JulianDate.fromTotalDays(0);
        var stop = JulianDate.fromTotalDays(1);

        var currentTime = JulianDate.fromTotalDays(1);
        var step = ClockStep.TICK_DEPENDENT;
        var range = ClockRange.CLAMPED;
        var multiplier = 100.0;
        var clock = new Clock({
            currentTime : currentTime,
            clockStep : step,
            multiplier : multiplier,
            startTime : start,
            stopTime : stop,
            clockRange : range
        });

        expect(clock.currentTime).toEqual(currentTime);
        expect(stop).toEqual(clock.tick());
        expect(stop).toEqual(clock.currentTime);
    });

    it('Ticks in real-time.', function() {
        //We can't numerically validate the real-time clock, but we
        //can at least make sure the code executes.
        var clock = new Clock({
            clockStep : ClockStep.SYSTEM_DEPENDENT
        });
        var time1 = clock.tick();

        waitsFor(function() {
            var time2 = clock.tick();
            return time2.greaterThan(time1);
        });
    });

    it('Tick dependant clock step stops at start animating backwards.', function() {
        var start = JulianDate.fromTotalDays(0);
        var stop = JulianDate.fromTotalDays(1);

        var currentTime = JulianDate.fromTotalDays(0);
        var step = ClockStep.TICK_DEPENDENT;
        var range = ClockRange.CLAMPED;
        var multiplier = -100.0;
        var clock = new Clock({
            currentTime : currentTime,
            clockStep : step,
            multiplier : multiplier,
            startTime : start,
            stopTime : stop,
            clockRange : range
        });

        expect(clock.currentTime).toEqual(currentTime);
        expect(start).toEqual(clock.tick());
        expect(start).toEqual(clock.currentTime);
    });

    it('Tick followed by tickReverse gets you back to the same time.', function() {
        var start = JulianDate.fromTotalDays(0);
        var stop = JulianDate.fromTotalDays(1);
        var currentTime = JulianDate.fromTotalDays(0);
        var step = ClockStep.TICK_DEPENDENT;
        var range = ClockRange.UNBOUNDED;
        var multiplier = 1.5;
        var clock = new Clock({
            currentTime : currentTime,
            clockStep : step,
            multiplier : multiplier,
            startTime : start,
            stopTime : stop,
            clockRange : range
        });

        expect(clock.currentTime).toEqual(currentTime);
        currentTime = currentTime.addSeconds(multiplier);
        clock.tick();
        expect(clock.currentTime).toEqual(currentTime);
        clock.reverseTick();
        currentTime = currentTime.addSeconds(-multiplier);
        expect(clock.currentTime).toEqual(currentTime);
    });

    it('Passing parameter to tick ticks that many seconds.', function() {
        var start = JulianDate.fromTotalDays(0);
        var stop = JulianDate.fromTotalDays(1);
        var currentTime = JulianDate.fromTotalDays(0);
        var step = ClockStep.SYSTEM_CLOCK_DEPENDENT;
        var range = ClockRange.UNBOUNDED;
        var multiplier = 10000;
        var clock = new Clock({
            currentTime : currentTime,
            clockStep : step,
            multiplier : multiplier,
            startTime : start,
            stopTime : stop,
            clockRange : range
        });

        expect(clock.currentTime).toEqual(currentTime);
        currentTime = currentTime.addSeconds(5);
        clock.tick(5);
        expect(clock.currentTime).toEqual(currentTime);
        clock.tick(-5);
        currentTime = currentTime.addSeconds(-5);
        expect(clock.currentTime).toEqual(currentTime);
    });

    it('throws if start time is after stop time.', function() {
        var start = JulianDate.fromTotalDays(1);
        var stop = JulianDate.fromTotalDays(0);
        expect(function() {
            return new Clock({
                startTime : start,
                stopTime : stop
            });
        }).toThrow();
    });
});
<|endoftext|>


<commit_before>import 'bundle/jquery.cmf_tree'
import {FancytreeAdapter} from 'bundle/adapter/fancytree'

describe('The cmfTree plugin', function () {

    it('has a constructor called cmfTree', function () {
        expect(jQuery.fn.cmfTree).toBeDefined();
    });

    it('requires a data url to make requests to', function() {
        expect(function () { $('#foo').cmfTree() }).toThrow('cmfTree needs an AJAX URL to lazy load the tree, pass it using the `request.load` option.');
    });

    it('defaults to fancytree if no adapter is given', function () {
        expect($('#foo').cmfTree({
            request: {
                load: function () {
                    return 'api/';
                }
            }
        }) instanceof FancytreeAdapter).toBe(true);
    });

    it('accepts other adapters using the adapter option', function () {
        var CustomAdapter = function () { };
        CustomAdapter.prototype.bindToElement = function () {};

        expect($('#foo').cmfTree({
            request: {
                load: function () {
                    return 'api/';
                }
            },
            adapter: new CustomAdapter()
        }) instanceof CustomAdapter).toBe(true);
    });

    it('binds to the selected element', function () {
        var spyAdapter = {
            bindToElement: function (elem) { }
        };

        spyOn(spyAdapter, 'bindToElement');

        $('#foo').cmfTree({
            adapter: spyAdapter,
            request: {
                load: function () {
                    return 'api/';
                }
            }
        });

        expect(spyAdapter.bindToElement).toHaveBeenCalled();
    });

    it('binds to the configured path output', function () {
        var spyAdapter = {
            bindToElement: function (elem) { },
            bindToInput: function (elem) { }
        };

        spyOn(spyAdapter, 'bindToInput');

        $('#foo').cmfTree({
            adapter: spyAdapter,
            request: {
                load: function () {
                    return 'api/';
                }
            },
            path_output: '#output'
        });

        expect(spyAdapter.bindToInput).toHaveBeenCalledWith(jasmine.objectContaining({selector: '#output'}));
    });

    describe('custom adapters', function () {

        it('have to have a bindToElement function', function () {
            var CustomAdapter = function () { };
            var createCmfTree = function () {
                $('#foo').cmfTree({
                    request: {
                        load: function () {
                            return 'api/';
                        }
                    },
                    adapter: new CustomAdapter()
                })
            };

            expect(createCmfTree).toThrow('cmfTree adapters must have a bindToElement() method to specify the output element of the tree.');

            CustomAdapter.prototype.bindToElement = function () { };

            expect(createCmfTree).not.toThrow('cmfTree adapters must have a bindToElement() method to specify the output element of the tree.');
        });

        it('have to have a bindToInput method when tree is bound to input element', function () {
            var CustomAdapter = function () { };
            CustomAdapter.prototype.bindToElement = function () { };
            var createCmfTree = function () {
                $('#foo').cmfTree({
                    request: {
                        load: function () {
                            return 'api/';
                        }
                    },
                    adapter: new CustomAdapter(),
                    path_output: '#bar'
                })
            };

            expect(createCmfTree).toThrow('The configured cmfTree adapter does not support binding to an input field, implement the bindToInput() method or use another adapter.');

            CustomAdapter.prototype.bindToInput = function () { };

            expect(createCmfTree).not.toThrow('The configured cmfTree adapter does not support binding to an input field, implement the bindToInput() method or use another adapter.');
        });

    });

});
<commit_msg>Temporary disable erroring test<commit_after>import 'bundle/jquery.cmf_tree'
import {FancytreeAdapter} from 'bundle/adapter/fancytree'

describe('The cmfTree plugin', function () {

    it('has a constructor called cmfTree', function () {
        expect(jQuery.fn.cmfTree).toBeDefined();
    });

    it('requires a data url to make requests to', function() {
        expect(function () { $('#foo').cmfTree() }).toThrow('cmfTree needs an AJAX URL to lazy load the tree, pass it using the `request.load` option.');
    });

    it('defaults to fancytree if no adapter is given', function () {
        expect($('#foo').cmfTree({
            request: {
                load: function () {
                    return 'api/';
                }
            }
        }) instanceof FancytreeAdapter).toBe(true);
    });

    it('accepts other adapters using the adapter option', function () {
        var CustomAdapter = function () { };
        CustomAdapter.prototype.bindToElement = function () {};

        expect($('#foo').cmfTree({
            request: {
                load: function () {
                    return 'api/';
                }
            },
            adapter: new CustomAdapter()
        }) instanceof CustomAdapter).toBe(true);
    });

    it('binds to the selected element', function () {
        var spyAdapter = {
            bindToElement: function (elem) { }
        };

        spyOn(spyAdapter, 'bindToElement');

        $('#foo').cmfTree({
            adapter: spyAdapter,
            request: {
                load: function () {
                    return 'api/';
                }
            }
        });

        expect(spyAdapter.bindToElement).toHaveBeenCalled();
    });

    xit('binds to the configured path output', function () {
        var spyAdapter = {
            bindToElement: function (elem) { },
            bindToInput: function (elem) { }
        };

        spyOn(spyAdapter, 'bindToInput');

        $('#foo').cmfTree({
            adapter: spyAdapter,
            request: {
                load: function () {
                    return 'api/';
                }
            },
            path_output: '#output'
        });

        expect(spyAdapter.bindToInput).toHaveBeenCalledWith(jasmine.objectContaining({selector: '#output'}));
    });

    describe('custom adapters', function () {

        it('have to have a bindToElement function', function () {
            var CustomAdapter = function () { };
            var createCmfTree = function () {
                $('#foo').cmfTree({
                    request: {
                        load: function () {
                            return 'api/';
                        }
                    },
                    adapter: new CustomAdapter()
                })
            };

            expect(createCmfTree).toThrow('cmfTree adapters must have a bindToElement() method to specify the output element of the tree.');

            CustomAdapter.prototype.bindToElement = function () { };

            expect(createCmfTree).not.toThrow('cmfTree adapters must have a bindToElement() method to specify the output element of the tree.');
        });

        it('have to have a bindToInput method when tree is bound to input element', function () {
            var CustomAdapter = function () { };
            CustomAdapter.prototype.bindToElement = function () { };
            var createCmfTree = function () {
                $('#foo').cmfTree({
                    request: {
                        load: function () {
                            return 'api/';
                        }
                    },
                    adapter: new CustomAdapter(),
                    path_output: '#bar'
                })
            };

            expect(createCmfTree).toThrow('The configured cmfTree adapter does not support binding to an input field, implement the bindToInput() method or use another adapter.');

            CustomAdapter.prototype.bindToInput = function () { };

            expect(createCmfTree).not.toThrow('The configured cmfTree adapter does not support binding to an input field, implement the bindToInput() method or use another adapter.');
        });

    });

});
<|endoftext|>


<commit_before>define(["Tone/core/Tone"], function(Tone){

	"use strict";

	/**
	 *  @class  Tone.Merge brings two signals into the left and right
	 *          channels of a single stereo channel.
	 *
	 *  @constructor
	 *  @extends {Tone}
	 *  @example
	 * var merge = new Tone.Merge().toMaster();
	 * //routing a sine tone in the left channel
	 * //and noise in the right channel
	 * var osc = new Tone.Oscillator().connect(merge.left);
	 * var noise = new Tone.Noise().connect(merge.right);
	 * //starting our oscillators
	 * noise.start();
	 * osc.start();
	 */
	Tone.Merge = function(){

		Tone.call(this, 2, 0);

		/**
		 *  The left input channel.
		 *  Alias for input[0]
		 *  @type {GainNode}
		 */
		this.left = this.input[0] = this.context.createGain();

		/**
		 *  The right input channel.
		 *  Alias for input[1].
		 *  @type {GainNode}
		 */
		this.right = this.input[1] = this.context.createGain();

		/**
		 *  the merger node for the two channels
		 *  @type {ChannelMergerNode}
		 *  @private
		 */
		this._merger = this.output = this.context.createChannelMerger(2);

		//connections
		this.left.connect(this._merger, 0, 0);
		this.right.connect(this._merger, 0, 1);
	};

	Tone.extend(Tone.Merge);

	/**
	 *  Clean up.
	 *  @returns {Tone.Merge} this
	 */
	Tone.Merge.prototype.dispose = function(){
		Tone.prototype.dispose.call(this);
		this.left.disconnect();
		this.left = null;
		this.right.disconnect();
		this.right = null;
		this._merger.disconnect();
		this._merger = null;
		return this;
	};

	return Tone.Merge;
});
<commit_msg>left and right inputs of merger are explicitly mono<commit_after>define(["Tone/core/Tone"], function(Tone){

	"use strict";

	/**
	 *  @class  Tone.Merge brings two signals into the left and right
	 *          channels of a single stereo channel.
	 *
	 *  @constructor
	 *  @extends {Tone}
	 *  @example
	 * var merge = new Tone.Merge().toMaster();
	 * //routing a sine tone in the left channel
	 * //and noise in the right channel
	 * var osc = new Tone.Oscillator().connect(merge.left);
	 * var noise = new Tone.Noise().connect(merge.right);
	 * //starting our oscillators
	 * noise.start();
	 * osc.start();
	 */
	Tone.Merge = function(){

		Tone.call(this, 2, 0);

		/**
		 *  The left input channel.
		 *  Alias for input[0]
		 *  @type {GainNode}
		 */
		this.left = this.input[0] = this.context.createGain();

		/**
		 *  The right input channel.
		 *  Alias for input[1].
		 *  @type {GainNode}
		 */
		this.right = this.input[1] = this.context.createGain();

		/**
		 *  the merger node for the two channels
		 *  @type {ChannelMergerNode}
		 *  @private
		 */
		this._merger = this.output = this.context.createChannelMerger(2);

		//connections
		this.left.connect(this._merger, 0, 0);
		this.right.connect(this._merger, 0, 1);

		this.left.channelCount = 1;
		this.right.channelCount = 1;
		this.left.channelCountMode = "explicit";
		this.right.channelCountMode = "explicit";
	};

	Tone.extend(Tone.Merge);

	/**
	 *  Clean up.
	 *  @returns {Tone.Merge} this
	 */
	Tone.Merge.prototype.dispose = function(){
		Tone.prototype.dispose.call(this);
		this.left.disconnect();
		this.left = null;
		this.right.disconnect();
		this.right = null;
		this._merger.disconnect();
		this._merger = null;
		return this;
	};

	return Tone.Merge;
});
<|endoftext|>


<commit_before>define(["Tone/core/Tone", "Tone/component/LowpassCombFilter", "Tone/effect/StereoEffect", "Tone/signal/Signal", "Tone/component/Split", "Tone/component/Merge"],
function(Tone){

	"use strict";

	/**
	 *  an array of comb filter delay values from Freeverb implementation
	 *  @static
	 *  @private
	 *  @type {Array}
	 */
	var combFilterTunings = [1557 / 44100, 1617 / 44100, 1491 / 44100, 1422 / 44100, 1277 / 44100, 1356 / 44100, 1188 / 44100, 1116 / 44100];

	/**
	 *  an array of allpass filter frequency values from Freeverb implementation
	 *  @private
	 *  @static
	 *  @type {Array}
	 */
	var allpassFilterFrequencies = [225, 556, 441, 341];

	/**
	 *  @class Reverb based on the Freeverb
	 *
	 *  @extends {Tone.Effect}
	 *  @constructor
	 *  @param {number} [roomSize=0.7] correlated to the decay time.
	 *                                 value between (0,1)
	 *  @param {number} [dampening=0.5] filtering which is applied to the reverb.
	 *                                  value between [0,1]
	 */
	Tone.Freeverb = function(){

		var options = this.optionsObject(arguments, ["roomSize", "dampening"], Tone.Freeverb.defaults);
		Tone.StereoEffect.call(this, options);

		/**
		 *  the roomSize value between (0,1)
		 *  @type {Tone.Signal}
		 */
		this.roomSize = new Tone.Signal(options.roomSize);

		/**
		 *  the amount of dampening
		 *  value between [0,1]
		 *  @type {Tone.Signal}
		 */
		this.dampening = new Tone.Signal(options.dampening);

		/**
		 *  scale the dampening
		 *  @type {Tone.ScaleExp}
		 *  @private
		 */
		this._dampeningScale = new Tone.ScaleExp(100, 8000, 0.5);

		/**
		 *  the comb filters
		 *  @type {Array.<Tone.LowpassCombFilter>}
		 *  @private
		 */
		this._combFilters = [];

		/**
		 *  the allpass filters on the left
		 *  @type {Array.<BiqaudFilterNode>}
		 *  @private
		 */
		this._allpassFiltersL = [];

		/**
		 *  the allpass filters on the right
		 *  @type {Array.<BiqaudFilterNode>}
		 *  @private
		 */
		this._allpassFiltersR = [];

		//make the allpass filters on teh right
		for (var l = 0; l < allpassFilterFrequencies.length; l++){
			var allpassL = this.context.createBiquadFilter();
			allpassL.type = "allpass";
			allpassL.frequency.value = allpassFilterFrequencies[l];
			this._allpassFiltersL.push(allpassL);
		}

		//make the allpass filters on the left
		for (var r = 0; r < allpassFilterFrequencies.length; r++){
			var allpassR = this.context.createBiquadFilter();
			allpassR.type = "allpass";
			allpassR.frequency.value = allpassFilterFrequencies[r];
			this._allpassFiltersR.push(allpassR);
		}

		//make the comb filters
		for (var c = 0; c < combFilterTunings.length; c++){
			var lfpf = new Tone.LowpassCombFilter(combFilterTunings[c]);
			if (c < combFilterTunings.length / 2){
				this.effectSendL.chain(lfpf, this._allpassFiltersL[0]);
			} else {
				this.effectSendR.chain(lfpf, this._allpassFiltersR[0]);
			}
			this.roomSize.connect(lfpf.resonance);
			this._dampeningScale.connect(lfpf.dampening);
			this._combFilters.push(lfpf);
		}

		//chain the allpass filters togetehr
		this.connectSeries.apply(this, this._allpassFiltersL);
		this.connectSeries.apply(this, this._allpassFiltersR);
		this._allpassFiltersL[this._allpassFiltersL.length - 1].connect(this.effectReturnL);
		this._allpassFiltersR[this._allpassFiltersR.length - 1].connect(this.effectReturnR);
		this.dampening.connect(this._dampeningScale);
	};

	Tone.extend(Tone.Freeverb, Tone.StereoEffect);

	/**
	 *  @static
	 *  @type {Object}
	 */
	Tone.Freeverb.defaults = {
		"roomSize" : 0.7,
		"dampening" : 0.5
	};

	/**
	 *  set the room size
	 *  @param {number} roomsize roomsize value between 0-1
	 */
	Tone.Freeverb.prototype.setRoomSize = function(roomsize) {
		this.roomSize.setValue(roomsize);
	};

	/**
	 *  set the dampening
	 *  @param {number} dampening dampening between 0-1
	 */
	Tone.Freeverb.prototype.setDampening = function(dampening) {
		this.dampening.setValue(dampening);
	};

	/**
	 *  set multiple parameters at once with an object
	 *  @param {Object} params the parameters as an object
	 */
	Tone.Freeverb.prototype.set = function(params){
		if (!this.isUndef(params.dampening)) this.setDampening(params.dampening);
		if (!this.isUndef(params.roomSize)) this.setRoomSize(params.roomSize);
		Tone.StereoEffect.prototype.set.call(this, params);
	};

	/**
	 *  clean up
	 */
	Tone.Freeverb.prototype.dispose = function(){
		Tone.StereoEffect.prototype.dispose.call(this);
		for (var al = 0; al < this._allpassFiltersL.length; al++) {
			this._allpassFiltersL[al].disconnect();
			this._allpassFiltersL[al] = null;
		}
		this._allpassFiltersL = null;
		for (var ar = 0; ar < this._allpassFiltersR.length; ar++) {
			this._allpassFiltersR[ar].disconnect();
			this._allpassFiltersR[ar] = null;
		}
		this._allpassFiltersR = null;
		for (var cf = 0; cf < this._combFilters.length; cf++) {
			this._combFilters[cf].dispose();
			this._combFilters[cf] = null;
		}
		this._combFilters = null;
		this.roomSize.dispose();
		this.dampening.dispose();
		this._dampeningScale.dispose();
		this.roomSize = null;
		this.dampening = null;
		this._dampeningScale = null;
	};

	return Tone.Freeverb;
});<commit_msg>Freeverb getter functions<commit_after>define(["Tone/core/Tone", "Tone/component/LowpassCombFilter", "Tone/effect/StereoEffect", "Tone/signal/Signal", "Tone/component/Split", "Tone/component/Merge"],
function(Tone){

	"use strict";

	/**
	 *  an array of comb filter delay values from Freeverb implementation
	 *  @static
	 *  @private
	 *  @type {Array}
	 */
	var combFilterTunings = [1557 / 44100, 1617 / 44100, 1491 / 44100, 1422 / 44100, 1277 / 44100, 1356 / 44100, 1188 / 44100, 1116 / 44100];

	/**
	 *  an array of allpass filter frequency values from Freeverb implementation
	 *  @private
	 *  @static
	 *  @type {Array}
	 */
	var allpassFilterFrequencies = [225, 556, 441, 341];

	/**
	 *  @class Reverb based on the Freeverb
	 *
	 *  @extends {Tone.Effect}
	 *  @constructor
	 *  @param {number} [roomSize=0.7] correlated to the decay time.
	 *                                 value between (0,1)
	 *  @param {number} [dampening=0.5] filtering which is applied to the reverb.
	 *                                  value between [0,1]
	 */
	Tone.Freeverb = function(){

		var options = this.optionsObject(arguments, ["roomSize", "dampening"], Tone.Freeverb.defaults);
		Tone.StereoEffect.call(this, options);

		/**
		 *  the roomSize value between (0,1)
		 *  @type {Tone.Signal}
		 */
		this.roomSize = new Tone.Signal(options.roomSize);

		/**
		 *  the amount of dampening
		 *  value between [0,1]
		 *  @type {Tone.Signal}
		 */
		this.dampening = new Tone.Signal(options.dampening);

		/**
		 *  scale the dampening
		 *  @type {Tone.ScaleExp}
		 *  @private
		 */
		this._dampeningScale = new Tone.ScaleExp(100, 8000, 0.5);

		/**
		 *  the comb filters
		 *  @type {Array.<Tone.LowpassCombFilter>}
		 *  @private
		 */
		this._combFilters = [];

		/**
		 *  the allpass filters on the left
		 *  @type {Array.<BiqaudFilterNode>}
		 *  @private
		 */
		this._allpassFiltersL = [];

		/**
		 *  the allpass filters on the right
		 *  @type {Array.<BiqaudFilterNode>}
		 *  @private
		 */
		this._allpassFiltersR = [];

		//make the allpass filters on teh right
		for (var l = 0; l < allpassFilterFrequencies.length; l++){
			var allpassL = this.context.createBiquadFilter();
			allpassL.type = "allpass";
			allpassL.frequency.value = allpassFilterFrequencies[l];
			this._allpassFiltersL.push(allpassL);
		}

		//make the allpass filters on the left
		for (var r = 0; r < allpassFilterFrequencies.length; r++){
			var allpassR = this.context.createBiquadFilter();
			allpassR.type = "allpass";
			allpassR.frequency.value = allpassFilterFrequencies[r];
			this._allpassFiltersR.push(allpassR);
		}

		//make the comb filters
		for (var c = 0; c < combFilterTunings.length; c++){
			var lfpf = new Tone.LowpassCombFilter(combFilterTunings[c]);
			if (c < combFilterTunings.length / 2){
				this.effectSendL.chain(lfpf, this._allpassFiltersL[0]);
			} else {
				this.effectSendR.chain(lfpf, this._allpassFiltersR[0]);
			}
			this.roomSize.connect(lfpf.resonance);
			this._dampeningScale.connect(lfpf.dampening);
			this._combFilters.push(lfpf);
		}

		//chain the allpass filters togetehr
		this.connectSeries.apply(this, this._allpassFiltersL);
		this.connectSeries.apply(this, this._allpassFiltersR);
		this._allpassFiltersL[this._allpassFiltersL.length - 1].connect(this.effectReturnL);
		this._allpassFiltersR[this._allpassFiltersR.length - 1].connect(this.effectReturnR);
		this.dampening.connect(this._dampeningScale);
	};

	Tone.extend(Tone.Freeverb, Tone.StereoEffect);

	/**
	 *  @static
	 *  @type {Object}
	 */
	Tone.Freeverb.defaults = {
		"roomSize" : 0.7,
		"dampening" : 0.5
	};

	/**
	 *  set the room size
	 *  @param {number} roomsize roomsize value between 0-1
	 */
	Tone.Freeverb.prototype.setRoomSize = function(roomsize) {
		this.roomSize.setValue(roomsize);
	};

	/**
	 * @return {number} the room size
	 */
	Tone.Freeverb.prototype.getRoomSize = function(){
		return this.roomSize.getValue();
	};

	/**
	 *  set the dampening
	 *  @param {number} dampening dampening between 0-1
	 */
	Tone.Freeverb.prototype.setDampening = function(dampening) {
		this.dampening.setValue(dampening);
	};

	/**
	 * @return {number} the dampening
	 */
	Tone.Freeverb.prototype.getDampening = function(){
		return this.dampening.getValue();
	};

	/**
	 *  set multiple parameters at once with an object
	 *  @param {Object} params the parameters as an object
	 */
	Tone.Freeverb.prototype.set = function(params){
		if (!this.isUndef(params.dampening)) this.setDampening(params.dampening);
		if (!this.isUndef(params.roomSize)) this.setRoomSize(params.roomSize);
		Tone.StereoEffect.prototype.set.call(this, params);
	};

	/**
	 *  clean up
	 */
	Tone.Freeverb.prototype.dispose = function(){
		Tone.StereoEffect.prototype.dispose.call(this);
		for (var al = 0; al < this._allpassFiltersL.length; al++) {
			this._allpassFiltersL[al].disconnect();
			this._allpassFiltersL[al] = null;
		}
		this._allpassFiltersL = null;
		for (var ar = 0; ar < this._allpassFiltersR.length; ar++) {
			this._allpassFiltersR[ar].disconnect();
			this._allpassFiltersR[ar] = null;
		}
		this._allpassFiltersR = null;
		for (var cf = 0; cf < this._combFilters.length; cf++) {
			this._combFilters[cf].dispose();
			this._combFilters[cf] = null;
		}
		this._combFilters = null;
		this.roomSize.dispose();
		this.dampening.dispose();
		this._dampeningScale.dispose();
		this.roomSize = null;
		this.dampening = null;
		this._dampeningScale = null;
	};

	return Tone.Freeverb;
});<|endoftext|>


<commit_before>/*** MQTT Z-Way odule *******************************************
 Version: 1.0.0
 -----------------------------------------------------------------------------
 Author: David Uebelacker <david@uebelacker.ch>
 ******************************************************************************/

function ZWayMqttBridge(id, controller) {
    ZWayMqttBridge.super_.call(this, id, controller);
}

inherits(ZWayMqttBridge, AutomationModule);

_module = ZWayMqttBridge;

ZWayMqttBridge.prototype.init = function (config) {
    ZWayMqttBridge.super_.prototype.init.call(this, config);

    var self = this;

    this.log = function(message) {
        console.log('ZWayMqttBridge: ' + message);
    };

    if (!self.config.host || !self.config.port) {
        this.log('Host or port not configured! will not start!')
    };

    this.reconnect = function () {
        self.connected = false;
        self.mqttBridge = null;
        self.log('Will try to reconnect to Mqtt Bridge in 10 seconds ...');
        setTimeout(function () {
            self.connect();
        }, 10000);
    };

    this.connect = function () {
        self.log('Connecting to Mqtt Bridge ....');

        this.mqttBridge = new sockets.tcp();
        this.mqttBridge.onrecv = function (data) {
            self.log('Connecting to Mqtt Bridge established!');
            self.connected = true;
        };

        this.mqttBridge.onclose = function () {
            self.log('Mqtt Bridge connection was closed!');
            self.reconnect();
        };

        if (this.mqttBridge.connect(self.config.host, parseInt(self.config.port))) {
            setTimeout(function () {
                if (self.mqttBridge && !self.connected) {
                    self.log('Mqtt Bridge connection timeout!');
                    self.reconnect();
                }
            }, 5000);
        } else {
            self.log('Could not connect to Mqtt Bridge!');
            self.reconnect();
        }
    };

    this.findRoom = function(id) {
        var locations = self.controller.locations;
        if (locations) {
            for (var i = 0; i < locations.length; i++) {
                if (locations[i].id == id) {
                    return locations[i];
                }
            }
        }
        return null;
    };

    this.createTopic = function(device) {

        var topic = '/';
        self.log(topic)
        topic += self.config.topic_prefix;
        self.log(topic)
        topic += '/';
        self.log(topic)
        topic += self.normalizeTopicToken(self.findRoom(device.get('location')));
        self.log(topic)
        topic += '/';
        self.log(topic)
        topic += self.normalizeTopicToken(device.get('metrics:title'));
        self.log(topic)
        return topic;
    };

    this.normalizeTopicToken = function(token) {
        token = token.toLowerCase();
        token = token.replace(/[^0-9a-z_]/g, '_');
        return token;
    };

    this.deviceUpdate = function (device) {
        if (self.mqttBridge) {
            var message = {
                'topic': self.createTopic(device),
                'payload': device.get('metric:level')
            };

            var str = JSON.stringify(message);

            self.log('Sending update to bridge:' + str);

            var buf = new ArrayBuffer(str.length); // 2 bytes for each char
            var bufView = new Uint8Array(buf);

            for (var i=0; i < str.length; i++) {
                bufView[i] = str.charCodeAt(i);
            }

            self.mqttBridge.send(buf);
        }
    };

    this.connect();
    this.controller.devices.on('change:metrics:level', self.deviceUpdate);
};

<commit_msg>devel<commit_after>/*** MQTT Z-Way odule *******************************************
 Version: 1.0.0
 -----------------------------------------------------------------------------
 Author: David Uebelacker <david@uebelacker.ch>
 ******************************************************************************/

function ZWayMqttBridge(id, controller) {
    ZWayMqttBridge.super_.call(this, id, controller);
}

inherits(ZWayMqttBridge, AutomationModule);

_module = ZWayMqttBridge;

ZWayMqttBridge.prototype.init = function (config) {
    ZWayMqttBridge.super_.prototype.init.call(this, config);

    var self = this;

    this.log = function(message) {
        console.log('ZWayMqttBridge: ' + message);
    };

    if (!self.config.host || !self.config.port) {
        this.log('Host or port not configured! will not start!')
    };

    this.reconnect = function () {
        self.connected = false;
        self.mqttBridge = null;
        self.log('Will try to reconnect to Mqtt Bridge in 10 seconds ...');
        setTimeout(function () {
            self.connect();
        }, 10000);
    };

    this.connect = function () {
        self.log('Connecting to Mqtt Bridge ....');

        this.mqttBridge = new sockets.tcp();
        this.mqttBridge.onrecv = function (data) {
            self.log('Connecting to Mqtt Bridge established!');
            self.connected = true;
        };

        this.mqttBridge.onclose = function () {
            self.log('Mqtt Bridge connection was closed!');
            self.reconnect();
        };

        if (this.mqttBridge.connect(self.config.host, parseInt(self.config.port))) {
            setTimeout(function () {
                if (self.mqttBridge && !self.connected) {
                    self.log('Mqtt Bridge connection timeout!');
                    self.reconnect();
                }
            }, 5000);
        } else {
            self.log('Could not connect to Mqtt Bridge!');
            self.reconnect();
        }
    };

    this.findRoom = function(id) {
        var locations = self.controller.locations;
        if (locations) {
            for (var i = 0; i < locations.length; i++) {
                if (locations[i].id == id) {
                    return locations[i];
                }
            }
        }
        return null;
    };

    this.createTopic = function(device) {

        var topic = '/';
        topic += self.config.topic_prefix;
        topic += '/';
        self.log(topic)
        topic += self.normalizeTopicToken(self.findRoom(device.get('location').title));
        self.log(topic)
        topic += '/';
        self.log(topic)
        topic += self.normalizeTopicToken(device.get('metrics:title'));
        self.log(topic)
        return topic;
    };

    this.normalizeTopicToken = function(token) {
        token = token.toLowerCase();
        token = token.replace(/[^0-9a-z_]/g, '_');
        return token;
    };

    this.deviceUpdate = function (device) {
        if (self.mqttBridge) {
            var message = {
                'topic': self.createTopic(device),
                'payload': device.get('metric:level')
            };

            var str = JSON.stringify(message);

            self.log('Sending update to bridge:' + str);

            var buf = new ArrayBuffer(str.length); // 2 bytes for each char
            var bufView = new Uint8Array(buf);

            for (var i=0; i < str.length; i++) {
                bufView[i] = str.charCodeAt(i);
            }

            self.mqttBridge.send(buf);
        }
    };

    this.connect();
    this.controller.devices.on('change:metrics:level', self.deviceUpdate);
};

<|endoftext|>


<commit_before>/*** MQTT Z-Way odule *******************************************
 Version: 1.0.0
 -----------------------------------------------------------------------------
 Author: David Uebelacker <david@uebelacker.ch>
 ******************************************************************************/

function ZWayMqttBridge(id, controller) {
    ZWayMqttBridge.super_.call(this, id, controller);
}

inherits(ZWayMqttBridge, AutomationModule);

_module = ZWayMqttBridge;

ZWayMqttBridge.prototype.init = function (config) {
    ZWayMqttBridge.super_.prototype.init.call(this, config);

    var self = this;

    this.reconnect = function () {
        self.connected = false;
        self.mqttBridge = null;
        console.log('Will try to reconnect to Mqtt Bridge in 10 seconds ...');
        setTimeout(function () {
            console.log('Will try to reconnect to Mqtt Bridge ...');
            self.connect();
        }, 10000);
    };

    this.connect = function () {
        console.log('Connecting to Mqtt Bridge ....');

        this.mqttBridge = new sockets.tcp();

        this.mqttBridge.onrecv = function (data) {
            console.log('Mqtt Bridge server:' + data);
            self.connected = true;
        };

        this.mqttBridge.onclose = function () {
            console.log('Mqtt Bridge websocket was closed!');
            self.reconnect();
        };

        if (this.mqttBridge.connect('192.168.0.62', 8080)) {
            setTimeout(function () {
                if (self.mqttBridge && !self.connected) {
                    console.log('Could not connect to Mqtt Bridge after 5 seconds!');
                    self.reconnect();
                }
            }, 5000);
        } else {
            console.log('Could not connect to Mqtt Bridge!');
            self.reconnect();
        }
    };

    this.deviceUpdate = function (device) {
        if (self.mqttBridge) {
            console.log('Mqtt Bridge: Sending update to Client...')
            self.mqttBridge.send(JSON.stringify(device, null, 4));
        }
    };

    this.connect();
    this.controller.devices.on('change:metrics:level', self.deviceUpdate);
};

<commit_msg>devel<commit_after>/*** MQTT Z-Way odule *******************************************
 Version: 1.0.0
 -----------------------------------------------------------------------------
 Author: David Uebelacker <david@uebelacker.ch>
 ******************************************************************************/

function ZWayMqttBridge(id, controller) {
    ZWayMqttBridge.super_.call(this, id, controller);
}

inherits(ZWayMqttBridge, AutomationModule);

_module = ZWayMqttBridge;

ZWayMqttBridge.prototype.init = function (config) {
    ZWayMqttBridge.super_.prototype.init.call(this, config);

    var self = this;

    this.reconnect = function () {
        self.connected = false;
        self.mqttBridge = null;
        console.log('Will try to reconnect to Mqtt Bridge in 10 seconds ...');
        setTimeout(function () {
            console.log('Will try to reconnect to Mqtt Bridge ...');
            self.connect();
        }, 10000);
    };

    this.connect = function () {
        console.log('Connecting to Mqtt Bridge ....');

        this.mqttBridge = new sockets.tcp();

        this.mqttBridge.onrecv = function (data) {
            console.log('Mqtt Bridge server:' + String.fromCharCode.apply(null, new Uint16Array(data)));
            self.connected = true;
        };

        this.mqttBridge.onclose = function () {
            console.log('Mqtt Bridge websocket was closed!');
            self.reconnect();
        };

        if (this.mqttBridge.connect('192.168.0.62', 8080)) {
            setTimeout(function () {
                if (self.mqttBridge && !self.connected) {
                    console.log('Could not connect to Mqtt Bridge after 5 seconds!');
                    self.reconnect();
                }
            }, 5000);
        } else {
            console.log('Could not connect to Mqtt Bridge!');
            self.reconnect();
        }
    };

    this.deviceUpdate = function (device) {
        if (self.mqttBridge) {
            console.log('Mqtt Bridge: Sending update to Client...')

            var message = JSON.stringify(device, null, 4);

            var buf = new ArrayBuffer(message.length*2); // 2 bytes for each char
            var bufView = new Uint16Array(buf);

            for (var i=0, strLen=message.length; i < strLen; i++) {
                bufView[i] = message.charCodeAt(i);
            }

            self.mqttBridge.send(buf);
        }
    };

    this.connect();
    this.controller.devices.on('change:metrics:level', self.deviceUpdate);
};

<|endoftext|>


<commit_before>
/**
 * @file
 * @author  Bryan Hazelbaker <bryan.hazelbaker@gmail.com>
 * @version 1.0
 *
 * @copyright Copyright (c) 2013 Bryan Hazelbaker <bryan.hazelbaker@gmail.com>
 * Released under the MIT license. Read the entire license located in the
 * project root or at http://opensource.org/licenses/mit-license.php
 *
 * @brief Register callbacks to parse astro empires blue nova skin.
 *
 * @details Parsing the astro empires site to retrieve information is skin
 * specific. This file will determine if the Blue Nova skin is being used,
 * and if so will handle all parsing for it.
 *
 * @see https://github.com/delphian/astro-empires-javascript-library
 */

AstroEmpires.Skin.BlueNova2_new = {
    /**
     * Publish callback for url_account_display.
     *
     * Determine if we are using the BlueNova skin and set ae object if we are.
     */
    setSkin: function(data, messageType, ae) {
        var skin = false;
        // Get the current value of the skin drop down.
        skin = AstroEmpires.regex(/<select name='skin'.*?>.*?<option value='([^']*)' selected='selected'>.*?<\/select>/i, data.data, 1, ae.user.skin);
        skin = (skin.length == 0) ? 'BlueNova2_new' : skin;
        ae.user.skin = skin;
    },
    /**
     * Publish callback for skin_BlueNova2_new_account_display.
     *
     * Set the language used.
     */
    setLanguage: function(data, messageType, ae) {
        ae.user.language = AstroEmpires.regex(/<select name='language'.*?>.*?<option value='([^']*)' selected='selected'>.*?<\/select>/i, data.data, 1, ae.user.langauge);
    },
    /**
     * Publish callback for skin_BlueNova2_new_account.
     *
     * Capture the credits, income, fleetSize, technology, level and rank.
     */
    account: function(data, messageType, ae) {
        ae.stats.credits = AstroEmpires.regex(/<a id='credits'.*?([0-9,]+).*?<\/a>/ig, data.data, 1, ae.stats.credits);
        ae.stats.income = AstroEmpires.regex(/[\s]*Empire Income<\/b>[\s]*<\/td>[\s]*([0-9,]+)/ig, data.data, 1, ae.stats.income);
        ae.stats.fleetSize = AstroEmpires.regex(/[\s]*Fleet Size<\/b>[\s]*<\/td>[\s]*([0-9,]+)/ig, data.data, 1, ae.stats.fleetSize);
        ae.stats.technology = AstroEmpires.regex(/[\s]*Technology<\/b>[\s]*<\/td>[\s]*([0-9,]+)/ig, data.data, 1, ae.stats.technology);
        ae.stats.level = AstroEmpires.regex(/[\s]*Level<\/b>[\s]*<\/td>[\s]*([0-9\.]+)[^(]+\([^0-9]+([0-9]+)\)/ig, data.data, 1, ae.stats.level);
        ae.stats.rank = AstroEmpires.regex(/[\s]*Level<\/b>[\s]*<\/td>[\s]*([0-9\.]+)[^(]+\([^0-9]+([0-9]+)\)/ig, data.data, 2, ae.stats.rank);
    },
    /**
     * Publish callback for skin_BlueNova2_new_board.
     *
     * Capture all messages on the first page of the board. Record the messages
     * on the ae object.
     */
    board: function(data, messageType, ae) {
        var message,
            pattern = /
.*?<\/tr>
.*?<\/tr>/gi;
        while(message = AstroEmpires.regex(pattern, data.data, 0, false)) {
            var time = AstroEmpires.regex(/([0-9]{1,2} [a-z]{3} [0-9]{4},.*?)<\/td>/i, message, 1, false);
            time = Date.parse(time.replace(/, /gi, ',').replace(/ /gi, '/').replace(/,/gi, ' '))/1000;
            var read = AstroEmpires.regex(/
/i, message, 1, false);
            var msgId = AstroEmpires.regex(/quote=([0-9]+)/i, message, 1, false);
            var text = AstroEmpires.regex(/
<\/tr>
(.*?)<\/td><\/tr>/i, message, 1, false);
            var playerId = AstroEmpires.regex(/player=([0-9]+)/i, message, 1, false);
            var playerName = AstroEmpires.regex(/(.*?)<\/a>/i, message, 1, false);
            if (!ae.msgs.guild.exists(msgId)) {
                ae.msgs.guild.set(msgId, {
                    id: msgId,
                    time: time,
                    playerId: playerId,
                    playerName: playerName,
                    message: text,
                    read: read
                });
            }
        }
    },
    /**
     * Publish callback for skin_BlueNova2_new_messages.
     *
     * Capture private messages.
     */
    messages: function(data, messageType, ae) {
        var message,
            pattern = /
.*?<\/tr>
.*?<\/tr>/gi;
        while(message = AstroEmpires.regex(pattern, data.data, 0, false)) {
            var time = AstroEmpires.regex(/([0-9]{1,2} [a-z]{3} [0-9]{4},.*?)<\/td>/i, message, 1, false);
            time = Date.parse(time.replace(/, /gi, ',').replace(/ /gi, '/').replace(/,/gi, ' '))/1000;
            var read = AstroEmpires.regex(/
/i, message, 1, false);
            var msgId = AstroEmpires.regex(/reply=([0-9]+)/i, message, 1, false);
            var text = AstroEmpires.regex(/
<\/tr>
(.*?)<\/td><\/tr>/i, message, 1, false);
            var playerId = AstroEmpires.regex(/player=([0-9]+)/i, message, 1, false);
            var playerName = AstroEmpires.regex(/(.*?)<\/a>/i, message, 1, false);
            if (!ae.msgs.mail.exists(msgId)) {
                ae.msgs.mail.set(msgId, {
                    id: msgId,
                    time: time,
                    playerId: playerId,
                    playerName: playerName,
                    message: text,
                    read: read
                });
            }
        }
    },
    map: function(data, messageType, ae) {
        // Solar system. Record player information.
        $('div.map-system_content div.astro_container div.description a', data.data).each(function(index) {
            var msg = {
                type: 'player',
                action: 'set',
                id: AstroEmpires.regex(/player=([0-9]+)/i, $(this).attr('href'), 1, null),
                player: {
                    id: AstroEmpires.regex(/player=([0-9]+)/i, $(this).attr('href'), 1, null),
                    name: AstroEmpires.regex(/(\[[^\]]*\][\s]+)?([a-z0-9 ]+)/i, $(this).html(), 2, null),
                }
            };
            ae.players.set(player);
        });
    },
    /**
     * Register to handle all messages if they exist.
     *
     * This function will be automatically called by the AstroEmpires.AE constructor.
     */
    register: function(ae) {
        ae.subscribe('url_account_display', AstroEmpires.Skin.BlueNova2_new.setSkin);
        ae.subscribe('url_map', AstroEmpires.Skin.BlueNova2_new.map);
        ae.subscribe('skin_BlueNova2_new_account_display', AstroEmpires.Skin.BlueNova2_new.setLanguage);
        ae.subscribe('skin_BlueNova2_new_account', AstroEmpires.Skin.BlueNova2_new.account);
        ae.subscribe('skin_BlueNova2_new_board', AstroEmpires.Skin.BlueNova2_new.board);
        ae.subscribe('skin_BlueNova2_new_messages', AstroEmpires.Skin.BlueNova2_new.messages);
    }
}
<commit_msg>Fixing bug in blue nova map function.<commit_after>
/**
 * @file
 * @author  Bryan Hazelbaker <bryan.hazelbaker@gmail.com>
 * @version 1.0
 *
 * @copyright Copyright (c) 2013 Bryan Hazelbaker <bryan.hazelbaker@gmail.com>
 * Released under the MIT license. Read the entire license located in the
 * project root or at http://opensource.org/licenses/mit-license.php
 *
 * @brief Register callbacks to parse astro empires blue nova skin.
 *
 * @details Parsing the astro empires site to retrieve information is skin
 * specific. This file will determine if the Blue Nova skin is being used,
 * and if so will handle all parsing for it.
 *
 * @see https://github.com/delphian/astro-empires-javascript-library
 */

AstroEmpires.Skin.BlueNova2_new = {
    /**
     * Publish callback for url_account_display.
     *
     * Determine if we are using the BlueNova skin and set ae object if we are.
     */
    setSkin: function(data, messageType, ae) {
        var skin = false;
        // Get the current value of the skin drop down.
        skin = AstroEmpires.regex(/<select name='skin'.*?>.*?<option value='([^']*)' selected='selected'>.*?<\/select>/i, data.data, 1, ae.user.skin);
        skin = (skin.length == 0) ? 'BlueNova2_new' : skin;
        ae.user.skin = skin;
    },
    /**
     * Publish callback for skin_BlueNova2_new_account_display.
     *
     * Set the language used.
     */
    setLanguage: function(data, messageType, ae) {
        ae.user.language = AstroEmpires.regex(/<select name='language'.*?>.*?<option value='([^']*)' selected='selected'>.*?<\/select>/i, data.data, 1, ae.user.langauge);
    },
    /**
     * Publish callback for skin_BlueNova2_new_account.
     *
     * Capture the credits, income, fleetSize, technology, level and rank.
     */
    account: function(data, messageType, ae) {
        ae.stats.credits = AstroEmpires.regex(/<a id='credits'.*?([0-9,]+).*?<\/a>/ig, data.data, 1, ae.stats.credits);
        ae.stats.income = AstroEmpires.regex(/[\s]*Empire Income<\/b>[\s]*<\/td>[\s]*([0-9,]+)/ig, data.data, 1, ae.stats.income);
        ae.stats.fleetSize = AstroEmpires.regex(/[\s]*Fleet Size<\/b>[\s]*<\/td>[\s]*([0-9,]+)/ig, data.data, 1, ae.stats.fleetSize);
        ae.stats.technology = AstroEmpires.regex(/[\s]*Technology<\/b>[\s]*<\/td>[\s]*([0-9,]+)/ig, data.data, 1, ae.stats.technology);
        ae.stats.level = AstroEmpires.regex(/[\s]*Level<\/b>[\s]*<\/td>[\s]*([0-9\.]+)[^(]+\([^0-9]+([0-9]+)\)/ig, data.data, 1, ae.stats.level);
        ae.stats.rank = AstroEmpires.regex(/[\s]*Level<\/b>[\s]*<\/td>[\s]*([0-9\.]+)[^(]+\([^0-9]+([0-9]+)\)/ig, data.data, 2, ae.stats.rank);
    },
    /**
     * Publish callback for skin_BlueNova2_new_board.
     *
     * Capture all messages on the first page of the board. Record the messages
     * on the ae object.
     */
    board: function(data, messageType, ae) {
        var message,
            pattern = /
.*?<\/tr>
.*?<\/tr>/gi;
        while(message = AstroEmpires.regex(pattern, data.data, 0, false)) {
            var time = AstroEmpires.regex(/([0-9]{1,2} [a-z]{3} [0-9]{4},.*?)<\/td>/i, message, 1, false);
            time = Date.parse(time.replace(/, /gi, ',').replace(/ /gi, '/').replace(/,/gi, ' '))/1000;
            var read = AstroEmpires.regex(/
/i, message, 1, false);
            var msgId = AstroEmpires.regex(/quote=([0-9]+)/i, message, 1, false);
            var text = AstroEmpires.regex(/
<\/tr>
(.*?)<\/td><\/tr>/i, message, 1, false);
            var playerId = AstroEmpires.regex(/player=([0-9]+)/i, message, 1, false);
            var playerName = AstroEmpires.regex(/(.*?)<\/a>/i, message, 1, false);
            if (!ae.msgs.guild.exists(msgId)) {
                ae.msgs.guild.set(msgId, {
                    id: msgId,
                    time: time,
                    playerId: playerId,
                    playerName: playerName,
                    message: text,
                    read: read
                });
            }
        }
    },
    /**
     * Publish callback for skin_BlueNova2_new_messages.
     *
     * Capture private messages.
     */
    messages: function(data, messageType, ae) {
        var message,
            pattern = /
.*?<\/tr>
.*?<\/tr>/gi;
        while(message = AstroEmpires.regex(pattern, data.data, 0, false)) {
            var time = AstroEmpires.regex(/([0-9]{1,2} [a-z]{3} [0-9]{4},.*?)<\/td>/i, message, 1, false);
            time = Date.parse(time.replace(/, /gi, ',').replace(/ /gi, '/').replace(/,/gi, ' '))/1000;
            var read = AstroEmpires.regex(/
/i, message, 1, false);
            var msgId = AstroEmpires.regex(/reply=([0-9]+)/i, message, 1, false);
            var text = AstroEmpires.regex(/
<\/tr>
(.*?)<\/td><\/tr>/i, message, 1, false);
            var playerId = AstroEmpires.regex(/player=([0-9]+)/i, message, 1, false);
            var playerName = AstroEmpires.regex(/(.*?)<\/a>/i, message, 1, false);
            if (!ae.msgs.mail.exists(msgId)) {
                ae.msgs.mail.set(msgId, {
                    id: msgId,
                    time: time,
                    playerId: playerId,
                    playerName: playerName,
                    message: text,
                    read: read
                });
            }
        }
    },
    map: function(data, messageType, ae) {
        // Solar system. Record player information.
        $('div.map-system_content div.astro_container div.description a', data.data).each(function(index) {
            var player = {
                id: AstroEmpires.regex(/player=([0-9]+)/i, $(this).attr('href'), 1, null),
                name: AstroEmpires.regex(/(\[[^\]]*\][\s]+)?([a-z0-9 ]+)/i, $(this).html(), 2, null),
            };
            ae.players.set(player);
        });
    },
    /**
     * Register to handle all messages if they exist.
     *
     * This function will be automatically called by the AstroEmpires.AE constructor.
     */
    register: function(ae) {
        ae.subscribe('url_account_display', AstroEmpires.Skin.BlueNova2_new.setSkin);
        ae.subscribe('url_map', AstroEmpires.Skin.BlueNova2_new.map);
        ae.subscribe('skin_BlueNova2_new_account_display', AstroEmpires.Skin.BlueNova2_new.setLanguage);
        ae.subscribe('skin_BlueNova2_new_account', AstroEmpires.Skin.BlueNova2_new.account);
        ae.subscribe('skin_BlueNova2_new_board', AstroEmpires.Skin.BlueNova2_new.board);
        ae.subscribe('skin_BlueNova2_new_messages', AstroEmpires.Skin.BlueNova2_new.messages);
    }
}
<|endoftext|>


<commit_before>(function(ext) {

    //load MQTT library

  function loadMQTT() {
    $.getScript('http://sisomm.github.io/scratch-skull-extension/mqttws31.js')
      .done(function(script, textStatus) {
        console.log('Loaded MQTT');
      })
      .fail(function(jqxhr, settings, exception) {
        console.log('Error loading MQTT');
    });
  }

    // Cleanup function when the extension is unloaded
    ext._shutdown = function() {};

    // Status reporting code
    // Use this to report missing hardware, plugin or unsupported browser
    ext._getStatus = function() {
        return {status: 2, msg: 'Ready'};
    };

    // Functions for block with type 'w' will get a callback function as the
    // final argument. This should be called to indicate that the block can
    // stop waiting.

    ext.blink_eyes = function() {
        if(client.isConnected()) client.send(mqqtDefaultTopic,'BLINK,1');
    }

    ext.talk = function(times) {
         if(client.isConnected()) client.send(mqqtDefaultTopic,'JAW_MOTION,'+times+',1');
    }

   ext.head = function(x,y) {
         if(client.isConnected()) client.send(mqqtDefaultTopic,'SCRATCH_MOVE,'+Math.floor(x)+','+Math.floor(y));
    }

    ext.send_mqtt = function(topic,msg) {
         if(client.isConnected()) client.send(topic,msg);
    }

    ext.isConnected = function(){
        if(client.isConnected()){
            return 1;
        } else {
            return 0;
        }
    }

    ext.eyes = function(eye,onoff){
        if(!client.isConnected()) return;
        var level=(onoff=="On" ? 1 :0);
        if(eye=="Both"){
            client.send(mqqtDefaultTopic,'LED,1,'+level);
            client.send(mqqtDefaultTopic,'LED,0,'+level);
        } else {
            var whichEye=(eye=="Left"?0:1);
            client.send(mqqtDefaultTopic,'LED,'+whichEye+','+level);
        }
    }

    ext.mouth = function(position,callback){
        var cmd =0;
        if(position=="Open") {
            cmd=1;
        }
        if(client.isConnected()) client.send(mqqtDefaultTopic,'JAW_POSITION,'+cmd);
        //Allow the movement to finish.. //todo add delay in the arduino code
        window.setTimeout(function() {
            callback();
        }, 500);
    }

    // Block and block menu descriptions
    var descriptor = {
        blocks: [
            [' ', 'Blink Eyes', 'blink_eyes'],
            ['w', '%m.openClose Mouth', 'mouth','Close'],
            [' ', 'Move Head to %n,%n', 'head',300,300],
            [' ', 'Talk %n times', 'talk',5],
            [' ', '%m.whichEye Eye(s) %m.onOff', 'eyes','Both','On'],
            [' ', 'MQTT topic %s message %s','send_mqtt','/scratch/sisomm','Hello, World'],
            ['r', 'Connected','isConnected'],
        ],
        menus: {
            openClose:['Open','Close'],
            whichEye:['Both','Left','Right'],
            onOff:['On','Off']
        }
    };

    // Register the extension
    ScratchExtensions.register('Keith Richards', descriptor, ext);
    loadMQTT();

    var wsbroker = "test.mosquitto.org";  //mqtt websocket enabled broker
    var wsport = 8080 // port for above
    var client = new Paho.MQTT.Client(wsbroker, wsport,
        "myclientid_" + parseInt(Math.random() * 100, 10));
    var mqqtDefaultTopic="/scratch/sisomm";

    client.onConnectionLost = function (responseObject) {
        console.log("connection lost: " + responseObject.errorMessage);
        setTimeout(client.connect(),100);
    };

    client.onMessageArrived = function (message) {
        console.log(message.destinationName, ' -- ', message.payloadString);
    };

    var options = {
      timeout: 3,
      onSuccess: function () {
        console.log("mqtt connected");
        // Connection succeeded; subscribe to our topic, you can add multile lines of these
        client.subscribe("/scratch/sisomm/#", {qos: 1});

        //use the below if you want to publish to a topic on connect
        message = new Paho.MQTT.Message('Hello');
        message.destinationName = "/scratch/sisomm";
        client.send(message);

      },
      onFailure: function (message) {
        console.log("Connection failed: " + message.errorMessage);
      }
    };

    client.connect(options);

})({});<commit_msg>local broker<commit_after>(function(ext) {

    //load MQTT library

  function loadMQTT() {
    $.getScript('http://sisomm.github.io/scratch-skull-extension/mqttws31.js')
      .done(function(script, textStatus) {
        console.log('Loaded MQTT');
      })
      .fail(function(jqxhr, settings, exception) {
        console.log('Error loading MQTT');
    });
  }

    // Cleanup function when the extension is unloaded
    ext._shutdown = function() {};

    // Status reporting code
    // Use this to report missing hardware, plugin or unsupported browser
    ext._getStatus = function() {
        return {status: 2, msg: 'Ready'};
    };

    // Functions for block with type 'w' will get a callback function as the
    // final argument. This should be called to indicate that the block can
    // stop waiting.

    ext.blink_eyes = function() {
        if(client.isConnected()) client.send(mqqtDefaultTopic,'BLINK,1');
    }

    ext.talk = function(times) {
         if(client.isConnected()) client.send(mqqtDefaultTopic,'JAW_MOTION,'+times+',1');
    }

   ext.head = function(x,y) {
         if(client.isConnected()) client.send(mqqtDefaultTopic,'SCRATCH_MOVE,'+Math.floor(x)+','+Math.floor(y));
    }

    ext.send_mqtt = function(topic,msg) {
         if(client.isConnected()) client.send(topic,msg);
    }

    ext.isConnected = function(){
        if(client.isConnected()){
            return 1;
        } else {
            return 0;
        }
    }

    ext.eyes = function(eye,onoff){
        if(!client.isConnected()) return;
        var level=(onoff=="On" ? 1 :0);
        if(eye=="Both"){
            client.send(mqqtDefaultTopic,'LED,1,'+level);
            client.send(mqqtDefaultTopic,'LED,0,'+level);
        } else {
            var whichEye=(eye=="Left"?0:1);
            client.send(mqqtDefaultTopic,'LED,'+whichEye+','+level);
        }
    }

    ext.mouth = function(position,callback){
        var cmd =0;
        if(position=="Open") {
            cmd=1;
        }
        if(client.isConnected()) client.send(mqqtDefaultTopic,'JAW_POSITION,'+cmd);
        //Allow the movement to finish.. //todo add delay in the arduino code
        window.setTimeout(function() {
            callback();
        }, 500);
    }

    // Block and block menu descriptions
    var descriptor = {
        blocks: [
            [' ', 'Blink Eyes', 'blink_eyes'],
            ['w', '%m.openClose Mouth', 'mouth','Close'],
            [' ', 'Move Head to %n,%n', 'head',300,300],
            [' ', 'Talk %n times', 'talk',5],
            [' ', '%m.whichEye Eye(s) %m.onOff', 'eyes','Both','On'],
            [' ', 'MQTT topic %s message %s','send_mqtt','/scratch/sisomm','Hello, World'],
            ['r', 'Connected','isConnected'],
        ],
        menus: {
            openClose:['Open','Close'],
            whichEye:['Both','Left','Right'],
            onOff:['On','Off']
        }
    };

    // Register the extension
    ScratchExtensions.register('Keith Richards', descriptor, ext);
    loadMQTT();

 //  var wsbroker = "test.mosquitto.org";  //mqtt websocket enabled broker
     var wsbroker = "192.168.1.29";  //mqtt websocket enabled broker
 //   var wsport = 8080 // port for above
    var wsport = 9000 // port for above
    var client = new Paho.MQTT.Client(wsbroker, wsport,
        "myclientid_" + parseInt(Math.random() * 100, 10));
    var mqqtDefaultTopic="/scratch/sisomm";

    client.onConnectionLost = function (responseObject) {
        console.log("connection lost: " + responseObject.errorMessage);
        setTimeout(client.connect(),100);
    };

    client.onMessageArrived = function (message) {
        console.log(message.destinationName, ' -- ', message.payloadString);
    };

    var options = {
      timeout: 3,
      onSuccess: function () {
        console.log("mqtt connected");
        // Connection succeeded; subscribe to our topic, you can add multile lines of these
        client.subscribe("/scratch/sisomm/#", {qos: 1});

        //use the below if you want to publish to a topic on connect
        message = new Paho.MQTT.Message('Hello');
        message.destinationName = "/scratch/sisomm";
        client.send(message);

      },
      onFailure: function (message) {
        console.log("Connection failed: " + message.errorMessage);
      }
    };

    client.connect(options);

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