<commit_before>/**
 *  This file is part of PerSE. PerSE is a visual analytics app for
 *  event periodicity detection and analysis.
 *  Copyright (C) 2015  Brian Swedberg
 */

define([
    'jquery',
    'd3',
    'perattrs/numericalplotdatasetbuilder',
    // no namespace
    'bootstrap'
], function ($, d3, numericalplotdatasetbuilder) {

    var numericalplot = {};

    numericalplot.NumericalPlot = function (attribute) {
        this.attribute = attribute;
        this.contentAttribute = undefined;
        this.container = $('<div>').attr({'class': 'perse-perattr-numericalplot'});
        this.listeners = [];
        this.svg = undefined;
        this.margin = {top: 10, right: 5, bottom: 10, left: 15};
        this.viewBox = {width: 100, height: 140};
        this.xScale = undefined;
        this.yScale = undefined;
        this.brush = undefined;
        this.size = {
            width: this.viewBox.width - this.margin.left - this.margin.right,
            height: this.viewBox.height - this.margin.top - this.margin.bottom
        };
        this.metadata = undefined;
    };

    numericalplot.NumericalPlot.prototype.render = function (parent) {
        $(parent).append(this.container);
        return this;
    };

    numericalplot.NumericalPlot.prototype.createToolbar = function () {
        var filterDiv = $('<div>')
            .attr({'class': 'btn-group', 'role': 'group'})
            .append(this.createFilterButton());
        return $('<div>')
            .attr({'class': 'btn-toolbar perse-header-toolbar', 'role': 'toolbar'})
            .append(filterDiv);
    };

    numericalplot.NumericalPlot.prototype.createFilterButton = function () {
        var filterIcon = $('<span>')
                .attr({'class': 'glyphicon glyphicon-filter', 'aria-hidden': 'true'}),
            filterButton = $('<button>')
                .attr({'class': 'btn btn-default btn-xs', 'type': 'button', 'title': 'Reset Filter'})
                .append(filterIcon);

        filterButton.on('mouseup', $.proxy(function () {
            $(filterButton).blur();
            this.onReset();
            this.notifyListeners('onPlotSelectionChanged', {context: this, filter: this.getFilter()});
        }, this));

        return filterButton;
    };

    numericalplot.NumericalPlot.prototype.build = function (data) {
        var xExtent = this.getXExtent(data);

        this.svg = d3.select(this.container.get(0)).append('svg')
            .attr('viewBox', [0, 0, this.viewBox.width, this.viewBox.height].join(' '))
            .append('g')
            .attr('transform', 'translate(' + this.margin.left + ',' + this.margin.top + ')');

        this.xScale = d3.scale.linear()
            .domain([xExtent.min, xExtent.max])
            .range([0, this.size.width]);

        this.update(data);
        this.buildBrush();

    };

    numericalplot.NumericalPlot.prototype.update = function (data) {
        var that = this,
            yExtent = this.getYExtent(data),
            xExtent = this.getXExtent(data),
            bars;
        console.log(xExtent);
        this.xScale = d3.scale.linear()
            .domain([xExtent.min, xExtent.max])
            .range([0, this.size.width]);

        this.yScale = d3.scale.linear()
            .domain([yExtent.min, yExtent.max])
            .range([this.size.height, 0]);

        if (this.brush !== undefined) {
            this.brush.x(this.xScale);
            this.svg.select('.brush').call(this.brush.clear());
        }

        bars = this.svg.selectAll('.numericalplot-bin')
            .data(data);

        bars.enter().append('g')
            .attr('class', 'numericalplot-bin selected');

        bars.each(function () {
            var g = d3.select(this),
                gData = g.datum(),
                rects,
                barWidth = (gData.dx === 0) ? that.size.width : that.xScale(gData.x + gData.dx) - that.xScale(gData.x);

            rects = g.selectAll('rect')
                .data(gData.events);

            rects.enter().append('rect');

            rects
                .transition()
                .duration(500)
                .attr('fill', function (d) {
                    return d.color;
                })
                .attr('x', 0)
                .attr('y', function (d) {
                    return that.yScale(d.count.end);
                })
                .attr('width', barWidth)
                .attr('height', function (d) {
                    return that.yScale(d.count.begin) - that.yScale(d.count.end);
                });

            rects.exit().remove();

        });

        bars.attr('transform', function (d) {
            console.log(d);
            return 'translate(' + that.xScale(d.x) + ',0)';
        });

        bars.exit().remove();

        this.updateAxis();
    };

    numericalplot.NumericalPlot.prototype.updateAxis = function () {
        var xAxisBuilder, yAxisBuilder;
        xAxisBuilder = d3.svg.axis()
            .scale(this.xScale)
            .ticks(5)
            .innerTickSize(2)
            .outerTickSize(2)
            .tickPadding(2)
            .orient('bottom');

        yAxisBuilder = d3.svg.axis()
            .scale(this.yScale)
            .innerTickSize(2)
            .outerTickSize(2)
            .tickPadding(2)
            .tickFormat(function (d) {
                var prefix = d3.formatPrefix(d);
                return (d >= 1000) ? prefix.scale(d) + prefix.symbol : d;
            })
            .orient('left');

        this.svg.selectAll('.numericalplot-axis').remove();
        this.svg.append('g')
            .attr('class', 'numericalplot-axis')
            .attr('transform', 'translate(0,' + (this.size.height + 1) + ')')
            .call(xAxisBuilder);

        this.svg.append('g')
            .attr('class', 'numericalplot-axis')
            .attr('transform', 'translate(-1,0)')
            .call(yAxisBuilder);
    };

    numericalplot.NumericalPlot.prototype.buildBrush = function () {
        var that = this, brushMove, brushEnd, brushG;

        this.svg
            .on('mousemove', function () {
                var x = d3.mouse(that.svg.node())[0];
                if (x >= 0) {
                    that.updateLabel('Frequency: ' + Math.round(that.xScale.invert(d3.mouse(that.svg.node())[0])));
                } else {
                    that.updateLabel('');
                }
            })
            .on('mouseout', function () {
                that.updateLabel('');
            });

        brushMove = function () {
            var bExtent = that.brush.extent();
            that.updateLabel('Frequency: ' + Math.round(bExtent[0]) + ' to ' + Math.round(bExtent[1]));
        };

        brushEnd = function () {
            that.notifyListeners('onPlotSelectionChanged', {context: that});
        };

        this.brush = d3.svg.brush()
            .x(this.xScale)
            .on('brush', brushMove)
            .on('brushend', brushEnd);

        brushG = this.svg.insert('g', '.numericalplot-bin')
            .attr('class', 'brush')
            .call(this.brush);

        brushG.selectAll("rect")
            .attr("height", this.size.height);

        this.svg.append('text')
            .attr('id', 'numericalplot-label');
    };

    numericalplot.NumericalPlot.prototype.updateLabel = function (label) {
        var labelNode = this.svg.select('#numericalplot-label')
                .text(label),
            bbox = labelNode.node().getBBox();
        labelNode
            .attr('x', this.size.width - bbox.width)
            .attr('y', -3);
    };

    numericalplot.NumericalPlot.prototype.clearBrush = function () {
        this.svg.selectAll('.brush').call(this.brush.clear());
    };

    numericalplot.NumericalPlot.prototype.getXExtent = function (data) {
        console.log(data);
        return {
            min: data[0].x,
            max: data[data.length - 1].x + data[data.length - 1].dx
        };
    };

    numericalplot.NumericalPlot.prototype.getYExtent = function (data) {
        var firstValue = (data.length === 0) ? 0 : data[0].events[data[0].events.length - 1].count.end,
            extent = {min: 0, max: firstValue};
        return data.reduce(function (p, c) {
            var aggMax = c.events[c.events.length - 1].count.end;
            p.max = Math.max(extent.max, aggMax);
            return p;
        }, extent);
    };

    numericalplot.NumericalPlot.prototype.getFilter = function () {
        var brushExtent = this.brush.extent();
        if (brushExtent[0] === brushExtent[1]) {
            return function () {return true; };
        }
        return function (d) {
            return (d >= brushExtent[0] && d <= brushExtent[1]);
        };
    };

    numericalplot.NumericalPlot.prototype.processData = function (data) {
        return new numericalplotdatasetbuilder.NumericalPlotDataSetBuilder()
            .setMetadata(this.metadata)
            .setData(data)
            .setContentAttribute(this.contentAttribute)
            .setAttribute(this.attribute)
            .build();
    };

    numericalplot.NumericalPlot.prototype.setContentAttribute = function (contentAttr) {
        this.contentAttribute = contentAttr;
    };

    numericalplot.NumericalPlot.prototype.onReset = function () {
        this.clearBrush();
    };

    numericalplot.NumericalPlot.prototype.onSelectionChanged = function (data) {
        this.update(this.processData(data));
    };

    numericalplot.NumericalPlot.prototype.onDataSetChanged = function (data, metadata) {
        this.metadata = metadata;
        this.build(this.processData(data));
    };

    numericalplot.NumericalPlot.prototype.registerListener = function (listenerObj) {
        this.listeners.push(listenerObj);
        return this;
    };

    numericalplot.NumericalPlot.prototype.notifyListeners = function (callbackStr, event) {
        this.listeners.forEach(function (listenerObj) {
            listenerObj[callbackStr].call(listenerObj.context, event);
        });
    };

    return numericalplot;

});<commit_msg>remove console.logs<commit_after>/**
 *  This file is part of PerSE. PerSE is a visual analytics app for
 *  event periodicity detection and analysis.
 *  Copyright (C) 2015  Brian Swedberg
 */

