<commit_before>
Ui.Element.extend('Ui.ContentEditable', {
	html: undefined,
	screenX: 0,
	screenY: 0,
	startTime: undefined,
	allowSelect: false,
	timer: undefined,
//	hasHtmlFocus: false,
	anchorNode: null,
	anchorOffset: 0,

	constructor: function(config) {
		this.addEvents('anchorchange');

		this.setSelectable(true);
		this.setFocusable(true);
//		this.getDrawing().style.outline = 'red none 0px';
//		this.getDrawing().style.borderBottom = 'solid red 1px';
//		this.getDrawing().style.borderRight = 'solid red 1px';
		this.getDrawing().setAttribute('contenteditable', 'true');
//		this.connect(this.getDrawing(), 'selectstart', this.onHtmlSelectStart);
		this.connect(this.getDrawing(), 'mousedown', this.onMouseDown);
//		this.connect(this.getDrawing(), 'focus', this.onHtmlFocus);
//		this.connect(this.getDrawing(), 'blur', this.onHtmlBlur);
//		this.connect(this.getDrawing(), 'keypress', this.onHtmlKeyPress);
		this.connect(this.getDrawing(), 'keyup', this.onKeyUp);

		this.connect(this.getDrawing(), 'touchstart', this.onTouchStart);
		this.connect(this.getDrawing(), 'touchend', this.onTouchEndCapture, true);
	},

	getHtml: function() {
		return this.getDrawing().innerHTML;
	},

	setHtml: function(html) {
		this.getDrawing().innerHTML = html;
		this.html = this.getDrawing().innerHTML;
		this.invalidateMeasure();
	},

	getText: function() {
		return ('innerText' in this.getDrawing())?this.getDrawing().innerText:this.getDrawing().textContent;
	},

	onKeyUp: function(event) {
		this.testAnchorChange();
	},

	onSubtreeModified: function(event) {
		this.testAnchorChange();
		this.html = this.getDrawing().innerHTML;
		this.invalidateMeasure();
	},

	onKeyPress: function(event) {
		if(this.getDrawing().innerHTML != this.html) {
			this.html = this.getDrawing().innerHTML;
			this.invalidateMeasure();
		}
	},

	onTouchEndCapture: function() {
		new Core.DelayedTask({ scope: this, delay: 0, callback: function() {
			this.testAnchorChange();
		}});
	},

	onTouchStart: function(event) {
		if(event.targetTouches.length == 1) {
			event.stopPropagation();

			this.connect(this.getDrawing(), 'touchmove', this.onTouchMove, true);
			this.connect(this.getDrawing(), 'touchend', this.onTouchEnd, true);

			if(this.timer != undefined) {
				this.timer.abort();
				this.timer = undefined;
			}
			this.timer = new Core.DelayedTask({	delay: 0.5, scope: this, callback: this.onTimer });
		}
	},

	onTouchMove: function(event) {
		if(!this.allowSelect) {
			if(this.timer != undefined) {
				this.timer.abort();
				this.timer = undefined;
			}
			this.disconnect(this.getDrawing(), 'touchmove', this.onTouchMove, true);
			this.disconnect(this.getDrawing(), 'touchend', this.onTouchEnd, true);
		}
//		else {
//			if(this.hasHtmlFocus)
//				event.stopPropagation();
//		}
	},

	onTouchEnd: function(event) {
		event.stopPropagation();

		if(this.timer != undefined) {
			this.timer.abort();
			this.timer = undefined;
		}

		this.disconnect(this.getDrawing(), 'touchmove', this.onTouchMove, true);
		this.disconnect(this.getDrawing(), 'touchend', this.onTouchEnd, true);
		this.allowSelect = false;
	},

	onHtmlKeyPress: function(event) {
//		console.log('onHtmlKeyPress');

/*		console.log('keypress: '+event.which);
		if(event.which == 13) {
			event.stopPropagation();
			event.preventDefault();
		}*/
	},

/*	onHtmlFocus: function(event) {
		console.log('onHtmlFocus');
		this.hasHtmlFocus = true;
		this.setSelectable(true);
		if(this.timer != undefined) {
			this.timer.abort();
			this.timer = undefined;
		}
		this.timer = new Core.DelayedTask({	delay: 0.25, scope: this, callback: this.onTimer });
	},

	onHtmlBlur: function(event) {
		console.log('onHtmlBlur');
		this.hasHtmlFocus = false;
		if(this.timer != undefined) {
			this.timer.abort();
			this.timer = undefined;
		}
		this.allowSelect = false;
	},*/

	onTimer: function(timer) {
		this.allowSelect = true;
		this.timer = undefined;
	},

	onMouseDown: function(event) {
		this.setSelectable(true);
		event.stopPropagation();

		if(this.timer != undefined) {
			this.timer.abort();
			this.timer = undefined;
		}
		this.allowSelect = false;
		this.timer = new Core.DelayedTask({	delay: 0.50, scope: this, callback: this.onTimer });

		this.screenX = event.screenX;
		this.screenY = event.screenY;

		var currentTime = (new Date().getTime())/1000;
		this.startTime = currentTime;

		this.connect(window, 'mousemove', this.onMouseMove, true);
		this.connect(window, 'mouseup', this.onMouseUp, true);
	},

	onMouseMove: function(event) {
		if(!this.allowSelect) {
			var deltaX = event.screenX - this.screenX;
			var deltaY = event.screenY - this.screenY;
			var delta = Math.sqrt(deltaX * deltaX + deltaY * deltaY);

			event.stopPropagation();
			event.preventDefault();

			// if the user move to much, release the touch event
			if(delta > 10) {
				if(this.timer != undefined) {
					this.timer.abort();
					this.timer = undefined;
				}

				var selection = window.getSelection();
				selection.removeAllRanges();
				this.setSelectable(false);

				this.disconnect(window, 'mousemove', this.onMouseMove, true);
				this.disconnect(window, 'mouseup', this.onMouseUp, true);

				var mouseDownEvent = document.createEvent('MouseEvents');
				mouseDownEvent.initMouseEvent('mousedown', true, true, window, 1, event.screenX, event.screenY,
					event.clientX, event.clientY,
					event.ctrlKey, event.altKey, event.shiftKey,
					event.metaKey, 0, event.target);
				this.getDrawing().offsetParent.dispatchEvent(mouseDownEvent);
			}
		}
		else
			event.stopPropagation();
	},

	onMouseUp: function(event) {
		this.testAnchorChange();

		if(this.timer != undefined) {
			this.timer.abort();
			this.timer = undefined;
		}
		this.disconnect(window, 'mousemove', this.onMouseMove, true);
		this.disconnect(window, 'mouseup', this.onMouseUp, true);
	},

	testAnchorChange: function() {
		if((window.getSelection().anchorNode != this.anchorNode) ||
			(window.getSelection().anchorOffset != this.anchorOffset)) {
			this.anchorNode = window.getSelection().anchorNode;
			this.anchorOffset = window.getSelection().anchorOffset;
//			console.log('anchor changed (offset: '+this.anchorOffset+')');
			this.fireEvent('anchorchange', this);
		}
	}

//	onHtmlSelectStart: function(event) {
//		event.stopPropagation();
//	}

}, {
	renderDrawing: function() {
		var drawing = document.createElement('div');
		drawing.style.display = 'block';
		drawing.style.position = 'absolute';
		drawing.style.left = '0px';
		drawing.style.top = '0px';
		this.connect(drawing, 'DOMSubtreeModified', this.onSubtreeModified);
		this.connect(drawing, 'keypress', this.onKeyPress);
		return drawing;
	},

	measureCore: function(width, height) {
		var div = document.createElement('div');
		div.style.display = 'block';
		div.style.visibility = 'hidden';
		div.style.position = 'absolute';
		div.style.left = '0px';
		div.style.top = '0px';
		if(this.getWidth() != undefined)
			div.style.width = this.getWidth()+'px';
		div.innerHTML = this.getDrawing().innerHTML;
		document.body.appendChild(div);
		var needWidth = div.clientWidth;
		var needHeight = div.clientHeight;
		document.body.removeChild(div);

		return { width: needWidth, height: needHeight };
	}
});