define([
    'jquery',
    'd3',
    'perattrs/numericalplotdatasetbuilder',
    // no namespace
    'bootstrap'
], function ($, d3, numericalplotdatasetbuilder) {

    var numericalplot = {};

    numericalplot.NumericalPlot = function (attribute) {
        this.attribute = attribute;
        this.contentAttribute = undefined;
        this.container = $('<div>').attr({'class': 'perse-perattr-numericalplot'});
        this.listeners = [];
        this.svg = undefined;
        this.margin = {top: 10, right: 5, bottom: 10, left: 15};
        this.viewBox = {width: 100, height: 140};
        this.xScale = undefined;
        this.yScale = undefined;
        this.brush = undefined;
        this.size = {
            width: this.viewBox.width - this.margin.left - this.margin.right,
            height: this.viewBox.height - this.margin.top - this.margin.bottom
        };
        this.metadata = undefined;
    };

    numericalplot.NumericalPlot.prototype.render = function (parent) {
        $(parent).append(this.container);
        return this;
    };

    numericalplot.NumericalPlot.prototype.createToolbar = function () {
        var filterDiv = $('<div>')
            .attr({'class': 'btn-group', 'role': 'group'})
            .append(this.createFilterButton());
        return $('<div>')
            .attr({'class': 'btn-toolbar perse-header-toolbar', 'role': 'toolbar'})
            .append(filterDiv);
    };

    numericalplot.NumericalPlot.prototype.createFilterButton = function () {
        var filterIcon = $('<span>')
                .attr({'class': 'glyphicon glyphicon-filter', 'aria-hidden': 'true'}),
            filterButton = $('<button>')
                .attr({'class': 'btn btn-default btn-xs', 'type': 'button', 'title': 'Reset Filter'})
                .append(filterIcon);

        filterButton.on('mouseup', $.proxy(function () {
            $(filterButton).blur();
            this.onReset();
            this.notifyListeners('onPlotSelectionChanged', {context: this, filter: this.getFilter()});
        }, this));

        return filterButton;
    };

    numericalplot.NumericalPlot.prototype.build = function (data) {
        var xExtent = this.getXExtent(data);

        this.svg = d3.select(this.container.get(0)).append('svg')
            .attr('viewBox', [0, 0, this.viewBox.width, this.viewBox.height].join(' '))
            .append('g')
            .attr('transform', 'translate(' + this.margin.left + ',' + this.margin.top + ')');

        this.xScale = d3.scale.linear()
            .domain([xExtent.min, xExtent.max])
            .range([0, this.size.width]);

        this.update(data);
        this.buildBrush();

    };

    numericalplot.NumericalPlot.prototype.update = function (data) {
        var that = this,
            yExtent = this.getYExtent(data),
            xExtent = this.getXExtent(data),
            bars;
        console.log(xExtent);
        this.xScale = d3.scale.linear()
            .domain([xExtent.min, xExtent.max])
            .range([0, this.size.width]);

        this.yScale = d3.scale.linear()
            .domain([yExtent.min, yExtent.max])
            .range([this.size.height, 0]);

        if (this.brush !== undefined) {
            this.brush.x(this.xScale);
            this.svg.select('.brush').call(this.brush.clear());
        }

        bars = this.svg.selectAll('.numericalplot-bin')
            .data(data);

        bars.enter().append('g')
            .attr('class', 'numericalplot-bin selected');

        bars.each(function () {
            var g = d3.select(this),
                gData = g.datum(),
                rects,
                barWidth = (gData.dx === 0) ? that.size.width : that.xScale(gData.x + gData.dx) - that.xScale(gData.x);

            rects = g.selectAll('rect')
                .data(gData.events);

            rects.enter().append('rect');

            rects
                .transition()
                .duration(500)
                .attr('fill', function (d) {
                    return d.color;
                })
                .attr('x', 0)
                .attr('y', function (d) {
                    return that.yScale(d.count.end);
                })
                .attr('width', barWidth)
                .attr('height', function (d) {
                    return that.yScale(d.count.begin) - that.yScale(d.count.end);
                });

            rects.exit().remove();

        });

        bars.attr('transform', function (d) {
            return 'translate(' + that.xScale(d.x) + ',0)';
        });

        bars.exit().remove();

        this.updateAxis();
    };

    numericalplot.NumericalPlot.prototype.updateAxis = function () {
        var xAxisBuilder, yAxisBuilder;
        xAxisBuilder = d3.svg.axis()
            .scale(this.xScale)
            .ticks(5)
            .innerTickSize(2)
            .outerTickSize(2)
            .tickPadding(2)
            .orient('bottom');

        yAxisBuilder = d3.svg.axis()
            .scale(this.yScale)
            .innerTickSize(2)
            .outerTickSize(2)
            .tickPadding(2)
            .tickFormat(function (d) {
                var prefix = d3.formatPrefix(d);
                return (d >= 1000) ? prefix.scale(d) + prefix.symbol : d;
            })
            .orient('left');

        this.svg.selectAll('.numericalplot-axis').remove();
        this.svg.append('g')
            .attr('class', 'numericalplot-axis')
            .attr('transform', 'translate(0,' + (this.size.height + 1) + ')')
            .call(xAxisBuilder);

        this.svg.append('g')
            .attr('class', 'numericalplot-axis')
            .attr('transform', 'translate(-1,0)')
            .call(yAxisBuilder);
    };

    numericalplot.NumericalPlot.prototype.buildBrush = function () {
        var that = this, brushMove, brushEnd, brushG;

        this.svg
            .on('mousemove', function () {
                var x = d3.mouse(that.svg.node())[0];
                if (x >= 0) {
                    that.updateLabel('Frequency: ' + Math.round(that.xScale.invert(d3.mouse(that.svg.node())[0])));
                } else {
                    that.updateLabel('');
                }
            })
            .on('mouseout', function () {
                that.updateLabel('');
            });

        brushMove = function () {
            var bExtent = that.brush.extent();
            that.updateLabel('Frequency: ' + Math.round(bExtent[0]) + ' to ' + Math.round(bExtent[1]));
        };

        brushEnd = function () {
            that.notifyListeners('onPlotSelectionChanged', {context: that});
        };

        this.brush = d3.svg.brush()
            .x(this.xScale)
            .on('brush', brushMove)
            .on('brushend', brushEnd);

        brushG = this.svg.insert('g', '.numericalplot-bin')
            .attr('class', 'brush')
            .call(this.brush);

        brushG.selectAll("rect")
            .attr("height", this.size.height);

        this.svg.append('text')
            .attr('id', 'numericalplot-label');
    };

    numericalplot.NumericalPlot.prototype.updateLabel = function (label) {
        var labelNode = this.svg.select('#numericalplot-label')
                .text(label),
            bbox = labelNode.node().getBBox();
        labelNode
            .attr('x', this.size.width - bbox.width)
            .attr('y', -3);
    };

    numericalplot.NumericalPlot.prototype.clearBrush = function () {
        this.svg.selectAll('.brush').call(this.brush.clear());
    };

    numericalplot.NumericalPlot.prototype.getXExtent = function (data) {
        return {
            min: data[0].x,
            max: data[data.length - 1].x + data[data.length - 1].dx
        };
    };

    numericalplot.NumericalPlot.prototype.getYExtent = function (data) {
        var firstValue = (data.length === 0) ? 0 : data[0].events[data[0].events.length - 1].count.end,
            extent = {min: 0, max: firstValue};
        return data.reduce(function (p, c) {
            var aggMax = c.events[c.events.length - 1].count.end;
            p.max = Math.max(extent.max, aggMax);
            return p;
        }, extent);
    };

    numericalplot.NumericalPlot.prototype.getFilter = function () {
        var brushExtent = this.brush.extent();
        if (brushExtent[0] === brushExtent[1]) {
            return function () {return true; };
        }
        return function (d) {
            return (d >= brushExtent[0] && d <= brushExtent[1]);
        };
    };

    numericalplot.NumericalPlot.prototype.processData = function (data) {
        return new numericalplotdatasetbuilder.NumericalPlotDataSetBuilder()
            .setMetadata(this.metadata)
            .setData(data)
            .setContentAttribute(this.contentAttribute)
            .setAttribute(this.attribute)
            .build();
    };

    numericalplot.NumericalPlot.prototype.setContentAttribute = function (contentAttr) {
        this.contentAttribute = contentAttr;
    };

    numericalplot.NumericalPlot.prototype.onReset = function () {
        this.clearBrush();
    };

    numericalplot.NumericalPlot.prototype.onSelectionChanged = function (data) {
        this.update(this.processData(data));
    };

    numericalplot.NumericalPlot.prototype.onDataSetChanged = function (data, metadata) {
        this.metadata = metadata;
        this.build(this.processData(data));
    };

    numericalplot.NumericalPlot.prototype.registerListener = function (listenerObj) {
        this.listeners.push(listenerObj);
        return this;
    };

    numericalplot.NumericalPlot.prototype.notifyListeners = function (callbackStr, event) {
        this.listeners.forEach(function (listenerObj) {
            listenerObj[callbackStr].call(listenerObj.context, event);
        });
    };

    return numericalplot;

});<|endoftext|>


<commit_before>var Table = function(name) {
	this._name = name;
}

Table.prototype.select = function() {
	var q = new Query(Query.SELECT);
	q.table(this._name);
	for (var i=0;i<arguments.length;i++) {
		q.field(arguments[i]);
	}
	return q;
}

Table.prototype.insert = function(values) {
	var q = new Query(Query.INSERT);
	q.table(this._name);
	for (var name in values) {
		var value = values[name];
		q.field(name);
		q.value(value);
	}
	return q;
}

Table.prototype.update = function(values) {
	var q = new Query(Query.UPDATE);
	q.table(this._name);
	for (var name in values) {
		var value = values[name];
		q.field(name);
		q.value(value);
	}
	return q;
}

Table.prototype.delete = function(values) {
	var q = new Query(Query.DELETE);
	q.table(this._name);
	return q;
}

var Query = function(type) {
	this._type = type;
	this._table = [];
	this._field = [];
	this._value = [];
	this._where = [];
	this._order = [];
	this._limit = null;
	this._offset = 0;
	this._group = [];
	this._having = [];
}

Query.SELECT = 0;
Query.INSERT = 1;
Query.UPDATE = 2;
Query.DELETE = 3;
Query._relations = [];
Query._db = null;

Query.setDB = function(db) {
	this._db = db;
}

Query.addRelation = function(t1,f1,t2,f2) {
	this._relations.push([t1,f1,t2,f2]);
}

Query.findRelation = function(t1, t2, joinfield) {
	for (var i=0;i<this._relations.length;i++) {
		var rel = this._relations[i];
		if (rel[0] != t1 && rel[0] != t2 && rel[2] != t1 && rel[2] != t2) { continue; }
		if (joinfield && joinfield != rel[1] && joinfield != rel[3]) { continue; }
		return rel;
	}
	return null;
}

Query.prototype.table = function(name, jointype, joinfield) {
	var obj = {
	    name:name,
	    jointype:jointype,
	    joinfield:joinfield
	}
	this._table.push(obj);
	return this;
}

Query.prototype.join = Query.prototype.table;

Query.prototype.field = function(fieldDef) {
	var str = "";
	if (arguments.length == 1) {
		str = this._qualify(fieldDef);
	} else {
		str = this._expand.apply(this, arguments);
	}
	this._field.push(str);
	return this;
}

Query.prototype.value = function(value, noescape) {
	var val = value;
	if (!noescape) { val = "'" + this._escape(val)+ "'"; }
	this._value.push(val);
	return this;
}

Query.prototype.where = function(conditionDef) {
	this._where.push(this._expand.apply(this, arguments));
	return this;
}

Query.prototype.order = function(fieldDef, mode) {
	var arr = [];
	for (var i=0;i<arguments.length;i++) {
		if (i != 1) { arr.push(arguments[i]); }
	}
	var str = this._expand.apply(this, arr) + " " + (mode || "ASC");
	this._order.push(str);
	return this;
}

Query.prototype.limit = function(limit) {
	this._limit = limit;
	return this;
}

Query.prototype.offset = function(offset) {
	this._offset = offset;
	return this;
}

Query.prototype.group = function(field) {
	this._group.push(this._qualify(field));
	return this;
}

Query.prototype.having = function(conditionDef) {
	this._where.push(this._expand.apply(this, arguments));
	return this;
}

Query.prototype.toString = function() {
	if (!this._field.length) { this.field("*"); }
	switch (this._type) {
		case Query.SELECT: return this._toStringSelect();
		case Query.INSERT: return this._toStringInsert();
		case Query.UPDATE: return this._toStringUpdate();
		case Query.DELETE: return this._toStringDelete();
		default: return false;
	}
}

Query.prototype.execute = function() {
	var str = this.toString();
	return Query._db.query(str);
}

Query.prototype._toStringSelect = function() {
	var arr = [];
	arr.push("SELECT");
	arr.push(this._toStringField());
	arr.push(this._toStringTable());
	arr.push(this._toStringWhere());
	arr.push(this._toStringGroup());
	arr.push(this._toStringHaving());
	arr.push(this._toStringOrder());
	arr.push(this._toStringLimit());
	arr.push(this._toStringOffset());
	return arr.join(" ");
}

Query.prototype._toStringInsert = function() {
	var arr = [];
	arr.push("INSERT");
	arr.push(this._toStringTable());
	arr.push(this._toStringField());
	return arr.join(" ");
}

Query.prototype._toStringUpdate = function() {
	var arr = [];
	arr.push("UPDATE");
	arr.push(this._toStringTable());
	arr.push(this._toStringField());
	arr.push(this._toStringWhere());
	arr.push(this._toStringOrder());
	arr.push(this._toStringLimit());
	arr.push(this._toStringOffset());
	return arr.join(" ");
}

Query.prototype._toStringDelete = function() {
	var arr = [];
	arr.push("DELETE");
	arr.push(this._toStringTable());
	arr.push(this._toStringWhere());
	arr.push(this._toStringOrder());
	arr.push(this._toStringLimit());
	arr.push(this._toStringOffset());
	return arr.join(" ");
}

Query.prototype._toStringOffset = function() {
	return (this._offset ? "OFFSET "+this._offset : "");
}

Query.prototype._toStringLimit = function() {
	return (this._limit !== null ? "LIMIT "+this._limit : "");
}

Query.prototype._toStringOrder = function() {
	return (this._order.length ? "ORDER BY "+this._order.join(", ") : "");
}

Query.prototype._toStringHaving = function() {
	var str = "";
	if (this._having.length) {
		str += "HAVING "+this._having.join(" ");
	}
	return str;
}

Query.prototype._toStringWhere = function() {
	var str = "";
	if (this._where.length) {
		str += "WHERE "+this._where.join(" ");
	}
	return str;
}

Query.prototype._toStringGroup = function() {
	return this._group.join(", ");
}

Query.prototype._toStringTable = function() {
	var cache = {};
	switch (this._type) {
		case Query.SELECT:
			var arr = [];
			for (var i=0;i<this._table.length;i++) {
				var item = this._table[i];
				var name = item.name;
				if (name in cache) {
					cache[name]++;
				} else {
					cache[name] = 1;
				}
				var alias = this._qualify(name+"#"+cache[name]);
				var full = this._qualify(name) + " AS "+alias;

				if (!i) {
					arr.push(full);
				} else {
					var str = "";
					if (item.jointype) { str += item.jointype+" "; }
					str += "JOIN "+full;

					var rel = false;
					for (var j=0;j<i;j++) {
						var t2 = this._table[j].name;
						rel = rel || Query.findRelation(name, t2, item.joinfield);
					}
					if (rel) {
						var tmp1 = rel[0] + "#" + cache[rel[0]] + "." + rel[1];
						var tmp2 = rel[2] + "#" + cache[rel[2]] + "." + rel[3];
						str += " ON "+this._qualify(tmp1)+" = "+this._qualify(tmp2);
					}
					arr.push(str);
				}
			}
			return " FROM "+arr.join(" ");
		break;

		case Query.INSERT:
			return " INTO "+this._qualify(this._table[0].name);
		break;

		case Query.UPDATE:
			return " "+this._qualify(this._table[0].name);
		break;

		case Query.DELETE:
			return " FROM "+this._qualify(this._table[0].name);
		break;
	}
}

Query.prototype._toStringField = function() {
	switch (this._type) {
		case Query.SELECT:
			return this._field.join(", ");
		break;

		case Query.INSERT:
			return "("+this._field.join(", ")+") VALUES ("+this._value.join(", ")+")";
		break;

		case Query.UPDATE:
			var arr = [];
			for (var i=0;i<this._field.length;i++) {
				arr.push(this._field[i]+"="+this._value[i]);
			}
			return "SET "+arr.join(", ");
		break;
	}
}

Query.prototype._qualify = function(str) {
	var parts = str.split(".");
	var arr = [];
	for (var i=0;i<parts.length;i++) {
		var val = parts[i];
		arr.push(val == "*" ? val : Query._db.qualify(val));
	}
	return arr.join(".");
}

Query.prototype._escape = function(str) {
	return Query._db.escape(str);
}

Query.prototype._expand = function(str) {
	if (arguments.length == 1) { return str; }
	var s = "";
	var argptr = 1;
	var index = 0;
	var start = false;

	while (index < str.length) {
		var ch = str.charAt(index);
		switch (ch) {
			case "%":
				start = !start;
				if (!start) { s += ch; }
			break;

			case "f":
				if (start) {
					start = false;
					s += this._qualify(arguments[argptr++]);
				} else {
					s += ch;
				}
			break;

			case "s":
				if (start) {
					start = false;
					s += "'"+this._escape(arguments[argptr++])+"'";
				} else {
					s += ch;
				}
			break;

			default:
				s += ch;
			break;
		}
		index++;
	}
	return s;
}
<commit_msg>new query.js<commit_after>var Table = function(name) {
	this._name = name;
}

Table.prototype.select = function() {
	var q = new Query(Query.SELECT);
	q.table(this._name);
	for (var i=0;i<arguments.length;i++) {
		q.field(arguments[i]);
	}
	return q;
}

Table.prototype.insert = function(values) {
	var q = new Query(Query.INSERT);
	q.table(this._name);
	for (var name in values) {
		var value = values[name];
		q.field(name);
		q.value(value);
	}
	return q;
}

Table.prototype.update = function(values) {
	var q = new Query(Query.UPDATE);
	q.table(this._name);
	for (var name in values) {
		var value = values[name];
		q.field(name);
		q.value(value);
	}
	return q;
}

Table.prototype.delete = function(values) {
	var q = new Query(Query.DELETE);
	q.table(this._name);
	return q;
}

var Query = function(type) {
	this._type = type;
	this._table = [];
	this._field = [];
	this._value = [];
	this._where = [];
	this._order = [];
	this._limit = null;
	this._offset = 0;
	this._group = [];
	this._having = [];
}

Query.SELECT = 0;
Query.INSERT = 1;
Query.UPDATE = 2;
Query.DELETE = 3;
Query._relations = [];
Query._db = null;

Query.setDB = function(db) {
	this._db = db;
}

Query.addRelation = function(t1,f1,t2,f2) {
	this._relations.push([t1,f1,t2,f2]);
}

Query.findRelation = function(t1, t2, joinfield) {
	for (var i=0;i<this._relations.length;i++) {
		var rel = this._relations[i];
		if (rel[0] != t1 && rel[0] != t2 && rel[2] != t1 && rel[2] != t2) { continue; }
		if (joinfield && joinfield != rel[1] && joinfield != rel[3]) { continue; }
		return rel;
	}
	return null;
}

Query.prototype.table = function(name, jointype, joinfield) {
	var obj = {
	    name:name,
	    jointype:jointype,
	    joinfield:joinfield
	}
	this._table.push(obj);
	return this;
}

Query.prototype.join = Query.prototype.table;

Query.prototype.field = function(fieldDef) {
	var str = "";
	if (arguments.length == 1) {
		str = this._qualify(fieldDef);
	} else {
		str = this._expand.apply(this, arguments);
	}
	this._field.push(str);
	return this;
}

Query.prototype.value = function(value, noescape) {
	var val = value;
	if (!noescape) { val = "'" + this._escape(val)+ "'"; }
	this._value.push(val);
	return this;
}

Query.prototype.where = function(conditionDef) {
	this._where.push(this._expand.apply(this, arguments));
	return this;
}

Query.prototype.order = function(fieldDef) {
	this._order.push(this._expand.apply(this, arguments));
	return this;
}

Query.prototype.limit = function(limit) {
	this._limit = limit;
	return this;
}

Query.prototype.offset = function(offset) {
	this._offset = offset;
	return this;
}

Query.prototype.group = function(field) {
	this._group.push(this._qualify(field));
	return this;
}

Query.prototype.having = function(conditionDef) {
	this._where.push(this._expand.apply(this, arguments));
	return this;
}

Query.prototype.toString = function() {
	if (!this._field.length) { this.field("*"); }
	switch (this._type) {
		case Query.SELECT: return this._toStringSelect();
		case Query.INSERT: return this._toStringInsert();
		case Query.UPDATE: return this._toStringUpdate();
		case Query.DELETE: return this._toStringDelete();
		default: return false;
	}
}

Query.prototype.execute = function() {
	var str = this.toString();
	return Query._db.query(str);
}

Query.prototype._toStringSelect = function() {
	var arr = [];
	arr.push("SELECT");
	arr.push(this._toStringField());
	arr.push(this._toStringTable());
	arr.push(this._toStringWhere());
	arr.push(this._toStringGroup());
	arr.push(this._toStringHaving());
	arr.push(this._toStringOrder());
	arr.push(this._toStringLimit());
	arr.push(this._toStringOffset());
	return arr.join(" ");
}

Query.prototype._toStringInsert = function() {
	var arr = [];
	arr.push("INSERT");
	arr.push(this._toStringTable());
	arr.push(this._toStringField());
	return arr.join(" ");
}

Query.prototype._toStringUpdate = function() {
	var arr = [];
	arr.push("UPDATE");
	arr.push(this._toStringTable());
	arr.push(this._toStringField());
	arr.push(this._toStringWhere());
	arr.push(this._toStringOrder());
	arr.push(this._toStringLimit());
	arr.push(this._toStringOffset());
	return arr.join(" ");
}

Query.prototype._toStringDelete = function() {
	var arr = [];
	arr.push("DELETE");
	arr.push(this._toStringTable());
	arr.push(this._toStringWhere());
	arr.push(this._toStringOrder());
	arr.push(this._toStringLimit());
	arr.push(this._toStringOffset());
	return arr.join(" ");
}

Query.prototype._toStringOffset = function() {
	return (this._offset ? "OFFSET "+this._offset : "");
}

Query.prototype._toStringLimit = function() {
	return (this._limit !== null ? "LIMIT "+this._limit : "");
}

Query.prototype._toStringOrder = function() {
	return (this._order.length ? "ORDER BY "+this._order.join(", ") : "");
}

Query.prototype._toStringHaving = function() {
	var str = "";
	if (this._having.length) {
		str += "HAVING "+this._having.join(" ");
	}
	return str;
}

Query.prototype._toStringWhere = function() {
	var str = "";
	if (this._where.length) {
		str += "WHERE "+this._where.join(" ");
	}
	return str;
}

Query.prototype._toStringGroup = function() {
	return this._group.join(", ");
}

Query.prototype._toStringTable = function() {
	var cache = {};
	switch (this._type) {
		case Query.SELECT:
			var arr = [];
			for (var i=0;i<this._table.length;i++) {
				var item = this._table[i];
				var name = item.name;
				if (name in cache) {
					cache[name]++;
				} else {
					cache[name] = 1;
				}
				var alias = this._qualify(name+"#"+cache[name]);
				var full = this._qualify(name) + " AS "+alias;

				if (!i) {
					arr.push(full);
				} else {
					var str = "";
					if (item.jointype) { str += item.jointype+" "; }
					str += "JOIN "+full;

					var rel = false;
					for (var j=0;j<i;j++) {
						var t2 = this._table[j].name;
						rel = rel || Query.findRelation(name, t2, item.joinfield);
					}
					if (rel) {
						var tmp1 = rel[0] + "#" + cache[rel[0]] + "." + rel[1];
						var tmp2 = rel[2] + "#" + cache[rel[2]] + "." + rel[3];
						str += " ON "+this._qualify(tmp1)+" = "+this._qualify(tmp2);
					}
					arr.push(str);
				}
			}
			return " FROM "+arr.join(" ");
		break;

		case Query.INSERT:
			return " INTO "+this._qualify(this._table[0].name);
		break;

		case Query.UPDATE:
			return " "+this._qualify(this._table[0].name);
		break;

		case Query.DELETE:
			return " FROM "+this._qualify(this._table[0].name);
		break;
	}
}

Query.prototype._toStringField = function() {
	switch (this._type) {
		case Query.SELECT:
			return this._field.join(", ");
		break;

		case Query.INSERT:
			return "("+this._field.join(", ")+") VALUES ("+this._value.join(", ")+")";
		break;

		case Query.UPDATE:
			var arr = [];
			for (var i=0;i<this._field.length;i++) {
				arr.push(this._field[i]+"="+this._value[i]);
			}
			return "SET "+arr.join(", ");
		break;
	}
}

Query.prototype._qualify = function(str) {
	var parts = str.split(".");
	var arr = [];
	for (var i=0;i<parts.length;i++) {
		var val = parts[i];
		arr.push(val == "*" ? val : Query._db.qualify(val));
	}
	return arr.join(".");
}

Query.prototype._escape = function(str) {
	return Query._db.escape(str);
}

Query.prototype._expand = function(str) {
	if (arguments.length == 1) { return str; }
	var s = "";
	var argptr = 1;
	var index = 0;
	var start = false;

	while (index < str.length) {
		var ch = str.charAt(index);
		switch (ch) {
			case "%":
				start = !start;
				if (!start) { s += ch; }
			break;

			case "f":
				if (start) {
					start = false;
					s += this._qualify(arguments[argptr++]);
				} else {
					s += ch;
				}
			break;

			case "s":
				if (start) {
					start = false;
					s += "'"+this._escape(arguments[argptr++])+"'";
				} else {
					s += ch;
				}
			break;

			default:
				s += ch;
			break;
		}
		index++;
	}
	return s;
}
<|endoftext|>


<commit_before>var assert = require('assert');

function JTrace() {
  this.enabled  = false;
  this.handlers = [];
}

/*

  facets   an array of strings
           the facets of a probe should be fixed,
           and order from general to specific

  vector   an array of numbers
           the vector provides a partial ordering over the
           values of a particular probe

  values   an array of objects
           the values are opaque to the tracer,
           they are meant to be interpreted and consumed
           by the tracer requesting them

*/
JTrace.prototype.emit = function emitTrace(facets, trap) {
  this.handlers.forEach(function (item) {
    var facetMask  = item.facetMask;
    var handler    = item.handler;

    var isMatch = true;

    // can filter against facets only
    if (facetMask) isMatch = match(facetMask, facets);

    if (isMatch) handler(facets, trap());
  });
};

JTrace.prototype.on = function onTrace(facetMask, handler) {
  this.enabled = true;
  this.handlers.push({
    facetMask  : facetMask,
    handler    : handler,
  });
};

function match(pattern, value) {
  return true;
}

function Trace() {
  this.module = null;
  this.target = null;

  this.level  = 0;
}

Trace.DIR   = 001;
Trace.LOG   = 002;
Trace.INFO  = 004;
Trace.WARN  = 010;
Trace.ERROR = 020;

Trace.NONE  = 000;
Trace.ALL   = 777;

function Tracer() {
  this.jtrace = null;
  this.module = null;
  this.parent = null;
}

function _facets(tracer, array) {
  array.unshift(tracer.module);
  if (tracer.parent) return _facets(tracer.parent, array);
  else return array;
}

Tracer.prototype.trap = function (level, target, trap) {
  // shortcut when tracing is disabled
  if (!this.jtrace.enabled) return;

  // from http://goo.gl/WaH2L
  var facets = {
    module : _facets(this, []),
    target : target,
    level  : level
  };

  this.jtrace.emit(facets, trap);
};

Tracer.prototype.trace = function (level, target, value) {
  var out;

  if (typeof value === 'function') out = value;
  else out = function () { return value };

  this.trap(level, target, out);
};

Tracer.prototype.dir = function dirTrace(target, value) {
  assert(target);
  assert.equal(typeof target, 'string');

  this.trace(Trace.DIR, target, value);
};

Tracer.prototype.log = function logTrace(target, value) {
  assert(target);
  assert.equal(typeof target, 'string');

  this.trace(Trace.LOG, target, value);
};