<commit_msg>add styles to Ui.ContentEditable + handle <br> in contentText for Firefox to looks like the others<commit_after>
Ui.Element.extend('Ui.ContentEditable', {
	html: undefined,
	screenX: 0,
	screenY: 0,
	startTime: undefined,
	allowSelect: false,
	timer: undefined,
//	hasHtmlFocus: false,
	anchorNode: null,
	anchorOffset: 0,

	constructor: function(config) {
		this.addEvents('anchorchange');

		this.setSelectable(true);
		this.setFocusable(true);
//		this.getDrawing().style.outline = 'red none 0px';
//		this.getDrawing().style.borderBottom = 'solid red 1px';
//		this.getDrawing().style.borderRight = 'solid red 1px';
		this.getDrawing().setAttribute('contenteditable', 'true');
//		this.connect(this.getDrawing(), 'selectstart', this.onHtmlSelectStart);
		this.connect(this.getDrawing(), 'mousedown', this.onMouseDown);
//		this.connect(this.getDrawing(), 'focus', this.onHtmlFocus);
//		this.connect(this.getDrawing(), 'blur', this.onHtmlBlur);
//		this.connect(this.getDrawing(), 'keypress', this.onHtmlKeyPress);
		this.connect(this.getDrawing(), 'keyup', this.onKeyUp);

		this.connect(this.getDrawing(), 'touchstart', this.onTouchStart);
		this.connect(this.getDrawing(), 'touchend', this.onTouchEndCapture, true);
	},

	getHtml: function() {
		return this.getDrawing().innerHTML;
	},

	setHtml: function(html) {
		this.getDrawing().innerHTML = html;
		this.html = this.getDrawing().innerHTML;
		this.invalidateMeasure();
	},

	getTextContent: function(el) {
		var text = '';
		if(el.nodeType === 3)
			text += el.textContent;
		else if((el.nodeType === 1) && (el.nodeName == "BR"))
			text += '\n';
		if('childNodes' in el) {
			for(var i = 0; i < el.childNodes.length; i++)
				text += this.getTextContent(el.childNodes[i]);
		}
		return text;
	},

	getText: function() {
		return ('innerText' in this.getDrawing())?this.getDrawing().innerText:this.getTextContent(this.getDrawing());
	},

	onKeyUp: function(event) {
		this.testAnchorChange();
	},

	onSubtreeModified: function(event) {
		this.testAnchorChange();
		this.html = this.getDrawing().innerHTML;
		this.invalidateMeasure();
	},

	onKeyPress: function(event) {
		if(this.getDrawing().innerHTML != this.html) {
			this.html = this.getDrawing().innerHTML;
			this.invalidateMeasure();
		}
	},

	onTouchEndCapture: function() {
		new Core.DelayedTask({ scope: this, delay: 0, callback: function() {
			this.testAnchorChange();
		}});
	},

	onTouchStart: function(event) {
		if(event.targetTouches.length == 1) {
			event.stopPropagation();

			this.connect(this.getDrawing(), 'touchmove', this.onTouchMove, true);
			this.connect(this.getDrawing(), 'touchend', this.onTouchEnd, true);

			if(this.timer != undefined) {
				this.timer.abort();
				this.timer = undefined;
			}
			this.timer = new Core.DelayedTask({	delay: 0.5, scope: this, callback: this.onTimer });
		}
	},

	onTouchMove: function(event) {
		if(!this.allowSelect) {
			if(this.timer != undefined) {
				this.timer.abort();
				this.timer = undefined;
			}
			this.disconnect(this.getDrawing(), 'touchmove', this.onTouchMove, true);
			this.disconnect(this.getDrawing(), 'touchend', this.onTouchEnd, true);
		}
//		else {
//			if(this.hasHtmlFocus)
//				event.stopPropagation();
//		}
	},

	onTouchEnd: function(event) {
		event.stopPropagation();

		if(this.timer != undefined) {
			this.timer.abort();
			this.timer = undefined;
		}

		this.disconnect(this.getDrawing(), 'touchmove', this.onTouchMove, true);
		this.disconnect(this.getDrawing(), 'touchend', this.onTouchEnd, true);
		this.allowSelect = false;
	},

	onHtmlKeyPress: function(event) {
//		console.log('onHtmlKeyPress');

/*		console.log('keypress: '+event.which);
		if(event.which == 13) {
			event.stopPropagation();
			event.preventDefault();
		}*/
	},

/*	onHtmlFocus: function(event) {
		console.log('onHtmlFocus');
		this.hasHtmlFocus = true;
		this.setSelectable(true);
		if(this.timer != undefined) {
			this.timer.abort();
			this.timer = undefined;
		}
		this.timer = new Core.DelayedTask({	delay: 0.25, scope: this, callback: this.onTimer });
	},

	onHtmlBlur: function(event) {
		console.log('onHtmlBlur');
		this.hasHtmlFocus = false;
		if(this.timer != undefined) {
			this.timer.abort();
			this.timer = undefined;
		}
		this.allowSelect = false;
	},*/

	onTimer: function(timer) {
		this.allowSelect = true;
		this.timer = undefined;
	},

	onMouseDown: function(event) {
		this.setSelectable(true);
		event.stopPropagation();

		if(this.timer != undefined) {
			this.timer.abort();
			this.timer = undefined;
		}
		this.allowSelect = false;
		this.timer = new Core.DelayedTask({	delay: 0.50, scope: this, callback: this.onTimer });

		this.screenX = event.screenX;
		this.screenY = event.screenY;

		var currentTime = (new Date().getTime())/1000;
		this.startTime = currentTime;

		this.connect(window, 'mousemove', this.onMouseMove, true);
		this.connect(window, 'mouseup', this.onMouseUp, true);
	},

	onMouseMove: function(event) {
		if(!this.allowSelect) {
			var deltaX = event.screenX - this.screenX;
			var deltaY = event.screenY - this.screenY;
			var delta = Math.sqrt(deltaX * deltaX + deltaY * deltaY);

			event.stopPropagation();
			event.preventDefault();

			// if the user move to much, release the touch event
			if(delta > 10) {
				if(this.timer != undefined) {
					this.timer.abort();
					this.timer = undefined;
				}

				var selection = window.getSelection();
				selection.removeAllRanges();
				this.setSelectable(false);

				this.disconnect(window, 'mousemove', this.onMouseMove, true);
				this.disconnect(window, 'mouseup', this.onMouseUp, true);

				var mouseDownEvent = document.createEvent('MouseEvents');
				mouseDownEvent.initMouseEvent('mousedown', true, true, window, 1, event.screenX, event.screenY,
					event.clientX, event.clientY,
					event.ctrlKey, event.altKey, event.shiftKey,
					event.metaKey, 0, event.target);
				this.getDrawing().offsetParent.dispatchEvent(mouseDownEvent);
			}
		}
		else
			event.stopPropagation();
	},

	onMouseUp: function(event) {
		this.testAnchorChange();

		if(this.timer != undefined) {
			this.timer.abort();
			this.timer = undefined;
		}
		this.disconnect(window, 'mousemove', this.onMouseMove, true);
		this.disconnect(window, 'mouseup', this.onMouseUp, true);
	},

	testAnchorChange: function() {
		if((window.getSelection().anchorNode != this.anchorNode) ||
			(window.getSelection().anchorOffset != this.anchorOffset)) {
			this.anchorNode = window.getSelection().anchorNode;
			this.anchorOffset = window.getSelection().anchorOffset;
//			console.log('anchor changed (offset: '+this.anchorOffset+')');
			this.fireEvent('anchorchange', this);
		}
	}

//	onHtmlSelectStart: function(event) {
//		event.stopPropagation();
//	}

}, {
	renderDrawing: function() {
		var drawing = document.createElement('div');
		drawing.style.display = 'block';
		drawing.style.position = 'absolute';
		drawing.style.left = '0px';
		drawing.style.top = '0px';
		this.connect(drawing, 'DOMSubtreeModified', this.onSubtreeModified);
		this.connect(drawing, 'keypress', this.onKeyPress);
		return drawing;
	},

	measureCore: function(width, height) {
		var div = document.createElement('div');
		div.style.display = 'block';
		div.style.visibility = 'hidden';
		div.style.position = 'absolute';
		div.style.left = '0px';
		div.style.top = '0px';
		if(this.getWidth() != undefined)
			div.style.width = this.getWidth()+'px';
		div.innerHTML = this.getDrawing().innerHTML;
		document.body.appendChild(div);
		var needWidth = div.clientWidth;
		var needHeight = div.clientHeight;
		document.body.removeChild(div);

		return { width: needWidth, height: needHeight };
	},

	onStyleChange: function() {
		var color = Ui.Color.create(this.getStyleProperty('color'));
		this.getDrawing().style.fontSize = this.getStyleProperty('fontSize')+'px';
		this.getDrawing().style.fontFamily = this.getStyleProperty('fontFamily');
		this.getDrawing().style.fontWeight = this.getStyleProperty('fontWeight');
		if(navigator.supportRgba)
			this.getDrawing().style.color = color.getCssRgba();
		else
			this.getDrawing().style.color = color.getCssHtml();
		this.invalidateMeasure();
	}
}, {
	style: {
		color: new Ui.Color({ r: 0, g: 0, b: 0 }),
		fontSize: 18,
		fontFamily: 'Sans-serif',
		fontWeight: 'normal'
	}
});

<|endoftext|>


<commit_before>/*
===============================================================================

    Class compilation defines in-game 3D objects.

===============================================================================
*/
function Objects() {
    if ( !(this instanceof Objects) ) return new Objects();
}

/*
=================
Actor
    Entity, that represents object in space.
=================
*/
Objects.prototype.Actor = function ( x, y, z ) {
    if ( !(this instanceof Objects.prototype.Actor) ) return new Objects.prototype.Actor();

    this.x = x || 0;
    this.y = y || 0;
    this.z = z || 0;

    this.material = null;
    this.geometry = null;
    this.mesh     = null;

    this.objects = null;

    // Can be overridden.
    // Should do all initial work, before adding to the scene.
    this.create = function ( objects ) {
        this.objects = objects || DOA.Engine._objects;
        this.objects.push( this );
        if ( this.mesh instanceof THREE.Mesh ) {
            this.mesh.position.set( this.x, this.y, this.z );
        }
        return this.mesh;
    };
    // Can be overridden.
    // Should do all initial work, before removing from scene.
    this.clear = function () {
        this.objects.pop( this );
        return this.mesh;
    };

    // Method to animate mesh in the Engine cycle.
    this.animate = function ( args ) {

    };

    this.setX = function ( x ) { this.x = x; this.mesh.position.x = x; };
    this.setY = function ( y ) { this.y = y; this.mesh.position.y = y; };
    this.setZ = function ( z ) { this.z = z; this.mesh.position.z = z; };
    this.setPosition = function ( x, y, z ) {
        if ( typeof x === 'number' ) this.setX( x );
        if ( typeof y === 'number' ) this.setY( y );
        if ( typeof z === 'number' ) this.setZ( z );
    };
};