Tracer.prototype.info = function infoTrace(target, value) {
  assert(target);
  assert.equal(typeof target, 'string');

  this.trace(Trace.INFO, target, value);
};

Tracer.prototype.warn = function warnTrace(target, value) {
  assert(target);
  assert.equal(typeof target, 'string');

  this.trace(Trace.WARN, target, value);
};

Tracer.prototype.error = function errorTrace(target, value) {
  assert(target);
  assert.equal(typeof target, 'string');

  this.trace(Trace.ERROR, target, value);
};

Tracer.prototype.segment = function segment(name) {
  var tracer = Tracer.New();

  tracer.module = name;
  tracer.parent = this;
  tracer.jtrace = this.jtrace;

  return tracer;
};

Tracer.New = function New() {
  return new Tracer();
};

Tracer.NewJTracer = function NewJTracer(jtrace) {
  var tracer = Tracer.New();

  tracer.jtrace = jtrace;
  tracer.module = '/';

  return tracer;
};

module.exports.JTrace = JTrace;
module.exports.Tracer = Tracer;
<commit_msg>early short circuit<commit_after>var assert = require('assert');

function JTrace() {
  this.enabled  = false;
  this.handlers = [];
}

/*

  facets   an array of strings
           the facets of a probe should be fixed,
           and order from general to specific

  vector   an array of numbers
           the vector provides a partial ordering over the
           values of a particular probe

  values   an array of objects
           the values are opaque to the tracer,
           they are meant to be interpreted and consumed
           by the tracer requesting them

*/
JTrace.prototype.emit = function emitTrace(facets, trap) {
  this.handlers.forEach(function (item) {
    var facetMask  = item.facetMask;
    var handler    = item.handler;

    var isMatch = true;

    // can filter against facets only
    if (facetMask) isMatch = match(facetMask, facets);

    if (isMatch) handler(facets, trap());
  });
};

JTrace.prototype.on = function onTrace(facetMask, handler) {
  this.enabled = true;
  this.handlers.push({
    facetMask  : facetMask,
    handler    : handler,
  });
};

function match(pattern, value) {
  return true;
}

function Trace() {
  this.module = null;
  this.target = null;

  this.level  = 0;
}

Trace.DIR   = 001;
Trace.LOG   = 002;
Trace.INFO  = 004;
Trace.WARN  = 010;
Trace.ERROR = 020;

Trace.NONE  = 000;
Trace.ALL   = 777;

function Tracer() {
  this.jtrace = null;
  this.module = null;
  this.parent = null;
}

function _facets(tracer, array) {
  array.unshift(tracer.module);
  if (tracer.parent) return _facets(tracer.parent, array);
  else return array;
}

Tracer.prototype.trap = function (level, target, trap) {
  var facets = {
    module : _facets(this, []),
    target : target,
    level  : level
  };

  this.jtrace.emit(facets, trap);
};

Tracer.prototype.trace = function (level, target, value) {
  // stop early when disabled
  if (!this.jtrace.enabled) return;

  var out;

  if (typeof value === 'function') out = value;
  else out = function () { return value };

  this.trap(level, target, out);
};

Tracer.prototype.dir = function dirTrace(target, value) {
  assert(target);
  assert.equal(typeof target, 'string');

  this.trace(Trace.DIR, target, value);
};

Tracer.prototype.log = function logTrace(target, value) {
  assert(target);
  assert.equal(typeof target, 'string');

  this.trace(Trace.LOG, target, value);
};

Tracer.prototype.info = function infoTrace(target, value) {
  assert(target);
  assert.equal(typeof target, 'string');

  this.trace(Trace.INFO, target, value);
};

Tracer.prototype.warn = function warnTrace(target, value) {
  assert(target);
  assert.equal(typeof target, 'string');

  this.trace(Trace.WARN, target, value);
};

Tracer.prototype.error = function errorTrace(target, value) {
  assert(target);
  assert.equal(typeof target, 'string');

  this.trace(Trace.ERROR, target, value);
};

Tracer.prototype.segment = function segment(name) {
  var tracer = Tracer.New();

  tracer.module = name;
  tracer.parent = this;
  tracer.jtrace = this.jtrace;

  return tracer;
};

Tracer.New = function New() {
  return new Tracer();
};

Tracer.NewJTracer = function NewJTracer(jtrace) {
  var tracer = Tracer.New();

  tracer.jtrace = jtrace;
  tracer.module = '/';

  return tracer;
};

module.exports.JTrace = JTrace;
module.exports.Tracer = Tracer;
<|endoftext|>


<commit_before>
var dd = 3;
var cnt = -1;
function chng() {

    $(".fadeThis").fadeTo(10,0);
    $(".fadeThis").fadeTo(2000,1);
    var img1 = document.getElementById('imgone');  // match image ID
    var img2 = document.getElementById('imgtwo');
    var img3 = document.getElementById('imgthree');
    var img4 = document.getElementById('imgfour');
    var img5 = document.getElementById('imgfive');
    var img6 = document.getElementById('imgsix');
    var img7 = document.getElementById('imgseven');
    var xmas1 = document.getElementById('xmasone');  // match image ID
    var xmas2 = document.getElementById('xmastwo');
    var xmas3 = document.getElementById('xmasthree');
    var xmas4 = document.getElementById('xmasfour');
    var xmas5 = document.getElementById('xmasfive');
    var xmas6 = document.getElementById('xmassix');
    var xmas7 = document.getElementById('xmasseven');

    var imageDir = '../img/kids/';     // change to match images folder
    var imageDir2 = '../img/xmas/';

    var images1 = ['Kids11.jpg','Kids12.jpg','Kids01.jpg'];
    var images2 = ['Kids13.jpg','Kids16.jpg','Kids04.jpg']
    var images3 = ['Kids07.jpg','Kids09.jpg','Kids02.jpg']
    var images4 = ['Kids10.jpg','Kids14.jpg','Kids03.jpg']
    var images5 = ['Kids15.jpg','Kids18.jpg','Kids05.jpg']
    var images6 = ['Kids17.jpg','Kids19.jpg','Kids06.jpg']
    var images7 = ['Kids20.jpg','Kids21.jpg','Kids08.jpg']

    var xmasOne = ['XMas10.jpg','XMas12.jpg','XMas02.jpg'];
    var xmasTwo = ['XMas13.jpg','XMas14.jpg','XMas03.jpg']
    var xmasThree = ['XMas07.jpg','XMas08.jpg','XMas01.jpg']
    var xmasFour = ['XMas11.jpg','XMas16.jpg','XMas04.jpg']
    var xmasFive = ['XMas18.jpg','XMas21.jpg','XMas05.jpg']
    var xmasSix = ['XMas15.jpg','XMas17.jpg','XMas06.jpg']
    var xmasSeven = ['XMas19.jpg','XMas20.jpg','XMas09.jpg']

    cnt++;

    if (cnt < dd) {
      if (img1){
        img1.src = imageDir + images1[cnt];
        img2.src = imageDir + images2[cnt];
        img3.src = imageDir + images3[cnt];
        img4.src = imageDir + images4[cnt];
        img5.src = imageDir + images5[cnt];
        img6.src = imageDir + images6[cnt];
        img7.src = imageDir + images7[cnt];
      };
      if (xmas1){
        xmas1.src = imageDir2 + xmasOne[cnt];
        xmas2.src = imageDir2 + xmasTwo[cnt];
        xmas3.src = imageDir2 + xmasThree[cnt];
        xmas4.src = imageDir2 + xmasFour[cnt];
        xmas5.src = imageDir2 + xmasFive[cnt];
        xmas6.src = imageDir2 + xmasSix[cnt];
        xmas7.src = imageDir2 + xmasSeven[cnt];
      };
    }
    else if (cnt == dd) {
      if (img1){
        img1.src = imageDir + images1[0];
        img2.src = imageDir + images2[0];
        img3.src = imageDir + images3[0];
        img4.src = imageDir + images4[0];
        img5.src = imageDir + images5[0];
        img6.src = imageDir + images6[0];
        img7.src = imageDir + images7[0];
      };
      if (xmas1){
        xmas1.src = imageDir2 + xmasOne[0];
        xmas2.src = imageDir2 + xmasTwo[0];
        xmas3.src = imageDir2 + xmasThree[0];
        xmas4.src = imageDir2 + xmasFour[0];
        xmas5.src = imageDir2 + xmasFive[0];
        xmas6.src = imageDir2 + xmasSix[0];
        xmas7.src = imageDir2 + xmasSeven[0];
      };
        cnt = 0;
    }

}

setInterval(chng, 7000);

/*
var myObj = {
  mike:
  hello:

}
*/
<commit_msg>made javascript page neater and added more comments to make it easier to change in the future<commit_after>
var dd = 3;           // variable based off of how many images
var cnt = -1;         // variable counting through the index
function chng() {

           /*--------------------------------
              Using jQuery to set opacity
              to 0 in 10 milliseconds
              then fade it in slowly to 100%
              opacity in 2 seconds
           -------------------------------- */

    $(".fadeThis").fadeTo(10,0);
    $(".fadeThis").fadeTo(2000,1);

             /*---------------------------
                       Image Id's
              -------------------------- */

    var img1 = document.getElementById('imgone');    // match image ID
    var img2 = document.getElementById('imgtwo');
    var img3 = document.getElementById('imgthree');
    var img4 = document.getElementById('imgfour');
    var img5 = document.getElementById('imgfive');
    var img6 = document.getElementById('imgsix');
    var img7 = document.getElementById('imgseven');
    var xmas1 = document.getElementById('xmasone');   // match image ID
    var xmas2 = document.getElementById('xmastwo');
    var xmas3 = document.getElementById('xmasthree');
    var xmas4 = document.getElementById('xmasfour');
    var xmas5 = document.getElementById('xmasfive');
    var xmas6 = document.getElementById('xmassix');
    var xmas7 = document.getElementById('xmasseven');

    var imageDir = '../img/kids/';       // change to match images folder
    var imageDir2 = '../img/xmas/';

              /*----------------------------
                 About Page Image Directory
              ---------------------------- */

    var images1 = ['Kids11.jpg','Kids12.jpg','Kids01.jpg'];
    var images2 = ['Kids13.jpg','Kids16.jpg','Kids04.jpg']
    var images3 = ['Kids07.jpg','Kids09.jpg','Kids02.jpg']
    var images4 = ['Kids10.jpg','Kids14.jpg','Kids03.jpg']
    var images5 = ['Kids15.jpg','Kids18.jpg','Kids05.jpg']
    var images6 = ['Kids17.jpg','Kids19.jpg','Kids06.jpg']
    var images7 = ['Kids20.jpg','Kids21.jpg','Kids08.jpg']

             /*---------------------------
               Xmas Page Image Directory
            ---------------------------- */

    var xmasOne = ['XMas10.jpg','XMas12.jpg','XMas02.jpg'];
    var xmasTwo = ['XMas13.jpg','XMas14.jpg','XMas03.jpg']
    var xmasThree = ['XMas07.jpg','XMas08.jpg','XMas01.jpg']
    var xmasFour = ['XMas11.jpg','XMas16.jpg','XMas04.jpg']
    var xmasFive = ['XMas18.jpg','XMas21.jpg','XMas05.jpg']
    var xmasSix = ['XMas15.jpg','XMas17.jpg','XMas06.jpg']
    var xmasSeven = ['XMas19.jpg','XMas20.jpg','XMas09.jpg']

    cnt++;     //adding one to the count to go through the array index

      /*--------------------------------------------
       Changing IMG directory by 1 each if statement
      -------------------------------------------- */

    if (cnt < dd) {
      if (img1){
        img1.src = imageDir + images1[cnt];
        img2.src = imageDir + images2[cnt];
        img3.src = imageDir + images3[cnt];
        img4.src = imageDir + images4[cnt];
        img5.src = imageDir + images5[cnt];
        img6.src = imageDir + images6[cnt];
        img7.src = imageDir + images7[cnt];
      };
      if (xmas1){
        xmas1.src = imageDir2 + xmasOne[cnt];
        xmas2.src = imageDir2 + xmasTwo[cnt];
        xmas3.src = imageDir2 + xmasThree[cnt];
        xmas4.src = imageDir2 + xmasFour[cnt];
        xmas5.src = imageDir2 + xmasFive[cnt];
        xmas6.src = imageDir2 + xmasSix[cnt];
        xmas7.src = imageDir2 + xmasSeven[cnt];
      };
    }

     /*--------------------------------------------
     Changing IMG directory back to 0 for the loop
     -------------------------------------------- */

    else if (cnt == dd) {
      if (img1){
        img1.src = imageDir + images1[0];
        img2.src = imageDir + images2[0];
        img3.src = imageDir + images3[0];
        img4.src = imageDir + images4[0];
        img5.src = imageDir + images5[0];
        img6.src = imageDir + images6[0];
        img7.src = imageDir + images7[0];
      };
      if (xmas1){
        xmas1.src = imageDir2 + xmasOne[0];
        xmas2.src = imageDir2 + xmasTwo[0];
        xmas3.src = imageDir2 + xmasThree[0];
        xmas4.src = imageDir2 + xmasFour[0];
        xmas5.src = imageDir2 + xmasFive[0];
        xmas6.src = imageDir2 + xmasSix[0];
        xmas7.src = imageDir2 + xmasSeven[0];
      };
        cnt = 0;
    }

}

               /*---------------------------
                 Once page loads setInterval
                 counts down from 7 then
                 calls the function above
               -------------------------- */