/*
=================
World
    Entity, that represents space, with a specific properties:
    gravity, world type (map, level), global lightning, etc.
=================
*/
Objects.prototype.World = function () {
    if ( !(this instanceof Objects.prototype.World) ) return new this.World();
};
<commit_msg>Update Actor object structure.<commit_after>/*
===============================================================================

    Class compilation defines in-game 3D objects.

===============================================================================
*/
function Objects() {
    if ( !(this instanceof Objects) ) return new Objects();
}

/*
=================
Actor
    Entity, that represents object in space.
=================
*/
Objects.prototype.Actor = function ( x, y, z ) {
    if ( !(this instanceof Objects.prototype.Actor) ) return new Objects.prototype.Actor();

    this.x = x || 0;
    this.y = y || 0;
    this.z = z || 0;

    this.material = null;
    this.geometry = null;
    this.mesh     = null;

    this.objects = null;

    // Can be overridden.
    // Should do all initial work, before adding to the scene.
    // @deprecated
    this.create = function ( objects ) {
        this.objects = objects || DOA.Engine._objects;
        this.objects.push( this );
        if ( this.mesh instanceof THREE.Mesh ) {
            this.mesh.position.set( this.x, this.y, this.z );
        }
        return this.mesh;
    };
    // Can be overridden.
    // Should do all initial work, before removing from scene.
    // @deprecated
    this.clear = function () {
        this.objects.pop( this );
        return this.mesh;
    };

    // Enables object for renderer. Marks active.
    this.enable = function () {
    };

    // Disables object for the renderer. Marks as suspended.
    this.disable = function () {
    };

    // Method to animate mesh in the Engine cycle.
    this.animate = function ( args ) {
    };

    this.setX = function ( x ) { this.x = x; this.mesh.position.x = x; };
    this.setY = function ( y ) { this.y = y; this.mesh.position.y = y; };
    this.setZ = function ( z ) { this.z = z; this.mesh.position.z = z; };
    this.setPosition = function ( x, y, z ) {
        if ( typeof x === 'number' ) this.setX( x );
        if ( typeof y === 'number' ) this.setY( y );
        if ( typeof z === 'number' ) this.setZ( z );
    };
};

/*
=================
World
    Entity, that represents space, with a specific properties:
    gravity, world type (map, level), global lightning, etc.
=================
*/
Objects.prototype.World = function () {
    if ( !(this instanceof Objects.prototype.World) ) return new this.World();
};
<|endoftext|>


<commit_before>/*
 This file is part of VoltDB.
 Copyright (C) 2008-2013 VoltDB Inc.

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as
 published by the Free Software Foundation, either version 3 of the
 License, or (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with VoltDB.  If not, see <http://www.gnu.org/licenses/>.
*/

var con;
var chartIntervalId;
var statsIntervalId;

// initialize actions
$(document).ready(function(){
    $('#loadingModal').modal('show');
    checkConnection();
});

function checkConnection() {
    VoltDB.TestConnection(location.hostname, 8080, false, null, null, false,
                          function(connected){
                              if (connected) {
                                  $('#loadingModal').modal('hide');
                                  connectToDatabase();
                              } else {
                                  checkConnection();
                              }
                          });
}

function connectToDatabase() {
    // connect to VoltDB HTTP/JSON interface
    con = VoltDB.AddConnection(location.hostname, 8080, false, null, null, false, (function(connection, success){}));

    // set the chart interval to 1 second default
    SetChartRefreshInterval(1);

    // set the stats interval to run every 1000 milliseconds
    statsIntervalId = setInterval(RefreshStats,1000);
}

// set/reset the chart interval
function SetChartRefreshInterval(interval) {
    if (chartIntervalId != null) {
        clearInterval(chartIntervalId);
        chartIntervalId = null;
    }
    if(interval > 0)
        chartIntervalId = setInterval(RefreshData, interval*1000);
}

// Refresh drop-down
$('#refresh-1').click(function(e) {
    e.preventDefault();// prevent the default anchor functionality
    SetChartRefreshInterval(1);
});
$('#refresh-5').click(function(e) {
    e.preventDefault();// prevent the default anchor functionality
    SetChartRefreshInterval(5);
});
$('#refresh-10').click(function(e) {
    e.preventDefault();// prevent the default anchor functionality
    SetChartRefreshInterval(10);
});
$('#refresh-pause').click(function(e) {
    e.preventDefault();// prevent the default anchor functionality
    SetChartRefreshInterval(-1);
});

// ----------------- Stats Charts -----------------

// this runs every second
function RefreshStats() {
    con.BeginExecute('@Statistics',
                     ['PROCEDUREPROFILE','0'],
                     function(response) {
                         DrawTPSChart(response,'#tps_chart');
                     }
                    );

}
var tpsVals = [];
var prevTime = null;
var tcount0 = null;
function DrawTPSChart(response, someDiv) {
    var tables = response.results;
    var table0 = tables[0];
    //var colcount = table0.schema.length;

    if (prevTime != null && table0.data[0][0] == prevTime) {
        // Skip cached old results
        return;
    }
    prevTime = table0.data[0][0];

    var time = table0.data[0][0]/1000;
    var tcount1 = 0;
    for(var r=0;r<table0.data.length;r++){ // for each row
        //var time = table0.data[r][0]/1000;
        tcount1 += table0.data[r][3];
    }
    var tps;
    if (tcount0 == null) {
        tps = 0;
    } else {
        tps = tcount1 - tcount0;
    }
    tcount0 = tcount1;
    tpsVals.push([time,tps]);

    var tpsline = { label: "TPS", data: tpsVals };

    var options = {
        series: {
	    lines: { show: true, fill: true },
	    //bars: { show: true, barWidth : 60*1000, fill: true},
	    points: { show: false }
        },
        xaxis: { mode: "time" },
        yaxis: { position: "right" },
        legend: { position: 'nw' }
    };

    $.plot($(someDiv), [tpsline], options);
}