setInterval(chng, 6000);
<|endoftext|>


<commit_before>appFramework.setMsgListener(function (e, data) {
    eval(data);
});

var origUrl = "http://palmapp.lenuslab.com/web/?version=1&platform=phonegap&phoneID=" + device.uuid + "&deviceplatform=" +device.platform;

if (!appFramework.getConf("url"))
    appFramework.setConf("url", origUrl);

// Depending on the device, a few examples are:
//   - "Android"
//   - "BlackBerry 10"
//   - "iOS"
//   - "WinCE"
//   - "Tizen"
var devicePlatform = device.platform;

alert(devicePlatform);
alert(PushNotification);

gcmSenderID = "993634988218";

if (PushNotification) {
	var push = PushNotification.init({
		android: {
			senderID: gcmSenderID
		},
		ios: {
			alert: "true",
			badge: "true",
			sound: "true",
            senderID: "619337680774",
            gcmSandbox:"true"
		},
		windows: {}
	});

	push.on('registration', function (data) {
		$.ajax({
			type: "POST",
			dataType: "json",
			url: "http://www.palmapp.lenuslab.com/web/palmapp/register.php?pid=" + device.uuid + "&rid=" + data.registrationId,
			contentType: "application/json; charset=utf-8",
			success: function (data) {
				console.log(data);
			},
			error: function (e) {
				console.log(e.message);
			}
		});
	});

	push.on('notification', function (data) {
		debugger; // enable debugger on this file

		if (data.additionalData.activity == "app.palmapp.com.WebViewActivity") {
			if (jQuery("#app-iframe").length) {
				navigator.notification.confirm(
						data.message, // message
						function (buttonIndex) {
							if (buttonIndex === 1) {
								jQuery("#app-iframe").attr('src', data.additionalData.url);
							}
						},
						data.title, // title
						['Vai', 'Chiudi']                  // buttonName
						);
			} else {
				appFramework.setConf("url", data.additionalData.url);
			}
		}
	});

	push.on('error', function (e) {
		// e.message
	});
}

// run external app
appFramework.loadExternal({

    onReady: function () {
        // restore original url ( can be changed by notifications )
        appFramework.setConf("url", origUrl);

        /*jQuery("#wrapper").css("background-image"," url('/android_asset/www/data/img/ajax-loader.gif')");
        jQuery("#wrapper").css("background-repeat","no-repeat");
        jQuery("#wrapper").css("background-attachment","fixed");
        jQuery("#wrapper").css("background-size","initial");
        jQuery("#wrapper").css("background-position","center");*/

        /*var iframe = jQuery("#iframe-wrapper");

         // just 2 tricks to make fading working on android:
         // 1) use css instead of jquery fade
         // 2) set a small timeout after iframe ready before "launche" the animation ( workaround )
         window.setTimeout(function () {
         iframe.addClass("fade-in");
         jQuery("#wrapper-table").remove();
         }, 500);
         */
    }
});

//# sourceURL=customPalmapp.js
<commit_msg>update<commit_after>appFramework.setMsgListener(function (e, data) {
    eval(data);
});

var origUrl = "http://palmapp.lenuslab.com/web/?version=1&platform=phonegap&phoneID=" + device.uuid + "&deviceplatform=" +device.platform;

if (!appFramework.getConf("url"))
    appFramework.setConf("url", origUrl);

// Depending on the device, a few examples are:
//   - "Android"
//   - "BlackBerry 10"
//   - "iOS"
//   - "WinCE"
//   - "Tizen"
var devicePlatform = device.platform;

gcmSenderID = "993634988218";

if (PushNotification) {
	var push = PushNotification.init({
		android: {
			senderID: gcmSenderID
		},
		ios: {
			alert: "true",
			badge: "true",
			sound: "true",
            senderID: "619337680774"
		},
		windows: {}
	});

	push.on('registration', function (data) {
		$.ajax({
			type: "POST",
			dataType: "json",
			url: "http://www.palmapp.lenuslab.com/web/palmapp/register.php?pid=" + device.uuid + "&rid=" + data.registrationId,
			contentType: "application/json; charset=utf-8",
			success: function (data) {
				console.log(data);
			},
			error: function (e) {
				console.log(e.message);
			}
		});
	});

	push.on('notification', function (data) {
		debugger; // enable debugger on this file

		if (data.additionalData.activity == "app.palmapp.com.WebViewActivity") {
			if (jQuery("#app-iframe").length) {
				navigator.notification.confirm(
						data.message, // message
						function (buttonIndex) {
							if (buttonIndex === 1) {
								jQuery("#app-iframe").attr('src', data.additionalData.url);
							}
						},
						data.title, // title
						['Vai', 'Chiudi']                  // buttonName
						);
			} else {
				appFramework.setConf("url", data.additionalData.url);
			}
		}
	});

	push.on('error', function (e) {
		// e.message
	});
}

// run external app
appFramework.loadExternal({

    onReady: function () {
        // restore original url ( can be changed by notifications )
        appFramework.setConf("url", origUrl);

        /*jQuery("#wrapper").css("background-image"," url('/android_asset/www/data/img/ajax-loader.gif')");
        jQuery("#wrapper").css("background-repeat","no-repeat");
        jQuery("#wrapper").css("background-attachment","fixed");
        jQuery("#wrapper").css("background-size","initial");
        jQuery("#wrapper").css("background-position","center");*/

        /*var iframe = jQuery("#iframe-wrapper");

         // just 2 tricks to make fading working on android:
         // 1) use css instead of jquery fade
         // 2) set a small timeout after iframe ready before "launche" the animation ( workaround )
         window.setTimeout(function () {
         iframe.addClass("fade-in");
         jQuery("#wrapper-table").remove();
         }, 500);
         */
    }
});

//# sourceURL=customPalmapp.js
<|endoftext|>


<commit_before>/// <reference path="../data/_references.js" />

(function (global) {

    var Foo = global.Foo,
        FooWithEqualityComparer = global.FooWithEqualityComparer,
        EqualityComparer = mx.EqualityComparer,
        Comparer = mx.Comparer;

    QUnit.module("Runtime");

    QUnit.test("hash", function (assert) {

        assert.ok(mx.hash(null) === 0, "hash null!");
        assert.ok(mx.hash(undefined) === 0, "hash undefined!");
        assert.ok(mx.hash(10) === mx.hash(10), "hash integer number!");
        assert.ok(mx.hash(10.5) === mx.hash(10.5), "hash float number!");
        assert.ok(mx.hash("string") === mx.hash("string"), "hash string!");
        assert.ok(mx.hash(true) === mx.hash(true), "hash boolean!");
        assert.ok(mx.hash(new Date(2015, 0, 1)) === mx.hash(new Date(2015, 0, 1)), "hash date!");
        assert.ok(mx.hash({ name: "A" }) === mx.hash({ name: "A" }), "hash object literal!");
        assert.ok(mx.hash(new Foo()) !== mx.hash(new Foo()), "hash class instance!");
        assert.ok(mx.hash(new FooWithEqualityComparer(10)) === mx.hash(new FooWithEqualityComparer(10)), "hash class instance overriding __hash__ method!");
        assert.ok(mx.hash(10, 10.5, "string", new Date(2015, 0, 1)) === mx.hash(10, 10.5, "string", new Date(2015, 0, 1)), "combine hash codes!");
    });

    QUnit.test("equals", function (assert) {

        assert.ok(mx.equals(null, null) === true, "equals null!");
        assert.ok(mx.equals(undefined, undefined) === true, "equals undefined!");
        assert.ok(mx.equals(10, new Number(10)), "equals integer number!");
        assert.ok(mx.equals(10.5, new Number(10.5)), "equals float number!");
        assert.ok(mx.equals("string", new String("string")), "equals string!");
        assert.ok(mx.equals(true, new Boolean(true)), "equals boolean!");
        assert.ok(mx.equals(new Date(2015, 0, 1), new Date(2015, 0, 1)), "equals date!");
        assert.ok(mx.equals({ name: "A" }, { name: "A" }), "equals object literal!");
        assert.ok(mx.equals(new Foo(), new Foo()) === false, "equals class instance!");
        assert.ok(mx.equals(new Foo(), new Foo(), EqualityComparer.create(
            function () { return 0; },
            function () { return true }
        )), "equals class instance using comparer!");
        assert.ok(mx.equals(new FooWithEqualityComparer(10), new FooWithEqualityComparer(10)), "equals class instance overriding __equals__ method!");
    });

    QUnit.test("compare", function (assert) {

        assert.ok(mx.runtime.compare(1, null) === 1 && mx.runtime.compare(null, 1) === -1 && mx.runtime.compare(null, null) === 0, "compare null!");
        assert.ok(mx.runtime.compare(1, 0) === 1 && mx.runtime.compare(0, 1) === -1 && mx.runtime.compare(1, 1) === 0, "compare numbers!");
        assert.ok(mx.runtime.compare("B", "A") === 1 && mx.runtime.compare("A", "B") === -1 && mx.runtime.compare("A", "A") === 0, "compare string!");
        assert.ok(mx.runtime.compare(true, false) === 1 && mx.runtime.compare(false, true) === -1 && mx.runtime.compare(true, true) === 0, "compare bolean!");
        assert.ok(mx.runtime.compare(new Date(2015, 0, 2), new Date(2015, 0, 1)) === 1 && mx.runtime.compare(new Date(2015, 0, 1), new Date(2015, 0, 2)) === -1 && mx.runtime.compare(new Date(2015, 0, 1), new Date(2015, 0, 1)) === 0, "compare date!");
        assert.ok(mx.runtime.compare({ name: "A" }, { name: "B" }) === 0, "compare objects!");
    });

    QUnit.test("lambda", function (assert) {

        var f1 = mx.runtime.lambda("t => t * t"),
            f2 = mx.runtime.lambda("(t, u) => t + u"),
            f3 = mx.runtime.lambda("(t, u, r) => t + u + r"),
            f4 = mx.runtime.lambda("(t, u) => {id:t, name:u}");

        assert.ok(f1(2) === 4, "square root lambda!");
        assert.ok(f2(1, 2) === 3, "sum of 2 numbers lambda!");
        assert.ok(f3(1, 2, 3) === 6, "sum of 3 numbers lambda!");
        assert.ok(f4(1, "A").id === 1 && f4(1, "A").name === "A", "object literal lambda!");
    });

})(window);
<commit_msg>runtime tests<commit_after>/// <reference path="../data/_references.js" />