// Draw a basic HTML table from a VoltTable
function DrawTable(response, tableName, selectedRow) {
    try {
        var tables = response.results;
        var hmt = tables[0];
        var colcount = hmt.schema.length;

        // the first time, initialize the table head
        if ($(tableName+' thead tr').length == 0) {
            var theadhtml = '
';
            for (var i=0; i<colcount; i++) {
                theadhtml += '' + hmt.schema[i].name + '	';
            }
            $(tableName).append('

');
            $(tableName).append('

');
            $(tableName).children('thead').html(theadhtml);
        }

        var tbodyhtml;
        for(var r=0;r<hmt.data.length;r++){ // for each row
            if (r==selectedRow) {
                tbodyhtml += '
';
            } else {
                tbodyhtml += '
';
            }
            for (var c=0;c<colcount;c++) { // for each column
                var f = hmt.data[r][c];

                // if type is DECIMAL
                if (hmt.schema[c].type == 22 || hmt.schema[c].type == 8) {
                    f = formatDecimal(f);
                }
                if (hmt.schema[c].type == 11) {
                    f = formatDate(f);
                }
                tbodyhtml += '' + f + '	';
            }
            tbodyhtml += '
';
        }
        $(tableName).children('tbody').html(tbodyhtml);

    } catch(x) {}
}

// Data Formatting Methods
function formatDecimal(n) {
    return (Math.round(parseFloat(n) * 100) / 100).toFixed(2);
}

function formatDate(n) {
    //return new Date(n/1000).toLocaleDateString();
    return new Date(n/1000).toUTCString();
}

function formatDateAsTime(n) {
    //return new Date(n/1000).toLocaleDateString();
    var d = new Date(n/1000).toUTCString();
    var s = d.toString().substring(17,29);
    return s;
}

<commit_msg>Fix throughput calculation.<commit_after>/*
 This file is part of VoltDB.
 Copyright (C) 2008-2013 VoltDB Inc.

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as
 published by the Free Software Foundation, either version 3 of the
 License, or (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with VoltDB.  If not, see <http://www.gnu.org/licenses/>.
*/

var con;
var chartIntervalId;
var statsIntervalId;

// initialize actions
$(document).ready(function(){
    $('#loadingModal').modal('show');
    checkConnection();
});

function checkConnection() {
    VoltDB.TestConnection(location.hostname, 8080, false, null, null, false,
                          function(connected){
                              if (connected) {
                                  $('#loadingModal').modal('hide');
                                  connectToDatabase();
                              } else {
                                  checkConnection();
                              }
                          });
}

function connectToDatabase() {
    // connect to VoltDB HTTP/JSON interface
    con = VoltDB.AddConnection(location.hostname, 8080, false, null, null, false, (function(connection, success){}));

    // set the chart interval to 1 second default
    SetChartRefreshInterval(1);

    // set the stats interval to run every 1000 milliseconds
    statsIntervalId = setInterval(RefreshStats,1000);
}

// set/reset the chart interval
function SetChartRefreshInterval(interval) {
    if (chartIntervalId != null) {
        clearInterval(chartIntervalId);
        chartIntervalId = null;
    }
    if(interval > 0)
        chartIntervalId = setInterval(RefreshData, interval*1000);
}

// Refresh drop-down
$('#refresh-1').click(function(e) {
    e.preventDefault();// prevent the default anchor functionality
    SetChartRefreshInterval(1);
});
$('#refresh-5').click(function(e) {
    e.preventDefault();// prevent the default anchor functionality
    SetChartRefreshInterval(5);
});
$('#refresh-10').click(function(e) {
    e.preventDefault();// prevent the default anchor functionality
    SetChartRefreshInterval(10);
});
$('#refresh-pause').click(function(e) {
    e.preventDefault();// prevent the default anchor functionality
    SetChartRefreshInterval(-1);
});

// ----------------- Stats Charts -----------------

// this runs every second
function RefreshStats() {
    con.BeginExecute('@Statistics',
                     ['PROCEDUREPROFILE','0'],
                     function(response) {
                         DrawTPSChart(response,'#tps_chart');
                     }
                    );

}
var tpsVals = [];
var prevTsMs = null;
var tcount0 = null;
function DrawTPSChart(response, someDiv) {
    var tables = response.results;
    var table0 = tables[0];
    //var colcount = table0.schema.length;

    var cTsMs = table0.data[0][0];
    if (prevTsMs != null && cTsMs == prevTsMs) {
        // Skip cached old results
        return;
    }
    var durationMs = cTsMs - prevTsMs;
    prevTsMs = cTsMs;

    var time = table0.data[0][0]/1000;
    var tcount1 = 0;
    for(var r=0;r<table0.data.length;r++){ // for each row
        //var time = table0.data[r][0]/1000;
        tcount1 += table0.data[r][3];
    }
    var tps;
    if (tcount0 == null) {
        tps = 0;
    } else {
        tps = (tcount1 - tcount0)*1000/durationMs;
    }
    tcount0 = tcount1;
    tpsVals.push([time,tps]);

    var tpsline = { label: "TPS", data: tpsVals };

    var options = {
        series: {
	    lines: { show: true, fill: true },
	    //bars: { show: true, barWidth : 60*1000, fill: true},
	    points: { show: false }
        },
        xaxis: { mode: "time" },
        yaxis: { position: "right" },
        legend: { position: 'nw' }
    };

    $.plot($(someDiv), [tpsline], options);
}

// Draw a basic HTML table from a VoltTable
function DrawTable(response, tableName, selectedRow) {
    try {
        var tables = response.results;
        var hmt = tables[0];
        var colcount = hmt.schema.length;

        // the first time, initialize the table head
        if ($(tableName+' thead tr').length == 0) {
            var theadhtml = '
';
            for (var i=0; i<colcount; i++) {
                theadhtml += '' + hmt.schema[i].name + '	';
            }
            $(tableName).append('

');
            $(tableName).append('

');
            $(tableName).children('thead').html(theadhtml);
        }

        var tbodyhtml;
        for(var r=0;r<hmt.data.length;r++){ // for each row
            if (r==selectedRow) {
                tbodyhtml += '
';
            } else {
                tbodyhtml += '
';
            }
            for (var c=0;c<colcount;c++) { // for each column
                var f = hmt.data[r][c];

                // if type is DECIMAL
                if (hmt.schema[c].type == 22 || hmt.schema[c].type == 8) {
                    f = formatDecimal(f);
                }
                if (hmt.schema[c].type == 11) {
                    f = formatDate(f);
                }
                tbodyhtml += '' + f + '	';
            }
            tbodyhtml += '
';
        }
        $(tableName).children('tbody').html(tbodyhtml);

    } catch(x) {}
}

// Data Formatting Methods
function formatDecimal(n) {
    return (Math.round(parseFloat(n) * 100) / 100).toFixed(2);
}

function formatDate(n) {
    //return new Date(n/1000).toLocaleDateString();
    return new Date(n/1000).toUTCString();
}

function formatDateAsTime(n) {
    //return new Date(n/1000).toLocaleDateString();
    var d = new Date(n/1000).toUTCString();
    var s = d.toString().substring(17,29);
    return s;
}

<|endoftext|>


<commit_before>/* https://github.com/aFarkas/webshim/issues#issue/16 */
jQuery.webshims.register('form-native-fix', function($, webshims, window, doc, undefined){

	if(!Modernizr.formvalidation || window.noHTMLExtFixes || Modernizr.bugfreeformvalidation){return;}

	var badWebkit = ($.browser.webkit && parseFloat($.browser.version, 10) < 534.19);
	var invalids = [],
		firstInvalidEvent,
		form,
		fromSubmit
	;

	//opera/chrome fix (this will double all invalid events in opera, we have to stop them!)
	//opera throws a submit-event and then the invalid events,
	//chrome7/safari5.02 has disabled invalid events, this brings them back
	//safari 5.02 reports false invalid events, if setCustomValidity was used
	if(window.addEventListener){
		var formnovalidate = {
			timer: undefined,
			prevented: false
		};
		window.addEventListener('submit', function(e){
			if(!formnovalidate.prevented && e.target.checkValidity && $.attr(e.target, 'novalidate') == null){
				fromSubmit = true;

				$(e.target).checkValidity();
				fromSubmit = false;
			}
		}, true);
		var preventValidityTest = function(e){
			if($.attr(e.target, 'formnovalidate') == null){return;}
			if(formnovalidate.timer){
				clearTimeout(formnovalidate.timer);
			}
			formnovalidate.prevented = true;
			formnovalidate.timer = setTimeout(function(){
				formnovalidate.prevented = false;
			}, 20);
		};
		window.addEventListener('click', preventValidityTest, true);
		window.addEventListener('touchstart', preventValidityTest, true);
		window.addEventListener('touchend', preventValidityTest, true);
	}

	$(document)
		.bind('firstinvalidsystem', function(e, data){
			form = data.form;
			if(!form){return;}
			firstInvalidEvent = false;
			invalids = [];

			var submitEvents = $(form)
				.unbind('submit.preventInvalidSubmit')
				.bind('submit.preventInvalidSubmit', function(submitEvent){
					if( $.attr(form, 'novalidate') == null ){
						submitEvent.stopImmediatePropagation();
						return false;
					}
				})
				.data('events').submit
			;
			//add this handler as first executing handler
			if (submitEvents && submitEvents.length > 1) {
				submitEvents.unshift(submitEvents.pop());
			}
			if(!fromSubmit){return;}
			firstInvalidEvent = data;
		})
		.bind('invalid', function(e){
			if(invalids.indexOf(e.target) == -1){
				invalids.push(e.target);
			} else {
				e.stopImmediatePropagation();
			}
		})
		.bind('lastinvalid', function(e, data){
			var firstTarget = data.invalidlist[0];
			if( firstTarget && badWebkit && document.activeElement && firstTarget !== document.activeElement && firstInvalidEvent && !firstInvalidEvent.isInvalidUIPrevented() ){
				webshims.validityAlert.showFor(firstTarget);
			}
			firstInvalidEvent = false;
			invalids = [];
			//remove webkit/operafix
			if(!form){return;}
			$(form).unbind('submit.preventInvalidSubmit');
		})
	;

	(function(){
		//safari 5.0.2/5.0.3 has serious issues with checkValidity in combination with setCustomValidity so we mimic checkValidity using validity-property (webshims.fix.checkValidity)
		if(!badWebkit){return;}
		['input', 'textarea', 'select'].forEach(function(name){
			var desc = webshims.defineNodeNameProperty(name, 'checkValidity', {
				value: function(){
					if(!this.willValidate){return true;}
					var valid = ($.attr(this, 'validity') || {valid: true}).valid;
					if(!valid && desc._supvalue && desc._supvalue.call(this)){
						$(this).trigger('invalid');
					}
					return valid;
				}
			});
		});

		webshims.defineNodeNameProperty('form', 'checkValidity', {
			value: function(){
				var ret = true;
				$(this.elements || [])
					.each(function(){
						 if($(this).checkValidity() === false){
							ret = false;
						}
					})
				;
				return ret;
			}
		});

	})();

	(function(){
		if(!$.browser.opera){return;}
		var preventDefault = function(e){
			e.preventDefault();
		};

		['form', 'input', 'textarea', 'select'].forEach(function(name){
			var desc = webshims.defineNodeNameProperty(name, 'checkValidity', {
				value: function(){
					if(!fromSubmit){
						$(this).bind('invalid', preventDefault);
					}
					var ret = desc._supvalue.apply(this, arguments);
					if(!fromSubmit){
						$(this).unbind('invalid', preventDefault);
					}
					return ret;
				}
			});
		});
	})();

	if(!Modernizr.requiredSelect){
		webshims.ready('form-extend', function(){
			var isPlaceholderOptionSelected = function(select){
				if(select.type == 'select-one' && select.size < 2){
					var option = $('> option:first-child', select);
					return (!option.attr('disabled') && option.attr('selected'));
				}
				return false;
			};
			webshims.addValidityRule('valueMissing', function(jElm, val, cache, validityState){

				if(cache.nodeName == 'select' && !val && jElm.attr('required')){
					if(!cache.type){
						cache.type = jElm[0].type;
					}

					if(!val && (jElm[0].selectedIndex < 0 || isPlaceholderOptionSelected(jElm[0]) )){
						return true;
					}
				}
				return validityState.valueMissing;
			});

			webshims.defineNodeNamesBooleanProperty(['select'], 'required', {
				set: function(value){
					this.setAttribute('aria-required', (value) ? 'true' : 'false');
					$.attr(this, 'validity');
				},
				initAttr: true
			});
		});
	}
});<commit_msg>fixed really old chrome 7 bug<commit_after>/* https://github.com/aFarkas/webshim/issues#issue/16 */
jQuery.webshims.register('form-native-fix', function($, webshims, window, doc, undefined){

	if(!Modernizr.formvalidation || window.noHTMLExtFixes || Modernizr.bugfreeformvalidation){return;}

	var browserVersion = parseFloat($.browser.version, 10);
	var badWebkit = ($.browser.webkit && browserVersion < 534.19);
	var xBadWebkit = badWebkit && browserVersion < 533.18;
	var invalids = [],
		firstInvalidEvent,
		form,
		fromSubmit,
		fromCheckValidity
	;

	//opera/chrome fix (this will double all invalid events in opera, we have to stop them!)
	//opera throws a submit-event and then the invalid events,
	//chrome7/safari5.02 has disabled invalid events, this brings them back
	//safari 5.02 reports false invalid events, if setCustomValidity was used
	if(window.addEventListener){
		var formnovalidate = {
			timer: undefined,
			prevented: false
		};
		window.addEventListener('submit', function(e){
			if(!formnovalidate.prevented && e.target.checkValidity && $.attr(e.target, 'novalidate') == null){
				fromSubmit = true;

				$(e.target).checkValidity();
				fromSubmit = false;
			}
		}, true);
		var preventValidityTest = function(e){
			if($.attr(e.target, 'formnovalidate') == null){return;}
			if(formnovalidate.timer){
				clearTimeout(formnovalidate.timer);
			}
			formnovalidate.prevented = true;
			formnovalidate.timer = setTimeout(function(){
				formnovalidate.prevented = false;
			}, 20);
		};
		window.addEventListener('click', preventValidityTest, true);
		window.addEventListener('touchstart', preventValidityTest, true);
		window.addEventListener('touchend', preventValidityTest, true);
	}

	$(document)
		.bind('firstinvalidsystem', function(e, data){
			form = data.form;
			if(!form){return;}
			firstInvalidEvent = false;
			invalids = [];

			var submitEvents = $(form)
				.unbind('submit.preventInvalidSubmit')
				.bind('submit.preventInvalidSubmit', function(submitEvent){
					if( $.attr(form, 'novalidate') == null ){
						submitEvent.stopImmediatePropagation();
						return false;
					}
				})
				.data('events').submit
			;
			//add this handler as first executing handler
			if (submitEvents && submitEvents.length > 1) {
				submitEvents.unshift(submitEvents.pop());
			}

			if(!fromSubmit){return;}
			firstInvalidEvent = data;
		})
		.bind('invalid', function(e){
			if(invalids.indexOf(e.target) == -1){
				invalids.push(e.target);
			} else {
				e.stopImmediatePropagation();
			}
		})
		.bind('lastinvalid', function(e, data){
			var firstTarget = data.invalidlist[0];

			if( firstTarget && badWebkit && document.activeElement && firstTarget !== document.activeElement && firstInvalidEvent && !firstInvalidEvent.isInvalidUIPrevented() ){
				webshims.validityAlert.showFor(firstTarget);
			}
			firstInvalidEvent = false;
			invalids = [];
			//remove webkit/operafix
			if(!form){return;}
			$(form).unbind('submit.preventInvalidSubmit');
		})
	;

	//safari 5.0.0 and 5.0.1
	if(xBadWebkit){
		$(document).bind('firstinvalidsystem', function(e, data){
			if(fromCheckValidity){return;}
			setTimeout(function(){
				if(!data.isInvalidUIPrevented()){
					webshims.validityAlert.showFor(data.element);
				}
			}, 0);
		});
	}

	(function(){
		//safari 5.0.2/5.0.3 has serious issues with checkValidity in combination with setCustomValidity so we mimic checkValidity using validity-property (webshims.fix.checkValidity)
		if(!badWebkit){return;}
		['input', 'textarea', 'select'].forEach(function(name){
			var desc = webshims.defineNodeNameProperty(name, 'checkValidity', {
				value: function(){
					if(!this.willValidate){return true;}
					var valid = ($.attr(this, 'validity') || {valid: true}).valid;
					fromCheckValidity = true;
					if(!valid && desc._supvalue && desc._supvalue.call(this)){
						$(this).trigger('invalid');
					}
					fromCheckValidity = false;
					return valid;
				}
			});
		});

		webshims.defineNodeNameProperty('form', 'checkValidity', {
			value: function(){
				var ret = true;
				$(this.elements || [])
					.each(function(){
						 if($(this).checkValidity() === false){
							ret = false;
						}
					})
				;
				return ret;
			}
		});

	})();

	(function(){
		if(!$.browser.opera){return;}
		var preventDefault = function(e){
			e.preventDefault();
		};

		['form', 'input', 'textarea', 'select'].forEach(function(name){
			var desc = webshims.defineNodeNameProperty(name, 'checkValidity', {
				value: function(){
					if(!fromSubmit){
						$(this).bind('invalid', preventDefault);
					}
					fromCheckValidity = true;
					var ret = desc._supvalue.apply(this, arguments);
					if(!fromSubmit){
						$(this).unbind('invalid', preventDefault);
					}
					fromCheckValidity = false;
					return ret;
				}
			});
		});
	})();

	if(!Modernizr.requiredSelect){
		webshims.ready('form-extend', function(){
			var isPlaceholderOptionSelected = function(select){
				if(select.type == 'select-one' && select.size < 2){
					var option = $('> option:first-child', select);
					return (!option.attr('disabled') && option.attr('selected'));
				}
				return false;
			};
			webshims.addValidityRule('valueMissing', function(jElm, val, cache, validityState){

				if(cache.nodeName == 'select' && !val && jElm.attr('required')){
					if(!cache.type){
						cache.type = jElm[0].type;
					}

					if(!val && (jElm[0].selectedIndex < 0 || isPlaceholderOptionSelected(jElm[0]) )){
						return true;
					}
				}
				return validityState.valueMissing;
			});

			webshims.defineNodeNamesBooleanProperty(['select'], 'required', {
				set: function(value){
					this.setAttribute('aria-required', (value) ? 'true' : 'false');
					$.attr(this, 'validity');
				},
				initAttr: true
			});
		});
	}
});<|endoftext|>


<commit_before>/*
 * jQuery UI Tooltip @VERSION
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Tooltip
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.widget.js
 *	jquery.ui.position.js
 */
(function( $ ) {

var increments = 0;

$.widget("ui.tooltip", {
	options: {
		tooltipClass: null,
		items: "[title]",
		content: function() {
			return $( this ).attr( "title" );
		},
		position: {
			my: "left+15 center",
			at: "right center"
		}
	},

	_create: function() {
		this._bind({
			mouseover: "open",
			focusin: "open"
		});
	},

	enable: function() {
		this.options.disabled = false;
	},

	disable: function() {
		// only set option, disable element style changes
		this.options.disabled = true;
	},

	open: function( event ) {
		var target = $( event ? event.target : this.element ).closest( this.options.items );
		if ( !target.length ) {
			return;
		}

		var that = this;
		if ( !target.data( "tooltip-title" ) ) {
			target.data( "tooltip-title", target.attr( "title" ) );
		}
		var content = this.options.content.call( target[0], function( response ) {
			// IE may instantly serve a cached response, need to give it a chance to finish with _open before that
			setTimeout(function() {
				// when undefined, it got removeAttr, then ignore (ajax response)
				// initially its an empty string, so not undefined
				// TODO is there a better approach to enable ajax tooltips to have two updates?
				if ( target.attr( "aria-describedby" ) !== undefined ) {
					that._open( event, target, response );
				}
			}, 13 );
		});
		if ( content ) {
			that._open( event, target, content );
		}
	},

	_open: function( event, target, content ) {
		if ( !content ) {
			return;
		}

		target.attr( "title", "" );

		// TODO: why is this check after we clear the title?
		if ( this.options.disabled ) {
			return;
		}

		// ajaxy tooltip can update an existing one
		var tooltip = this._find( target );
		if ( !tooltip.length ) {
			tooltip = this._tooltip();
			target.attr( "aria-describedby", tooltip.attr( "id" ) );
		}
		tooltip.find( ".ui-tooltip-content" ).html( content );
		tooltip
			.stop( true )
			.position( $.extend({
				of: target,
				using: function( pos ) {
					// we only want to hide if there's no custom using defined
					$( this ).css( pos ).hide();
				}
			}, this.options.position ) );

		this._show( tooltip, this.options.show );

		this._trigger( "open", event );

		this._bind( target, {
			mouseleave: "close",
			blur: "close",
			click: "close"
		});
	},

	close: function( event ) {
		var target = $( event ? event.currentTarget : this.element );
		target.attr( "title", target.data( "tooltip-title" ) );

		if ( this.options.disabled ) {
			return;
		}

		var tooltip = this._find( target );
		target.removeAttr( "aria-describedby" );

		tooltip.stop( true );
		this._hide( tooltip, this.options.hide, function() {
			$( this ).remove();
		});

		target.unbind( "mouseleave.tooltip blur.tooltip" );

		this._trigger( "close", event );
	},

	_tooltip: function() {
		var tooltip = $( "<div>" )
			.attr({
				id: "ui-tooltip-" + increments++,
				role: "tooltip"
			})
			.addClass( "ui-tooltip ui-widget ui-corner-all ui-widget-content" +
				( this.options.tooltipClass || "" ) );
		$( "<div>" )
			.addClass( "ui-tooltip-content" )
			.appendTo( tooltip );
		tooltip.appendTo( document.body );
		return tooltip;
	},

	_find: function( target ) {
		var id = target.attr( "aria-describedby" );
		return id ? $( document.getElementById( id ) ) : $();
	}
});

$.ui.tooltip.version = "@VERSION";

}( jQuery ) );
<commit_msg>Tooltip: Cleanup.<commit_after>/*
 * jQuery UI Tooltip @VERSION
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Tooltip
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.widget.js
 *	jquery.ui.position.js
 */
(function( $ ) {

var increments = 0;

$.widget( "ui.tooltip", {
	options: {
		tooltipClass: null,
		items: "[title]",
		content: function() {
			return $( this ).attr( "title" );
		},
		position: {
			my: "left+15 center",
			at: "right center"
		}
	},

	_create: function() {
		this._bind({
			mouseover: "open",
			focusin: "open"
		});
	},

	enable: function() {
		this.options.disabled = false;
	},

	disable: function() {
		// only set option, disable element style changes
		this.options.disabled = true;
	},

	open: function( event ) {
		var target = $( event ? event.target : this.element ).closest( this.options.items );
		if ( !target.length ) {
			return;
		}

		var that = this;
		if ( !target.data( "tooltip-title" ) ) {
			target.data( "tooltip-title", target.attr( "title" ) );
		}
		var content = this.options.content.call( target[0], function( response ) {
			// IE may instantly serve a cached response for ajax requests
			// delay this call to _open so the other call to _open runs first
			setTimeout(function() {
				// when undefined, it got removeAttr, then ignore (ajax response)
				// initially its an empty string, so not undefined
				// TODO is there a better approach to enable ajax tooltips to have two updates?
				if ( target.attr( "aria-describedby" ) !== undefined ) {
					that._open( event, target, response );
				}
			}, 1 );
		});
		if ( content ) {
			that._open( event, target, content );
		}
	},

	_open: function( event, target, content ) {
		if ( !content ) {
			return;
		}

		target.attr( "title", "" );

		// TODO: why is this check after we clear the title?
		if ( this.options.disabled ) {
			return;
		}

		// ajaxy tooltip can update an existing one
		var tooltip = this._find( target );
		if ( !tooltip.length ) {
			tooltip = this._tooltip();
			target.attr( "aria-describedby", tooltip.attr( "id" ) );
		}
		tooltip.find( ".ui-tooltip-content" ).html( content );
		tooltip
			.stop( true )
			.position( $.extend({
				of: target,
				using: function( pos ) {
					// we only want to hide if there's no custom using defined
					$( this ).css( pos ).hide();
				}
			}, this.options.position ) );

		this._show( tooltip, this.options.show );

		this._trigger( "open", event );

		this._bind( target, {
			mouseleave: "close",
			blur: "close",
			click: "close"
		});
	},

	close: function( event ) {
		var target = $( event ? event.currentTarget : this.element );
		target.attr( "title", target.data( "tooltip-title" ) );

		if ( this.options.disabled ) {
			return;
		}

		var tooltip = this._find( target );
		target.removeAttr( "aria-describedby" );

		tooltip.stop( true );
		this._hide( tooltip, this.options.hide, function() {
			$( this ).remove();
		});

		// TODO: why isn't click unbound here?
		target.unbind( "mouseleave.tooltip blur.tooltip" );

		this._trigger( "close", event );
	},

	_tooltip: function() {
		var tooltip = $( "<div>" )
			.attr({
				id: "ui-tooltip-" + increments++,
				role: "tooltip"
			})
			.addClass( "ui-tooltip ui-widget ui-corner-all ui-widget-content" +
				( this.options.tooltipClass || "" ) );
		$( "<div>" )
			.addClass( "ui-tooltip-content" )
			.appendTo( tooltip );
		tooltip.appendTo( document.body );
		return tooltip;
	},

	_find: function( target ) {
		var id = target.attr( "aria-describedby" );
		return id ? $( "#" + id ) : $();
	}
});

$.ui.tooltip.version = "@VERSION";

}( jQuery ) );
<|endoftext|>


<commit_before>var config = require('../../../config.js');
var db     = config.db;
var core   = require('../../../core.js');
var _      = require('lodash');
var Promise = require('bluebird');

var utils = {};

var callId = "#1";
var args = {
    accountId: "test@test.com",
    ifInState: "",
    create: {},
    update: {},
    destroy: []
};

var validCreateObject = {
    id: "",
    parentId: null,
    role: null,
    totalMessages: 0,
    unreadMessages: 0,
    totalThread: "",
    unreadThread: ""
};

// List of ids created, use for cleanup
var created = [];

utils.createMailboxes = function (number) {
    var res = [];
    for (var i = 0; i < number; i++) {
        args.create[i] = validCreateObject;
    }
    return core.setMailboxes(res, args, callId).then(function () {
        var ids = [];
        _.keys(res[0][1].created).forEach(function (key) {
            var id = res[0][1].created[key].id;
            ids.push(id);
            created.push(id);
        });
        return ids;
    });
};

utils.cleanup = function () {
    var promises = [];
    created.forEach(function (id) {
        promises.push(db.get(id).then(function (doc) {
            return db.remove(doc);
        }));
    });
    return Promise.all(promises);
};

module.exports = utils;
<commit_msg>Update cleanup function<commit_after>var config  = require('../../../config.js');
var db      = config.db;
var core    = require('../../../core.js');
var models  = require('../../../models.js');
var _       = require('lodash');
var Promise = require('bluebird');

var utils = {};

var callId = "#1";
var args = {
    accountId: "test@test.com",
    ifInState: "",
    create: {},
    update: {},
    destroy: []
};

var validCreateObject = {
    id: "",
    parentId: null,
    role: null,
    totalMessages: 0,
    unreadMessages: 0,
    totalThread: "",
    unreadThread: ""
};

utils.createMailboxes = function (number) {
    var res = [];
    for (var i = 0; i < number; i++) {
        args.create[i] = validCreateObject;
    }
    return core.setMailboxes(res, args, callId).then(function () {
        var ids = [];
        _.keys(res[0][1].created).forEach(function (key) {
            var id = res[0][1].created[key].id;
            ids.push(id);
        });
        return ids;
    });
};

utils.cleanup = function (accountId) {
    var promises = [];
    var opts = {
        startkey: models.mailbox.startkey(accountId),
        endkey: models.mailbox.endkey(accountId)
    };

    return db.allDocs(opts).then(function (mailboxes) {
        mailboxes.rows.forEach(function (mailbox) {
            promises.push(db.remove({'_id': mailbox.id, '_rev': mailbox.value.rev}));
        });
        return Promise.all(promises);
    }).catch(function (err) {
        console.log(err);
    });
};

module.exports = utils;
<|endoftext|>


<commit_before>console.log(2);

var clicked = false;
var easterImgClass = "text-center";
var easterImgStyle = "width: 100%; height: auto;";
var easterImgSrcBase = "../img/easter-eggs/";
var easterImg = "some HTML string -> use setImg()";

function setImg(newSrc) {
    easterImg = "" +
                    "You found an Easter Egg!";
}

// GISD - Sharingan
$("#gisd-image").click(function () {

    if (clicked) return;
    else clicked = true;

    // create image
    var img = document.createElement("img");
    img.className = "img-circle img-responsive";
    img.src = "../img/sharingan/msharingan.png";
    img.alt = "Mangekyo Sharingan";
    img.onclick = rasengan();

    // create div
    var div = document.createElement("div");
    div.className = "timeline-image";

    // create li
    var li = document.createElement("li");
    li.className = "timeline-inverted wow rotateIn";

    div.appendChild(img);
    li.appendChild(div);
    $("#timeline-list").append(li);
});

function rasengan() {
    console.log("rasengan!");

    var randNum = Math.floor(Math.random() * 3);

    // create image
    var img = document.createElement("img");
    img.className = "img-circle img-responsive";
    img.alt = "Mangekyo Sharingan";
    img.onclick = "rasengan()";

    switch (randNum) {
        case 0: img.src = "../img/sharingan/msharingan.png";
        case 1: img.src = "../img/sharingan/msharingan-color.png";
        case 2: img.src = "../img/sharingan/sharingan.png";
    }

    // create div
    var div = document.createElement("div");
    div.className = "timeline-image";

    // create li
    var li = document.createElement("li");
    li.className = "timeline-inverted wow rotateIn";

    div.appendChild(img);
    li.appendChild(div);
    $("#timeline-list").append(li);
}

// Android
$("#android-image").click(function () {
    setImg("android-doughnut.jpg");
    bootbox.alert({
        size: 'large',
        title: 'My kind of doughnut! (me at Google HQ)',
        message: easterImg,
        callback: function () {
            console.log("bootbox over and out");
        }
    });
});

// HomeAway
$("#homeaway-image").click(function () {
    setImg("banana.jpg");
    bootbox.alert({
        size: 'large',
        title: "I don't work there at this time of writing so....here's a funny banana I made :p",
        message: easterImg,
        callback: function () {
            console.log("bootbox over and out");
        }
    });
});

// PayPal
$("#paypal-image").click(function () {
    setImg("paypal-ceo.jpg");
    bootbox.alert({
        size: 'large',
        title: 'Me and Dan Schulman (CEO of PayPal)',
        message: easterImg,
        callback: function () {
            console.log("bootbox over and out");
        }
    });
});

// IBM
$("#ibm-image").click(function () {
    setImg("floppy-disk.jpg");
    bootbox.alert({
        size: 'large',
        title: 'The oldest of companies',
        message: easterImg,
        callback: function () {
            console.log("bootbox over and out");
        }
    });
});

// Interests
$("#interests-image").click(function () {
    setImg("eyepatch.jpg");
    bootbox.alert({
        size: 'large',
        title: 'Why so serious?',
        message: easterImg,
        callback: function () {
            console.log("bootbox over and out");
        }
    });
});

// Details
$("#details-image").click(function () {
    setImg("daisy-straw.jpg");
    bootbox.alert({
        size: 'large',
        title: 'She helped on the website',
        message: easterImg,
        callback: function () {
            console.log("bootbox over and out");
        }
    });
});<commit_msg>updated rasengan again<commit_after>console.log(2);

var clicked = false;
var easterImgClass = "text-center";
var easterImgStyle = "width: 100%; height: auto;";
var easterImgSrcBase = "../img/easter-eggs/";
var easterImg = "some HTML string -> use setImg()";

function setImg(newSrc) {
    easterImg = "" +
                    "You found an Easter Egg!";
}

// GISD - Sharingan
$("#gisd-image").click(function () {

    if (clicked) return;
    else clicked = true;

    // create image
    var img = document.createElement("img");
    img.className = "img-circle img-responsive";
    img.src = "../img/sharingan/msharingan.png";
    img.alt = "Mangekyo Sharingan";
    img.onclick = rasengan;

    // create div
    var div = document.createElement("div");
    div.className = "timeline-image";

    // create li
    var li = document.createElement("li");
    li.className = "timeline-inverted wow rotateIn";

    div.appendChild(img);
    li.appendChild(div);
    $("#timeline-list").append(li);
});

function rasengan() {
    console.log("rasengan!");

    var randNum = Math.floor(Math.random() * 3);

    // create image
    var img = document.createElement("img");
    img.className = "img-circle img-responsive";
    img.alt = "Mangekyo Sharingan";
    img.onclick = "rasengan()";

    switch (randNum) {
        case 0: img.src = "../img/sharingan/msharingan.png";
        case 1: img.src = "../img/sharingan/msharingan-color.png";
        case 2: img.src = "../img/sharingan/sharingan.png";
    }

    // create div
    var div = document.createElement("div");
    div.className = "timeline-image";

    // create li
    var li = document.createElement("li");
    li.className = "timeline-inverted wow rotateIn";

    div.appendChild(img);
    li.appendChild(div);
    $("#timeline-list").append(li);
}

// Android
$("#android-image").click(function () {
    setImg("android-doughnut.jpg");
    bootbox.alert({
        size: 'large',
        title: 'My kind of doughnut! (me at Google HQ)',
        message: easterImg,
        callback: function () {
            console.log("bootbox over and out");
        }
    });
});

// HomeAway
$("#homeaway-image").click(function () {
    setImg("banana.jpg");
    bootbox.alert({
        size: 'large',
        title: "I don't work there at this time of writing so....here's a funny banana I made :p",
        message: easterImg,
        callback: function () {
            console.log("bootbox over and out");
        }
    });
});

// PayPal
$("#paypal-image").click(function () {
    setImg("paypal-ceo.jpg");
    bootbox.alert({
        size: 'large',
        title: 'Me and Dan Schulman (CEO of PayPal)',
        message: easterImg,
        callback: function () {
            console.log("bootbox over and out");
        }
    });
});

// IBM
$("#ibm-image").click(function () {
    setImg("floppy-disk.jpg");
    bootbox.alert({
        size: 'large',
        title: 'The oldest of companies',
        message: easterImg,
        callback: function () {
            console.log("bootbox over and out");
        }
    });
});

// Interests
$("#interests-image").click(function () {
    setImg("eyepatch.jpg");
    bootbox.alert({
        size: 'large',
        title: 'Why so serious?',
        message: easterImg,
        callback: function () {
            console.log("bootbox over and out");
        }
    });
});

// Details
$("#details-image").click(function () {
    setImg("daisy-straw.jpg");
    bootbox.alert({
        size: 'large',
        title: 'She helped on the website',
        message: easterImg,
        callback: function () {
            console.log("bootbox over and out");
        }
    });
});<|endoftext|>


<commit_before>/* See license.txt for terms of usage */

"use strict";

// Add-on SDK
const Events = require("sdk/event/core");
const { Cc, Ci, Cu } = require("chrome");

// DevTools
const { XPCOMUtils } = Cu.import("resource://gre/modules/XPCOMUtils.jsm", {});
const { devtools } = Cu.import("resource://gre/modules/devtools/Loader.jsm", {});
const { console } = Cu.import("resource://gre/modules/devtools/Console.jsm", {});
const { expectState } = devtools["require"]("devtools/server/actors/common");
const protocol = devtools["require"]("devtools/server/protocol");
const { method, RetVal, ActorClass, FrontClass, Front, Actor, Arg } = protocol;

// Bug 1203802 - Websocket Frame Listener API for devtool Network Inspector
const webSocketService = Cc["@mozilla.org/websocketframe/service;1"].
  getService(Ci.nsIWebSocketFrameService);

/**
 * Custom actor object
 */
var WsActor = ActorClass({
  typeName: "WsActor",

  /**
   * Events emitted by this actor.
   */
  events: {
    "frameReceived": { data: Arg(0, "json") },
    "frameSent": { data: Arg(0, "json") }
  },

  // Initialization

  initialize: function(conn, parent) {
    Actor.prototype.initialize.call(this, conn);

    console.log("WsActor.initialize");

    this.parent = parent;
    this.state = "detached";
  },

  destroy: function() {
    if (this.state === "attached") {
      this.detach();
    }

    Actor.prototype.destroy.call(this);
  },

  /**
   * Attach to this actor.
   */
  attach: method(expectState("detached", function() {
    this.state = "attached";

    var innerId = getInnerId(this.parent.window);
    webSocketService.addListener(innerId, this);

    return {
      type: "attached",
      winInnerId: innerId
    }
  }), {
    request: {},
    response: RetVal("json")
  }),

  /**
   * Detach from this actor.
   */
  detach: method(expectState("attached", function() {
    this.state = "detached";

    var innerId = getInnerId(this.parent.window);
    webSocketService.removeListener(innerId, this);
  }), {
    request: {},
    response: {
      type: "detached"
    }
  }),

  /**
   * Returns title of the content window.
   */
  getConnections: method(expectState("attached", function() {
    let win = this.parent.window;

    return {
      list: ["empty"]
    };
  }), {
    request: {},
    response: RetVal("json"),
  }),

  // nsIWebSocketFrameService listener

  QueryInterface:
    XPCOMUtils.generateQI([Ci.nsIWebSocketFrameListener]),

  frameReceived: function(webSocketSerialID, maskBit, finBit,
    rsvBits, opCode, payload) {

    Events.emit(this, "frameReceived", {
      webSocketSerialID: webSocketSerialID,
      maskBit: maskBit,
      finBit: finBit,
      rsvBits: rsvBits,
      opCode: opCode,
      payload: payload
    });
  },

  frameSent: function(webSocketSerialID, header, payload) {

    Events.emit(this, "frameSent", {
      webSocketSerialID: webSocketSerialID,
      header: header,
      payload: payload
    });
  }
});

// Helpers

function getInnerId(win) {
  return win.top.QueryInterface(Ci.nsIInterfaceRequestor).
    getInterface(Ci.nsIDOMWindowUtils).currentInnerWindowID;
}

/**
 * TODO: docs
 */
var WsActorFront = FrontClass(WsActor, {
  initialize: function(client, form) {
    Front.prototype.initialize.call(this, client, form);

    this.actorID = form[WsActor.prototype.typeName];
    this.manage(this);
  }
});

// Exports from this module
exports.WsActor = WsActor;
exports.WsActorFront = WsActorFront;
<commit_msg>Avoid exception if WebSocketsFrameService doesn't exist<commit_after>/* See license.txt for terms of usage */

"use strict";

// Add-on SDK
const Events = require("sdk/event/core");
const { Cc, Ci, Cu } = require("chrome");

// DevTools
const { XPCOMUtils } = Cu.import("resource://gre/modules/XPCOMUtils.jsm", {});
const { devtools } = Cu.import("resource://gre/modules/devtools/Loader.jsm", {});
const { console } = Cu.import("resource://gre/modules/devtools/Console.jsm", {});
const { expectState } = devtools["require"]("devtools/server/actors/common");
const protocol = devtools["require"]("devtools/server/protocol");
const { method, RetVal, ActorClass, FrontClass, Front, Actor, Arg } = protocol;

// Bug 1203802 - Websocket Frame Listener API for devtool Network Inspector
try {
  const webSocketService = Cc["@mozilla.org/websocketframe/service;1"].
    getService(Ci.nsIWebSocketFrameService);
} catch (err) {
}

/**
 * Custom actor object
 */
var WsActor = ActorClass({
  typeName: "WsActor",

  /**
   * Events emitted by this actor.
   */
  events: {
    "frameReceived": { data: Arg(0, "json") },
    "frameSent": { data: Arg(0, "json") }
  },

  // Initialization

  initialize: function(conn, parent) {
    Actor.prototype.initialize.call(this, conn);

    console.log("WsActor.initialize");

    this.parent = parent;
    this.state = "detached";
  },

  destroy: function() {
    if (this.state === "attached") {
      this.detach();
    }

    Actor.prototype.destroy.call(this);
  },

  /**
   * Attach to this actor.
   */
  attach: method(expectState("detached", function() {
    this.state = "attached";

    var innerId = getInnerId(this.parent.window);
    webSocketService.addListener(innerId, this);

    return {
      type: "attached",
      winInnerId: innerId
    }
  }), {
    request: {},
    response: RetVal("json")
  }),

  /**
   * Detach from this actor.
   */
  detach: method(expectState("attached", function() {
    this.state = "detached";

    var innerId = getInnerId(this.parent.window);
    webSocketService.removeListener(innerId, this);
  }), {
    request: {},
    response: {
      type: "detached"
    }
  }),

  /**
   * Returns title of the content window.
   */
  getConnections: method(expectState("attached", function() {
    let win = this.parent.window;

    return {
      list: ["empty"]
    };
  }), {
    request: {},
    response: RetVal("json"),
  }),

  // nsIWebSocketFrameService listener

  QueryInterface:
    XPCOMUtils.generateQI([Ci.nsIWebSocketFrameListener]),

  frameReceived: function(webSocketSerialID, maskBit, finBit,
    rsvBits, opCode, payload) {

    Events.emit(this, "frameReceived", {
      webSocketSerialID: webSocketSerialID,
      maskBit: maskBit,
      finBit: finBit,
      rsvBits: rsvBits,
      opCode: opCode,
      payload: payload
    });
  },

  frameSent: function(webSocketSerialID, header, payload) {

    Events.emit(this, "frameSent", {
      webSocketSerialID: webSocketSerialID,
      header: header,
      payload: payload
    });
  }
});

// Helpers

function getInnerId(win) {
  return win.top.QueryInterface(Ci.nsIInterfaceRequestor).
    getInterface(Ci.nsIDOMWindowUtils).currentInnerWindowID;
}

/**
 * TODO: docs
 */
var WsActorFront = FrontClass(WsActor, {
  initialize: function(client, form) {
    Front.prototype.initialize.call(this, client, form);

    this.actorID = form[WsActor.prototype.typeName];
    this.manage(this);
  }
});

// Exports from this module
exports.WsActor = WsActor;
exports.WsActorFront = WsActorFront;
<|endoftext|>


<commit_before>define(['aura/aura'], function(aura) {

  'use strict';
  /*jshint browser: true */
  /*global describe:true, it:true, before: true, sinon: true */

  /**
   * Writes a template into the DOM
   */
  function insertTemplateHelper (name, contents) {
    return function () {
      var elt = document.createElement('script');
      elt.id = "test_template";
      elt.type = "text/whatever";
      elt.setAttribute("data-hull-template", name);
      elt.innerHTML = contents;
      document.body.appendChild(elt);
    };
  }

  describe("Template loader", function() {
    var env;
    var app = aura();

    var extension = {
      initialize: function (appEnv) {
        env = appEnv;
      }
    };

    app
      .use(extension)
      .use("aura-extensions/aura-handlebars")
      .use('lib/client/templates');

    var initStatus = app.start();

    // Make sure the app is started before...
    before(function(done) {
      initStatus.then(done.bind(null, null));
    });

    describe("Check the correct loading of the module", function() {
      it("Should be available in the environment", function() {
        env.core.template.should.be.a('object');
      });

      it("should contain a load function", function () {
        env.core.template.load.should.be.a("function");
      });
    });

    describe("Error management", function () {
      it("should fail the promise", function (done) {
        var tplName = "doesNotExist";
        var prefix = "test";
        var ret = env.core.template.load(tplName, prefix);
        var spy = sinon.spy(done.bind(null, null));
        ret.fail(spy);
      });
    });

    describe("DOM loading", function () {
      var tplName = "tpl1";
      var prefix = "DOM";
      var hullTemplateName = prefix + "/" + tplName;
      var templateContents = "Woow, what a template!";

      before(insertTemplateHelper(hullTemplateName, templateContents));

      it("should contain the template as the return value of the promise", function (done) {
        var ret = env.core.template.load(tplName, prefix);
        var spy = sinon.spy(function (ret) {
          ret.should.contain.keys('tpl1');
          ret.tpl1.should.be.a('function');
          ret.tpl1().should.equal(templateContents);
          done();
        });
        ret.done(spy);
      });
    });

    describe("Server loading", function () {
      it("should use require to fetch the necessary templates", function (done) {
        var ret = env.core.template.load('test', 'fixtures');
        var spy = sinon.spy(done.bind(null, null));
        ret.done(spy);
        ret.done(function (tpls) {
          arguments.should.have.length(1);
          tpls.should.be.a('object');
          tpls.should.have.key('test');
          tpls.test.should.be.a('function');
        });
      });
    });

    describe("Order of precedence", function () {
      var tplContents = "That's a DOM template!";
      before(insertTemplateHelper('fixtures/test1', tplContents));

      it("should prefer DOM over server-template", function () {
        var ret = env.core.template.load('test1', 'fixtures');
        ret.done(function (tpls) {
          tpls.should.have.keys('test1');
          tpls.test1.should.be.a('function');
          tpls.test1().should.equal(tplContents);
        });
      });
    });

    describe("Multiple template loading", function () {
      before(insertTemplateHelper("multiple/tpl1", "First template"));
      before(insertTemplateHelper("multiple/tpl2", "Second template"));

      it("should load an array of templates", function () {
        var ret = env.core.template.load(["tpl1", "tpl2"], "multiple");
        ret.done(function (tpls) {
          tpls.should.contain.keys("tpl1");
          tpls.should.contain.keys("tpl2");
        });
      });
    });
  });
});
<commit_msg>Fixes specs<commit_after>define(['aura/aura'], function(aura) {

  'use strict';
  /*jshint browser: true */
  /*global describe:true, it:true, before: true, sinon: true */

  /**
   * Writes a template into the DOM
   */
  function insertTemplateHelper (name, contents) {
    return function () {
      var elt = document.createElement('script');
      elt.id = "test_template";
      elt.type = "text/whatever";
      elt.setAttribute("data-hull-template", name);
      elt.innerHTML = contents;
      document.body.appendChild(elt);
    };
  }

  describe("Template loader", function() {
    var env;
    var app = aura();

    var extension = {
      initialize: function (appEnv) {
        env = appEnv;
      }
    };

    app
      .use(extension)
      .use("aura-extensions/aura-handlebars")
      .use('lib/client/templates');

    var initStatus = app.start();

    // Make sure the app is started before...
    before(function(done) {
      initStatus.then(done.bind(null, null));
    });

    describe("Check the correct loading of the module", function() {
      it("Should be available in the environment", function() {
        env.core.template.should.be.a('object');
      });

      it("should contain a load function", function () {
        env.core.template.load.should.be.a("function");
      });
    });

    describe("Error management", function () {
      it("should fail the promise", function (done) {
        var tplName = "doesNotExist";
        var prefix = "test";
        var ret = env.core.template.load(tplName, prefix);
        ret.fail(function () {
          done();
        });
        ret.then(function () {
          done(new Error('Should not have been called.'));
        });
      });
    });

    describe("DOM loading", function () {
      var tplName = "tpl1";
      var prefix = "DOM";
      var hullTemplateName = prefix + "/" + tplName;
      var templateContents = "Woow, what a template!";

      before(insertTemplateHelper(hullTemplateName, templateContents));

      it("should contain the template as the return value of the promise", function (done) {
        var ret = env.core.template.load(tplName, prefix);
        var spy = sinon.spy(function (ret) {
          ret.should.contain.keys('tpl1');
          ret.tpl1.should.be.a('function');
          ret.tpl1().should.equal(templateContents);
          done();
        });
        ret.done(spy);
      });
    });

    describe("Server loading", function () {
      it("should use require to fetch the necessary templates", function (done) {
        var ret = env.core.template.load('test', 'fixtures');
        var spy = sinon.spy(done.bind(null, null));
        ret.done(spy);
        ret.done(function (tpls) {
          arguments.should.have.length(1);
          tpls.should.be.a('object');
          tpls.should.have.key('test');
          tpls.test.should.be.a('function');
        });
      });
    });

    describe("Order of precedence", function () {
      var tplContents = "That's a DOM template!";
      before(insertTemplateHelper('fixtures/test1', tplContents));

      it("should prefer DOM over server-template", function () {
        var ret = env.core.template.load('test1', 'fixtures');
        ret.done(function (tpls) {
          tpls.should.have.keys('test1');
          tpls.test1.should.be.a('function');
          tpls.test1().should.equal(tplContents);
        });
      });
    });

    describe("Multiple template loading", function () {
      before(insertTemplateHelper("multiple/tpl1", "First template"));
      before(insertTemplateHelper("multiple/tpl2", "Second template"));

      it("should load an array of templates", function () {
        var ret = env.core.template.load(["tpl1", "tpl2"], "multiple");
        ret.done(function (tpls) {
          tpls.should.contain.keys("tpl1");
          tpls.should.contain.keys("tpl2");
        });
      });
    });
  });
});
<|endoftext|>