(function (global) {

    var Foo = global.Foo,
        FooWithEqualityComparer = global.FooWithEqualityComparer,
        EqualityComparer = mx.EqualityComparer;

    QUnit.module("Runtime");

    QUnit.test("hash", function (assert) {

        assert.ok(mx.hash(null) === 0, "hash null!");
        assert.ok(mx.hash(undefined) === 0, "hash undefined!");
        assert.ok(mx.hash(10) === mx.hash(10), "hash integer number!");
        assert.ok(mx.hash(10.5) === mx.hash(10.5), "hash float number!");
        assert.ok(mx.hash("string") === mx.hash("string"), "hash string!");
        assert.ok(mx.hash(true) === mx.hash(true), "hash boolean!");
        assert.ok(mx.hash(new Date(2015, 0, 1)) === mx.hash(new Date(2015, 0, 1)), "hash date!");
        assert.ok(mx.hash({ name: "A" }) === mx.hash({ name: "A" }), "hash object literal!");
        assert.ok(mx.hash(new Foo()) !== mx.hash(new Foo()), "hash class instance!");
        assert.ok(mx.hash(new FooWithEqualityComparer(10)) === mx.hash(new FooWithEqualityComparer(10)), "hash class instance overriding __hash__ method!");
        assert.ok(mx.hash(10, 10.5, "string", new Date(2015, 0, 1)) === mx.hash(10, 10.5, "string", new Date(2015, 0, 1)), "combine hash codes!");
    });

    QUnit.test("equals", function (assert) {

        assert.ok(mx.equals(null, null) === true, "equals null!");
        assert.ok(mx.equals(undefined, undefined) === true, "equals undefined!");
        assert.ok(mx.equals(10, 10), "equals integer number!");
        assert.ok(mx.equals(10.5, 10.5), "equals float number!");
        assert.ok(mx.equals("string", "string"), "equals string!");
        assert.ok(mx.equals(true, true), "equals boolean!");
        assert.ok(mx.equals(new Date(2015, 0, 1), new Date(2015, 0, 1)), "equals date!");
        assert.ok(mx.equals({ name: "A" }, { name: "A" }), "equals object literal!");
        assert.ok(mx.equals(new Foo(), new Foo()) === false, "equals class instance!");
        assert.ok(mx.equals(new Foo(), new Foo(), EqualityComparer.create(
            function () { return 0; },
            function () { return true; }
        )), "equals class instance using comparer!");
        assert.ok(mx.equals(new FooWithEqualityComparer(10), new FooWithEqualityComparer(10)), "equals class instance overriding __equals__ method!");
    });

    QUnit.test("compare", function (assert) {

        assert.ok(mx.runtime.compare(1, null) === 1 && mx.runtime.compare(null, 1) === -1 && mx.runtime.compare(null, null) === 0, "compare null!");
        assert.ok(mx.runtime.compare(1, 0) === 1 && mx.runtime.compare(0, 1) === -1 && mx.runtime.compare(1, 1) === 0, "compare numbers!");
        assert.ok(mx.runtime.compare("B", "A") === 1 && mx.runtime.compare("A", "B") === -1 && mx.runtime.compare("A", "A") === 0, "compare string!");
        assert.ok(mx.runtime.compare(true, false) === 1 && mx.runtime.compare(false, true) === -1 && mx.runtime.compare(true, true) === 0, "compare bolean!");
        assert.ok(mx.runtime.compare(new Date(2015, 0, 2), new Date(2015, 0, 1)) === 1 && mx.runtime.compare(new Date(2015, 0, 1), new Date(2015, 0, 2)) === -1 && mx.runtime.compare(new Date(2015, 0, 1), new Date(2015, 0, 1)) === 0, "compare date!");
        assert.ok(mx.runtime.compare({ name: "A" }, { name: "B" }) === 0, "compare objects!");
    });

    QUnit.test("lambda", function (assert) {

        var f1 = mx.runtime.lambda("t => t * t"),
            f2 = mx.runtime.lambda("(t, u) => t + u"),
            f3 = mx.runtime.lambda("(t, u, r) => t + u + r"),
            f4 = mx.runtime.lambda("(t, u) => {id:t, name:u}");

        assert.ok(f1(2) === 4, "square root lambda!");
        assert.ok(f2(1, 2) === 3, "sum of 2 numbers lambda!");
        assert.ok(f3(1, 2, 3) === 6, "sum of 3 numbers lambda!");
        assert.ok(f4(1, "A").id === 1 && f4(1, "A").name === "A", "object literal lambda!");
    });

})(window);
<|endoftext|>


<commit_before>

(function(){

	"use strict";

var ds = require('./datastore.js');

exports.httpStatusIs = function( expected ){

	return function( response, body ){
		expected = ds.getValue( expected );

		var code = parseInt(response.statusCode, 10),
			result = code  === expected;

		if ( ! result ){
			/*jshint validthis:true */
			this.debug = {expected: expected, actual: code, data: body};
		}

		return result;
	};
};

exports.isJSON = function( response, body ){
	try{
		return ( typeof JSON.parse( body ) == 'object' );
	} catch(e){
		this.debug = {body: body};
		return false;
	}

};

exports.JsonEqual = function( path, expected  ){

	return function( response, body ){
		expected = ds.getValue( expected );

		oBody = JSON.parse(body);
		actual = ds.getStorableVar(oBody, path);

		result = ( actual === expected );

		if( ! result ){
			this.debug = {expected: expected, actual: actual, data: oBody};
		}

		return result;
	};
};

exports.JsonNotEqual = function( path, unexpected ){
	return function( response, body ){
		unexpected = ds.getValue( unexpected );

		oBody = JSON.parse(body);
		actual = ds.getStorableVar(oBody, path);

		result = ( actual !== unexpected );

		if( ! result ){
			this.debug = {unexpected: unexpected, actual: actual, data: oBody};
		}

		return result;
	};
};

exports.JsonHas = function( path  ){

	return function( response, body ){

		oBody = JSON.parse(body);
		result = ds.getStorableVar(oBody, path);

		if( result === undefined ){
			this.debug = {expected: path, found: ds.getStorableVar(oBody, path), data: oBody};
			return false;
		}

		return true;
	};
};

exports.JsonType = function( path, expected  ){

	return function( response, body ){
		expected = ds.getValue( expected );

		oBody = JSON.parse(body);
		value = ds.getStorableVar(oBody, path);

		actual = typeof(value);

		result = ( actual === expected );

		if( ! result ){
			this.debug = {expected: expected, actual: actual, data: oBody};
		}

		return result;
	};
};

exports.ArrayLength = function( length, path ){

	return function( response, body ){
		length = ds.getValue( length );

		value = JSON.parse(body);
		if ( path ) {
			value = ds.getStorableVar(value, path);
		}

		if (value.length === length ) {
			return true;
		} else {
			this.debug = {expected: length, actual: value.length, data: value};
			return false;
		}
	};
};

exports.JsonContains = function( path, value ){
	return function( response, body ){
		var data = JSON.parse(body);

		value = ds.getValue( value );

		data = ds.getStorableVar(data, path);

		for ( var key in data ){
			if ( data[key] == value ){
				return true;
			}
		}

		this.debug = {expected: value, actual: null, data: data};
		return false;
	};
};

exports.JsonNotContains = function( path, value ){
	return function( response, body ){
		var data = JSON.parse(body);
		value = ds.getValue( value );
		data = ds.getStorableVar(data, path);

		for ( var key in data ){
			if ( data[key] == value ){
				this.debug = {expected: value, actual: value, data: data};
				return false;
			}
		}
		return true;
	};
};

}());<commit_msg>Improved formating and doc<commit_after>(function(){

	"use strict";

	var ds = require('./datastore.js');

	/**
	 * Checks status code
	 * @param int expected A HTTP status code
	 */
	exports.httpStatusIs = function( expected ){

		return function( response, body ){
			expectedStatus = ds.getValue( expected );

			var code = parseInt(response.statusCode, 10),
				result = code  === expected;

			if ( ! result ){
				/*jshint validthis:true */
				this.debug = {expected: expected, actual: code, data: body};
			}

			return result;
		};
	};

	exports.isJSON = function( response, body ){
		try{
			return ( typeof JSON.parse( body ) == 'object' );
		} catch(e){
			this.debug = {body: body};
			return false;
		}
	};

	/**
	 * Checks a given `key path` value against an expectation
	 * @param String path String representation of how you would acces the property
	 *	eg: myobject.property.sub_property
	 * @param Mixed expected
	 */
	exports.JsonEqual = function( path, expected  ){

		return function( response, body ){
			expected = ds.getValue( expected );

			var oBody = JSON.parse(body);
			var actual = ds.getStorableVar(oBody, path);

			var result = ( actual === expected );

			if( ! result ){
				this.debug = {expected: expected, actual: actual, data: oBody};
			}

			return result;
		};
	};

	/**
	 * Checks a given `key path` value is NOT equal to an (un)expectation
	 * @param String path String representation of how you would acces the property
	 *	eg: myobject.property.sub_property
	 * @param Mixed unexpected
	 */
	exports.JsonNotEqual = function( path, unexpected ){
		return function( response, body ){
			unexpected = ds.getValue( unexpected );

			var oBody = JSON.parse(body);
			var actual = ds.getStorableVar(oBody, path);

			var result = ( actual !== unexpected );

			if( ! result ){
				this.debug = {unexpected: unexpected, actual: actual, data: oBody};
			}

			return result;
		};
	};

	/**
	 * Checks if response JSON contains the given key path
	 * (even if the value is null or false)
	 * @param String path
	 */
	exports.JsonHas = function( path  ){

		return function( response, body ){

			var oBody = JSON.parse(body);
			var result = ds.getStorableVar(oBody, path);

			if( result === undefined ){
				this.debug = {expected: path, found: ds.getStorableVar(oBody, path), data: oBody};
				return false;
			}

			return true;
		};
	};

	/**
	 * Checks if given path is of expected type
	 * @param String path
	 * @param String type String reprensentation of the type
	 * @TODO Rename this assertion ?
	 */
	exports.JsonType = function( path, expected  ){

		return function( response, body ){
			expected = ds.getValue( expected );

			var oBody = JSON.parse(body);
			var value = ds.getStorableVar(oBody, path);

			var actual = typeof(value);
			var result = ( actual === expected );

			if( ! result ){
				this.debug = {expected: expected, actual: actual, data: oBody};
			}

			return result;
		};
	};

	/**
	 * Checks array length...
	 * @param Int length
	 * @param String path
	 * @TODO : Parameters order doesn't match others assertions
	 * @TODO Rename this assertion ?
	 */
	exports.ArrayLength = function( length, path ){

		return function( response, body ){
			var length = ds.getValue( length );
			var value = JSON.parse(body);

			if ( path ) {
				value = ds.getStorableVar(value, path);
			}

			if (value.length === length ) {
				return true;
			} else {
				this.debug = {expected: length, actual: value.length, data: value};
				return false;
			}
		};
	};

	/**
	 * Checks if an array at path contains execpted value
	 * @param String path
	 * @param Mixed value
	 * @TODO Rename this assertion ?
	 */
	exports.JsonContains = function( path, value ){
		return function( response, body ){
			var data = JSON.parse(body);
			var value = ds.getValue( value );

			data = ds.getStorableVar(data, path);

			for ( var key in data ){
				if ( data[key] == value ){
					return true;
				}
			}

			this.debug = {expected: value, actual: null, data: data};
			return false;
		};
	};

	/**
	 * Checks if an array at path does NOT contain (un)execpted value
	 * @param String path
	 * @param Mixed value
	 * @TODO Rename this assertion ?
	 */
	exports.JsonNotContains = function( path, value ){
		return function( response, body ){
			var data = JSON.parse(body);
			var value = ds.getValue( value );

			data = ds.getStorableVar(data, path);

			for ( var key in data ){
				if ( data[key] == value ){
					this.debug = {expected: value, actual: value, data: data};
					return false;
				}
			}
			return true;
		};
	};

}());<|endoftext|>


<commit_before>var deps = {
	Core: {
		src: [
			'Leaflet.KSP.js',
			'geo/crs/CRS.js',
			'body/CelestialBody.js',
			'map/Map.js'
		],
		desc: 'The core of the plugin, including predifined default CRS, and CelestialBody.'
	},

	TileLayer: {
		src: [ 'layer/tile/TileLayer.js' ],
		desc: 'Displays tile layers on the map, must be of a specified type.'
	},

	LayerGroup: {
		src: [ 'layer/LayerGroup.js' ],
		desc: 'Allows grouping several layers to handle them as one, must be of a specified type.'
	},

	Marker: {
		src: [ 'layer/marker/Icon.js' ],
		desc: 'Markers to put on the map. Includes some predefined plugin specific icons.'
	},

	Legend: {
		src: [ 'model/Legend.js' ],
		desc: 'A very simple data model for the legend control, and predifined legends.'
	},

	Control: {
		src: [ 'control/Control.js' ],
		desc: 'A contol to change which CelestialBody is displayed on a map.'
	},

	ControlLegend: {
		src: [ 'control/Control.Legend.js' ],
		desc: 'Displays a simple legend on the map',
		deps: ['Legend']
	},

	ControlScale: {
		src: [ 'control/Control.Scale.js' ],
		desc: 'A scale control that uses the radius of the CelestialBody.'
	},

	ControlCelestialBody: {
		src: [ 'control/Control.CelestialBody.js' ],
		desc: 'A control that changes which CelestialBody is displayed.'
	},

	ControlLayers: {
		src: [ 'control/Control.Layers.js' ],
		desc: 'A layer contol that updates when the CelestialBody is changed.'
	},

	CelestialBodyDefinitions: {
		src: [ 'body/CelestialBody.Definitions.js' ],
		desc: 'Definitions of all the celestial bodies in Kerbal Space program, tile and marker layers to display them, and a model of their relationships.',
		deps: ['TileLayer', 'LayerGroup', 'Legend']
	}
};

if (typeof exports !== 'undefined') {
	exports.deps = deps;
}
<commit_msg>move base Control to core<commit_after>var deps = {
	Core: {
		src: [
			'Leaflet.KSP.js',
			'geo/crs/CRS.js',
			'body/CelestialBody.js',
			'control/Control.js',
			'map/Map.js'
		],
		desc: 'The core of the plugin, including predifined default CRS, and CelestialBody.'
	},

	TileLayer: {
		src: [ 'layer/tile/TileLayer.js' ],
		desc: 'Displays tile layers on the map, must be of a specified type.'
	},

	LayerGroup: {
		src: [ 'layer/LayerGroup.js' ],
		desc: 'Allows grouping several layers to handle them as one, must be of a specified type.'
	},

	Marker: {
		src: [ 'layer/marker/Icon.js' ],
		desc: 'Markers to put on the map. Includes some predefined plugin specific icons.'
	},

	Legend: {
		src: [ 'model/Legend.js' ],
		desc: 'A very simple data model for the legend control, and predifined legends.'
	},

	ControlLegend: {
		src: [ 'control/Control.Legend.js' ],
		desc: 'Displays a simple legend on the map',
		deps: ['Legend']
	},

	ControlScale: {
		src: [ 'control/Control.Scale.js' ],
		desc: 'A scale control that uses the radius of the CelestialBody.'
	},

	ControlCelestialBody: {
		src: [ 'control/Control.CelestialBody.js' ],
		desc: 'A control that changes which CelestialBody is displayed.'
	},

	ControlLayers: {
		src: [ 'control/Control.Layers.js' ],
		desc: 'A layer contol that updates when the CelestialBody is changed.'
	},

	CelestialBodyDefinitions: {
		src: [ 'body/CelestialBody.Definitions.js' ],
		desc: 'Definitions of all the celestial bodies in Kerbal Space program, tile and marker layers to display them, and a model of their relationships.',
		deps: ['TileLayer', 'LayerGroup', 'Legend']
	}
};

if (typeof exports !== 'undefined') {
	exports.deps = deps;
}
<|endoftext|>


<commit_before>app.factory('bunkerListener', function ($rootScope, $window, $document, $interval, bunkerData, $state, notifications) {

	function handleRoomEvent(evt) {
		var room = bunkerData.getRoom(evt._id);
		if (!room) throw new Error('Received a message from a room we did not know about: ' + JSON.stringify(evt));

		switch (evt.verb) {
			case 'messaged':
				var message = evt.data;
				if (message.edited) {
					bunkerData.decorateMessage(room, message);

					var otherMessage = _.find(room.$messages, {_id: message._id});
					message.$firstInSeries = otherMessage.$firstInSeries;

					var index = _.indexOf(room.$messages, otherMessage);
					room.$messages.splice(index, 1, message);
				}
				else {
					if (!room.$messages) room.$messages = [];
					bunkerData.addMessage(room, message);
					notifications.newMessage(room, message);
					$rootScope.$broadcast('bunkerMessaged', message);
					$rootScope.$broadcast('bunkerMessaged.' + message.type, message);
				}
				break;
			case 'updated':
				_.assign(room, evt.data);
				break;
		}
	}

	function handleUserEvent(evt) {
		var userData = evt.data;
		var users = _(bunkerData.rooms).pluck('$members').flatten().pluck('user').filter({_id: evt._id}).value();

		switch (evt.verb) {
			case 'updated':
				_.each(users, function (user) {
					_.assign(user, userData);
					user.$present = isPresent(user);
				});
				if (evt._id == bunkerData.user._id) {
					_.assign(bunkerData.user, userData);
					if (userData.typingIn == null) {
						bunkerData.cancelBroadcastTyping();
					}
				}
				$rootScope.$broadcast('userUpdated', userData);
				break;
			case 'messaged':
				$rootScope.$broadcast('userMessaged_' + userData.type, userData);
				break;
		}
	}

	function handleMembershipEvent(evt) {
		var membership = _(bunkerData.rooms).pluck('$members').flatten().filter({_id: evt._id}).first();
		switch (evt.verb) {
			case 'updated':
				_.assign(membership, evt.data);
				break;
			case 'messaged':
				var room = bunkerData.getRoom(evt.data.room._id);
				bunkerData.addMessage(room, evt.data);
				$rootScope.$broadcast('bunkerMessaged', evt.data);
				break;
		}
	}

	function handleUserMembershipEvent(evt) {
		var membership = _.find(bunkerData.memberships, {_id: evt._id});
		if (!membership) return;
		switch (evt.verb) {
			case 'updated':
				_.assign(membership, evt.data);
				break;
		}
	}

	function handleInboxEvent(evt) {
		switch (evt.verb) {
			case 'messaged':
				bunkerData.inbox.unshift(evt.data);
				bunkerData.inbox.unreadMessages++;
				break;
		}
	}

	function handleVisibilityShow() {
		var activeRoom = _.find(bunkerData.rooms, {$selected: true});
		if (activeRoom) {
			bunkerData.broadcastActiveRoom(activeRoom._id);
		}
		bunkerData.broadcastPresent(true);
	}

	function handleVisibilityHide() {
		bunkerData.broadcastActiveRoom(null);
		bunkerData.broadcastPresent(false);
	}

	function handleReconnect() {
		console.log('socket reconnected');
		bunkerData.init();
	}

	function handleDisconnect() {
		console.log('socket disconnected');
	}

	function handleClose() {
		bunkerData.broadcastActiveRoom(null);
		io.socket.disconnect();
	}

	function isPresent(user) {
		return user.connected && !user.busy && user.present;
	}

	// Handle events
	var listeners = [
		{name: 'room', type: 'socket', handler: handleRoomEvent},
		{name: 'user', type: 'socket', handler: handleUserEvent},
		// usersettings are only updated by the client and mirroring is off
		{name: 'roommember', type: 'socket', handler: handleMembershipEvent},
		{name: 'user_roommember', type: 'socket', handler: handleUserMembershipEvent},
		{name: 'inboxMessage', type: 'socket', handler: handleInboxEvent},
		{name: 'reconnect', type: 'socket', handler: handleReconnect},
		{name: 'disconnect', type: 'socket', handler: handleDisconnect},
		{name: 'visibilityShow', type: 'rootScope', handler: handleVisibilityShow},
		{name: 'visibilityHide', type: 'rootScope', handler: handleVisibilityHide},
		{name: 'onbeforeunload', type: 'window', handler: handleClose},
		{name: 'onload', type: 'window', handler: _.throttle(resetTimer, 5000)},
		{name: 'onmousemove', type: 'document', handler: _.throttle(resetTimer, 5000)},
		{name: 'onkeypress', type: 'document', handler: _.throttle(resetTimer, 5000)}
	];

	var awayTimeout;

	function resetTimer() {
		clearTimeout(awayTimeout);
		awayTimeout = setTimeout(handleVisibilityHide, 1000 * 60 * 10 /* 10 min */);
		handleVisibilityShow();
	}

	return {
		init: function () {
			_.each(listeners, function (listener) {
				if (listener.type == 'socket') {
					io.socket.on(listener.name.toLowerCase(), function (evt) {
						// Ensure we have data back before responding to events
						bunkerData.$promise.then(function () {
							listener.handler(evt);
						});
					});
				}
				else if (listener.type == 'rootScope') {
					$rootScope.$on(listener.name, function (evt) {
						bunkerData.$promise.then(function () {
							listener.handler(evt);
						});
					});
				}
				else if (listener.type == 'window') {
					$window[listener.name] = listener.handler;
				}
				else if (listener.type == 'document') {
					$document[0][listener.name] = listener.handler;
				}
			});

			// Every 10 seconds, set user statuses
			$interval(function () {
				_(bunkerData.rooms).pluck('$members').flatten().pluck('user').each(function (user) {
					user.$present = isPresent(user);
				}).value();
			}, 10000);
		}
	};
});
<commit_msg>removed onbeforeunload code that doesn't work<commit_after>app.factory('bunkerListener', function ($rootScope, $window, $document, $interval, bunkerData, $state, notifications) {

	function handleRoomEvent(evt) {
		var room = bunkerData.getRoom(evt._id);
		if (!room) throw new Error('Received a message from a room we did not know about: ' + JSON.stringify(evt));

		switch (evt.verb) {
			case 'messaged':
				var message = evt.data;
				if (message.edited) {
					bunkerData.decorateMessage(room, message);

					var otherMessage = _.find(room.$messages, {_id: message._id});
					message.$firstInSeries = otherMessage.$firstInSeries;

					var index = _.indexOf(room.$messages, otherMessage);
					room.$messages.splice(index, 1, message);
				}
				else {
					if (!room.$messages) room.$messages = [];
					bunkerData.addMessage(room, message);
					notifications.newMessage(room, message);
					$rootScope.$broadcast('bunkerMessaged', message);
					$rootScope.$broadcast('bunkerMessaged.' + message.type, message);
				}
				break;
			case 'updated':
				_.assign(room, evt.data);
				break;
		}
	}

	function handleUserEvent(evt) {
		var userData = evt.data;
		var users = _(bunkerData.rooms).pluck('$members').flatten().pluck('user').filter({_id: evt._id}).value();

		switch (evt.verb) {
			case 'updated':
				_.each(users, function (user) {
					_.assign(user, userData);
					user.$present = isPresent(user);
				});
				if (evt._id == bunkerData.user._id) {
					_.assign(bunkerData.user, userData);
					if (userData.typingIn == null) {
						bunkerData.cancelBroadcastTyping();
					}
				}
				$rootScope.$broadcast('userUpdated', userData);
				break;
			case 'messaged':
				$rootScope.$broadcast('userMessaged_' + userData.type, userData);
				break;
		}
	}

	function handleMembershipEvent(evt) {
		var membership = _(bunkerData.rooms).pluck('$members').flatten().filter({_id: evt._id}).first();
		switch (evt.verb) {
			case 'updated':
				_.assign(membership, evt.data);
				break;
			case 'messaged':
				var room = bunkerData.getRoom(evt.data.room._id);
				bunkerData.addMessage(room, evt.data);
				$rootScope.$broadcast('bunkerMessaged', evt.data);
				break;
		}
	}

	function handleUserMembershipEvent(evt) {
		var membership = _.find(bunkerData.memberships, {_id: evt._id});
		if (!membership) return;
		switch (evt.verb) {
			case 'updated':
				_.assign(membership, evt.data);
				break;
		}
	}

	function handleInboxEvent(evt) {
		switch (evt.verb) {
			case 'messaged':
				bunkerData.inbox.unshift(evt.data);
				bunkerData.inbox.unreadMessages++;
				break;
		}
	}

	function handleVisibilityShow() {
		var activeRoom = _.find(bunkerData.rooms, {$selected: true});
		if (activeRoom) {
			bunkerData.broadcastActiveRoom(activeRoom._id);
		}
		bunkerData.broadcastPresent(true);
	}

	function handleVisibilityHide() {
		bunkerData.broadcastActiveRoom(null);
		bunkerData.broadcastPresent(false);
	}

	function handleReconnect() {
		console.log('socket reconnected');
		bunkerData.init();
	}

	function handleDisconnect() {
		console.log('socket disconnected');
	}

	function isPresent(user) {
		return user.connected && !user.busy && user.present;
	}

	// Handle events
	var listeners = [
		{name: 'room', type: 'socket', handler: handleRoomEvent},
		{name: 'user', type: 'socket', handler: handleUserEvent},
		// usersettings are only updated by the client and mirroring is off
		{name: 'roommember', type: 'socket', handler: handleMembershipEvent},
		{name: 'user_roommember', type: 'socket', handler: handleUserMembershipEvent},
		{name: 'inboxMessage', type: 'socket', handler: handleInboxEvent},
		{name: 'reconnect', type: 'socket', handler: handleReconnect},
		{name: 'disconnect', type: 'socket', handler: handleDisconnect},
		{name: 'visibilityShow', type: 'rootScope', handler: handleVisibilityShow},
		{name: 'visibilityHide', type: 'rootScope', handler: handleVisibilityHide},
		{name: 'onload', type: 'window', handler: _.throttle(resetTimer, 5000)},
		{name: 'onmousemove', type: 'document', handler: _.throttle(resetTimer, 5000)},
		{name: 'onkeypress', type: 'document', handler: _.throttle(resetTimer, 5000)}
	];

	var awayTimeout;

	function resetTimer() {
		clearTimeout(awayTimeout);
		awayTimeout = setTimeout(handleVisibilityHide, 1000 * 60 * 10 /* 10 min */);
		handleVisibilityShow();
	}

	return {
		init: function () {
			_.each(listeners, function (listener) {
				if (listener.type == 'socket') {
					io.socket.on(listener.name.toLowerCase(), function (evt) {
						// Ensure we have data back before responding to events
						bunkerData.$promise.then(function () {
							listener.handler(evt);
						});
					});
				}
				else if (listener.type == 'rootScope') {
					$rootScope.$on(listener.name, function (evt) {
						bunkerData.$promise.then(function () {
							listener.handler(evt);
						});
					});
				}
				else if (listener.type == 'window') {
					$window[listener.name] = listener.handler;
				}
				else if (listener.type == 'document') {
					$document[0][listener.name] = listener.handler;
				}
			});

			// Every 10 seconds, set user statuses
			$interval(function () {
				_(bunkerData.rooms).pluck('$members').flatten().pluck('user').each(function (user) {
					user.$present = isPresent(user);
				}).value();
			}, 10000);
		}
	};
});
<|endoftext|>


<commit_before>/** @class representing an Index. */
class Index {
/**
* Constructor initializes indices to an empty object.
*/
  constructor() {
    this.indices = {};
  }

/**
 * @method fileCheck
 *
 * Checks if file is empty, valid or object
 *
 * @param {string} fileContents
 */
  fileCheck(fileContents) {
    if (!fileContents.files) {
      return this.message = {
        type: 'fileEmpty',
        message: `${fileContents.name} ${'is empty!'}`,
      };
    }
    if (typeof fileContents === 'object') {
      return this.message = {
        type: 'fileValid',
        message: `${fileContents.name} ${' has been indexed successfully.'}`,
      };
    }
  }

/**
 * @method isJSON
 *
 * Converts passed string into a JSON object
 *
 * @param {string} fileData
 */
  isJSON(fileData) {
    fileData = typeof fileData !== 'string' ? JSON.stringify(fileData) : fileData;
    try {
      return JSON.parse(fileData);
    } catch (error) {
      return false;
    }
  }

/**
 * @method sanitizeInput
 *
 * It sanitizes input to alphanumeric only
 *
 * @param {string} content
 * @returns {string} return characters
 */
  sanitizeInput(content) {
    const characters = content.trim().replace(/[^a-z0-9 ]/gi, '').toLowerCase().split(' ');
    return characters;
  }

/**
 * @method createIndex
 *
 * Method that creates indices
 *
 * @param {string} fileName
 * @param {object} fileContents
 */
  createIndex(fileName, fileContents) {
    const obj = {
      name: fileName,
      files: fileContents,
    };
    const check = this.fileCheck(obj);
    if (check.type === 'fileValid') {
      const filesToBeIndexed = fileContents;
      this.indices[fileName] = {
        filesToBeIndexed,
      };
      filesToBeIndexed.forEach((doc, index) => {
        const splitTextAndTitle = `${doc.text} ${doc.title}`.split(' ');
        splitTextAndTitle.forEach((word) => {
          const theword = this.sanitizeInput(word);
          if (!this.indices[fileName][theword]) {
            this.indices[fileName][theword] = new Set();
            this.indices[fileName][theword].add(index);
          }
          this.indices[fileName][theword].add(index);
        });
      });
    }
    return check;
  }

/**
 * @method getIndex
 *
 * Method return index of files in indices object
 *
 * @param {string} name
 * @returns {object}
 */
  getIndex(name) {
    if (name && typeof name === 'string') {
      return this.indices[name];
    }
    return this.indices;
  }

/**
 * @method searchFeedback
 *
 * Takes terms of array and fetch result of each token.
 *
 * @param {array} termsArray
 * @param {object} file
 * @returns {object} searchResults
 */
  searchFeedback(termsArray, file) {
    const searchResults = {};
    termsArray.forEach((term, index) => {
      if (file.hasOwnProperty(term)) {
        searchResults[termsArray[index]] = Array.from(file[term]);
      } else {
        searchResults[term] = [];
      }
    });
    return searchResults;
  }

/**
 * @method searchIndex
 *
 * Looks for search terms in created index
 *
 * @param {object} currentFile
 * @param {array} searchTerm
 * @returns {object} searchResults
 */
  searchIndex(currentFile, ...searchTerm) {
    const searchResults = {};
    let termsArray = [];
    termsArray = this.sanitizeInput(searchTerm[0]);
    if (!currentFile) {
      Object.keys(this.indices).forEach((fileName) => {
        searchResults[fileName] = this.searchFeedback(termsArray, this.indices[fileName]);
      });
    } else {
      try {
        const file = this.indices[currentFile];
        searchResults[currentFile] = this.searchFeedback(termsArray, file);
      } catch (e) {
        return null;
      }
    }
    return searchResults;
  }
}

window.Index = Index;
export default Index;
<commit_msg>edit codeblock documentation<commit_after>/** @class representing an Index. */
class Index {
/**
* Constructor initializes indices to an empty object.
*/
  constructor() {
    this.indices = {};
  }

/**
 * @method fileCheck
 *
 * Checks if file is empty, valid or object
 *
 * @param {object} fileContents
 */
  fileCheck(fileContents) {
    if (!fileContents.files) {
      return this.message = {
        type: 'fileEmpty',
        message: `${fileContents.name} ${'is empty!'}`,
      };
    }
    if (typeof fileContents === 'object') {
      return this.message = {
        type: 'fileValid',
        message: `${fileContents.name} ${' has been indexed successfully.'}`,
      };
    }
  }

/**
 * @method isJSON
 *
 * Converts passed string into a JSON object
 *
 * @param {string} fileData
 */
  isJSON(fileData) {
    fileData = typeof fileData !== 'string' ? JSON.stringify(fileData) : fileData;
    try {
      return JSON.parse(fileData);
    } catch (error) {
      return false;
    }
  }

/**
 * @method sanitizeInput
 *
 * It sanitizes input to alphanumeric only
 *
 * @param {string} content
 * @returns {string} return characters
 */
  sanitizeInput(content) {
    const characters = content.trim().replace(/[^a-z0-9 ]/gi, '').toLowerCase().split(' ');
    return characters;
  }

/**
 * @method createIndex
 *
 * Method that creates indices
 *
 * @param {string} fileName
 * @param {object} fileContents
 */
  createIndex(fileName, fileContents) {
    const obj = {
      name: fileName,
      files: fileContents,
    };
    const check = this.fileCheck(obj);
    if (check.type === 'fileValid') {
      const filesToBeIndexed = fileContents;
      this.indices[fileName] = {
        filesToBeIndexed,
      };
      filesToBeIndexed.forEach((doc, index) => {
        const splitTextAndTitle = `${doc.text} ${doc.title}`.split(' ');
        splitTextAndTitle.forEach((word) => {
          const theword = this.sanitizeInput(word);
          if (!this.indices[fileName][theword]) {
            this.indices[fileName][theword] = new Set();
            this.indices[fileName][theword].add(index);
          }
          this.indices[fileName][theword].add(index);
        });
      });
    }
    return check;
  }

/**
 * @method getIndex
 *
 * Method return index of files in indices object
 *
 * @param {string} name
 * @returns {object}
 */
  getIndex(name) {
    if (name && typeof name === 'string') {
      return this.indices[name];
    }
    return this.indices;
  }

/**
 * @method searchFeedback
 *
 * Takes terms of array and fetch result of each token.
 *
 * @param {array} termsArray
 * @param {object} file
 * @returns {object} searchResults
 */
  searchFeedback(termsArray, file) {
    const searchResults = {};
    termsArray.forEach((term, index) => {
      if (file.hasOwnProperty(term)) {
        searchResults[termsArray[index]] = Array.from(file[term]);
      } else {
        searchResults[term] = [];
      }
    });
    return searchResults;
  }

/**
 * @method searchIndex
 *
 * Looks for search terms in created index
 *
 * @param {object} currentFile
 * @param {array} searchTerm
 * @returns {object} searchResults
 */
  searchIndex(currentFile, ...searchTerm) {
    const searchResults = {};
    let termsArray = [];
    termsArray = this.sanitizeInput(searchTerm[0]);
    if (!currentFile) {
      Object.keys(this.indices).forEach((fileName) => {
        searchResults[fileName] = this.searchFeedback(termsArray, this.indices[fileName]);
      });
    } else {
      try {
        const file = this.indices[currentFile];
        searchResults[currentFile] = this.searchFeedback(termsArray, file);
      } catch (e) {
        return null;
      }
    }
    return searchResults;
  }
}

window.Index = Index;
export default Index;
<|endoftext|>


<commit_before>var gShiftKey = false;
var gEpsilon = "Ɛ";
var gGraph =
  {
  };

gGraph.init = function () {
  var svg = d3.select ("svg");
  gGraph.width = svg.node ().getBoundingClientRect ().width;
  gGraph.height = svg.node ().getBoundingClientRect ().height;

  var charSetParam = getURLParam ("charset");
  gGraph.problem = getURLParam ("problem");
  gGraph.pset = getURLParam ("pset");
  if (charSetParam == null) {
    var url = window.location.href;
    var loc = url.lastIndexOf ("/") + 1;
    if (loc <= 8) {
      url += "/";
    } else {
      url = url.substring (0, loc);
    }
    window.location = url + "index.html";
  }
  gGraph.charSet = sortString (charSetParam);
  gGraph.epsilonEnabled = true;

  gServer.getSunetid (function (sunetid) {
    gGraph.sunetid = sunetid;
  });

  gNodes.init ();
  gEdges.init ();
  gBrush.init ();
  gTape.init ();
  gTestMenu.init ();
  gModalMenu.initSubmit ();
  gGraph.initDelete ();

  gBehaviors.addBehavior ("page", "keydown", function () { return true; }, gGraph.keydown);
  gBehaviors.addBehavior ("page", "keyup", function () { return true; }, gGraph.keyup);
  gBehaviors.apply ("page", d3.select("body"));
  gBehaviors.apply ("background", d3.select("div.gui"));

  gNodes.addNode ();
  gNodes.addNode ();
  gGraph.draw ();
}

gGraph.keydown = function () {
  gShiftKey = d3.event.shiftKey || d3.event.metaKey;
};

gGraph.keyup = function () {
  gShiftKey = d3.event.shiftKey || d3.event.metaKey;
};

gGraph.save = function () {
  return {
      nodes: gNodes.save (),
      edges: gEdges.save ()
    };
};

gGraph.load = function (saveData) {
  gNodes.load (saveData.nodes);
  gEdges.load (saveData.edges);
};

gGraph.draw = function () {
  gNodes.draw ();
  gEdges.draw ();
  gTopMenu.draw ();
  gTableMenu.draw ();
  gTape.draw ();
}

// TODO: Make the resizing more useful
// TODO: Find a non-kludgey way for the svg to have 100% height
gGraph.resize = function () {
  var svg = d3.select ("svg");
  gGraph.width = svg.node ().getBoundingClientRect ().width;
  gGraph.height = svg.node ().getBoundingClientRect ().height;
  d3.select (".background").attr("width", gGraph.width);
  d3.select (".background").attr("height", gGraph.height);
};<commit_msg>Removed vertical scrollbar<commit_after>var gShiftKey = false;
var gEpsilon = "Ɛ";
var gGraph =
  {
    HEIGHT_OFFSET: 5
  };

gGraph.init = function () {
  var svg = d3.select ("svg");
  gGraph.width = svg.node ().getBoundingClientRect ().width;
  gGraph.height = svg.node ().getBoundingClientRect ().height - gGraph.HEIGHT_OFFSET;
  svg.attr ("height", gGraph.height);

  var charSetParam = getURLParam ("charset");
  gGraph.problem = getURLParam ("problem");
  gGraph.pset = getURLParam ("pset");
  if (charSetParam == null) {
    var url = window.location.href;
    var loc = url.lastIndexOf ("/") + 1;
    if (loc <= 8) {
      url += "/";
    } else {
      url = url.substring (0, loc);
    }
    window.location = url + "index.html";
  }
  gGraph.charSet = sortString (charSetParam);
  gGraph.epsilonEnabled = true;

  gServer.getSunetid (function (sunetid) {
    gGraph.sunetid = sunetid;
  });

  gNodes.init ();
  gEdges.init ();
  gBrush.init ();
  gTape.init ();
  gTestMenu.init ();
  gModalMenu.initSubmit ();
  gGraph.initDelete ();

  gBehaviors.addBehavior ("page", "keydown", function () { return true; }, gGraph.keydown);
  gBehaviors.addBehavior ("page", "keyup", function () { return true; }, gGraph.keyup);
  gBehaviors.apply ("page", d3.select("body"));
  gBehaviors.apply ("background", d3.select("div.gui"));

  gNodes.addNode ();
  gNodes.addNode ();
  gGraph.draw ();
}

gGraph.keydown = function () {
  gShiftKey = d3.event.shiftKey || d3.event.metaKey;
};

gGraph.keyup = function () {
  gShiftKey = d3.event.shiftKey || d3.event.metaKey;
};

gGraph.save = function () {
  return {
      nodes: gNodes.save (),
      edges: gEdges.save ()
    };
};

gGraph.load = function (saveData) {
  gNodes.load (saveData.nodes);
  gEdges.load (saveData.edges);
};

gGraph.draw = function () {
  gNodes.draw ();
  gEdges.draw ();
  gTopMenu.draw ();
  gTableMenu.draw ();
  gTape.draw ();
}

// TODO: Make the resizing more useful
// TODO: Find a non-kludgey way for the svg to have 100% height
gGraph.resize = function () {
  var svg = d3.select ("svg");
  gGraph.width = svg.node ().getBoundingClientRect ().width;
  gGraph.height = svg.node ().getBoundingClientRect ().height;
  d3.select (".background").attr("width", gGraph.width);
  d3.select (".background").attr("height", gGraph.height);
};<|endoftext|>