<commit_before>'use strict'

var fixture = require('./fixture')
var Benchmark = require('benchmark')
var benchmarks = require('beautify-benchmark')

var chalk = require('chalk')

var clone = require('clone')
var cloneDeep = require('clone-deep')
var cloneExtend = require('clone-extend')
var cloneextend = require('cloneextend')
var componentClone = require('component-clone')
var dcopy = require('deep-copy')
var deepcopy = require('deepcopy')
var extend = require('extend')
var lodash = require('lodash')
var safeCloneDeep = require('safe-clone-deep')
var stringifyClone = require('stringify-clone')
var structuredClone = require('structured-clone')
var utilsCopy = require('utils-copy')
// var v8clone = require('node-v8-clone').clone

var suite = new Benchmark.Suite()

// .add('node-v8-clone', function () {
//   v8clone(fixture, true)
// })

suite.add('JSON.stringify', function () {
  JSON.parse(JSON.stringify(fixture))
})

suite.add('stringify-clone', function () {
  stringifyClone(fixture)
})

.add('clone', function () {
  clone(fixture)
})

.add('clone-deep', function () {
  cloneDeep(fixture)
})

.add('clone-extend', function () {
  cloneExtend(fixture, {})
})

.add('cloneextend', function () {
  cloneextend.clone(fixture)
})

.add('component-clone', function () {
  componentClone(fixture)
})

.add('deepcopy', function () {
  deepcopy(fixture)
})

.add('lodash', function () {
  lodash.cloneDeep(fixture)
})

.add('safe-clone-deep', function () {
  safeCloneDeep(fixture)
})

.add('structured-clone', function () {
  structuredClone(fixture)
})

.add('utils-copy', function () {
  utilsCopy(fixture)
})

.add('deep-copy', function () {
  dcopy(fixture)
})

.add('extend', function () {
  extend(true, {}, fixture)
})

// add listeners
.on('cycle', function (event) {
  benchmarks.add(event.target)
})

.on('complete', function () {
  benchmarks.log()

  console.log('Fastest is %s', chalk.green(this.filter('fastest').pluck('name')))
  console.log('Slowest is %s', chalk.red(this.filter('slowest').pluck('name')))
})

.run({
  'async': true
})
<commit_msg>re-enabling v8-clone<commit_after>'use strict'

// dependencies
var Benchmark = require('benchmark')
var benchmarks = require('beautify-benchmark')
var chalk = require('chalk')
var fixture = require('./fixture')

// libs
var clone = require('clone')
var cloneDeep = require('clone-deep')
var cloneExtend = require('clone-extend')
var cloneextend = require('cloneextend')
var componentClone = require('component-clone')
var dcopy = require('deep-copy')
var deepcopy = require('deepcopy')
var extend = require('extend')
var lodash = require('lodash')
var safeCloneDeep = require('safe-clone-deep')
var stringifyClone = require('stringify-clone')
var structuredClone = require('structured-clone')
var utilsCopy = require('utils-copy')
var v8clone = require('node-v8-clone').clone

var suite = new Benchmark.Suite()

.add('node-v8-clone', function () {
  v8clone(fixture, true)
})

suite.add('JSON.stringify', function () {
  JSON.parse(JSON.stringify(fixture))
})

suite.add('stringify-clone', function () {
  stringifyClone(fixture)
})

.add('clone', function () {
  clone(fixture)
})

.add('clone-deep', function () {
  cloneDeep(fixture)
})

.add('clone-extend', function () {
  cloneExtend(fixture, {})
})

.add('cloneextend', function () {
  cloneextend.clone(fixture)
})

.add('component-clone', function () {
  componentClone(fixture)
})

.add('deepcopy', function () {
  deepcopy(fixture)
})

.add('lodash', function () {
  lodash.cloneDeep(fixture)
})

.add('safe-clone-deep', function () {
  safeCloneDeep(fixture)
})

.add('structured-clone', function () {
  structuredClone(fixture)
})

.add('utils-copy', function () {
  utilsCopy(fixture)
})

.add('deep-copy', function () {
  dcopy(fixture)
})

.add('extend', function () {
  extend(true, {}, fixture)
})

// add listeners
.on('cycle', function (event) {
  benchmarks.add(event.target)
})

.on('complete', function () {
  benchmarks.log()

  console.log('Fastest is %s', chalk.green(this.filter('fastest').pluck('name')))
  console.log('Slowest is %s', chalk.red(this.filter('slowest').pluck('name')))
})

.run({
  'async': true
})
<|endoftext|>


<commit_before>(function(lib, undefined) {
    lib.array = {
        toArray: function toArray(object) {
            var array = [];
            try {
                array = Array.prototype.slice.call(object, 0);
            } catch (e) {
                for (var i = 0, len = object.length; i < len; i++) array[i] = object[i];
            }
            return array;
        },

        indexOf: function indexOf(array, object) {
            for (var i = 0, len = array.length; i < len; i++) {
                if (array[i] === object) return i;
            }
            return -1;
        },

        lastIndexOf: function lastIndexOf(array, object) {
            for (var len = array.length, i = len - 1; i >= 0; i--) {
                if (array[i] === object) return i;
            }
            return -1;
        },

        inArray: function inArray(array, object) {
            return (this.indexOf(array, object) > -1) ? true : false;
        },

        forEach: function forEach(array, callback, thisObject) {
            if (typeof callback != "function") throw new TypeError(callback + " is not a function");

            if ("forEach" in array) {
                array.forEach(callback, thisObject || lib.window);
            } else {
                for (var i = 0, len = array.length; i < len; i++) {
                    callback.call(thisObject || lib.window, array[i], i, array);
                }
            }
        },

        every: function every(array, callback, thisObject) {
            if (typeof callback != "function") throw new TypeError(callback + " is not a function");

            if ("every" in array) {
                return array.every(callback, thisObject || lib.window);
            } else {
                for (var i = 0, len = array.length; i < len; i++) {
                    if (i in array && !callback.call(thisObject || lib.window, array[i], i, array)) return false;
                }
                return true;
            }
        },

        some: function some(array, callback, thisObject) {
            if (typeof callback != "function") throw new TypeError(callback + " is not a function");

            if ("some" in array) {
                return array.some(callback, thisObject || lib.window);
            } else {
                for (var i = 0, len = array.length; i < len; i++) {
                    if (i in array && callback.call(thisObject || lib.window, array[i], i, array)) return true;
                }
                return false;
            }
        },

        filter: function filter(array, callback, thisObject) {
            if (typeof callback != "function") throw new TypeError(callback + " is not a function");

            if ("filter" in array) {
                return array.filter(callback, thisObject || lib.window);
            } else {
                var out = [];
                for (var i = 0, len = array.length; i < len; i++) {
                    if (i in array) {
                        if (callback.call(thisObject || lib.window, array[i], i, array)) out.push(array[i]);
                    }
                }
                return out;
            }
        },

        map: function map(array, callback, thisObject) {
            if (typeof callback != "function") throw new TypeError(callback + " is not a function");

            if ("map" in array) {
                return array.map(callback, thisObject || lib.window);
            } else {
                var len = array.length,
                    out = new Array(len);
                for (var i = 0; i < len; i++) {
                    if (i in array) out[i] = callback.call(thisObject || lib.window, array[i], i, array);
                }
                return out;
            }
        },

        reduce: function reduce(array, callback, initialValue) {
            if (typeof callback != "function") throw new TypeError(callback + " is not a function");

            if ("reduce" in array) {
                return array.reduce(callback, initialValue);
            } else {
                var len = array.length,
                    isUndefined = typeof initialValue == "undefined";

                if (len == 0 && isUndefined) {
                    throw new TypeError("Reduce of empty array with no initial value");
                }

                var i = 0,
                    out = (isUndefined) ? initialValue : array[i++];

                for (; i < len; i++) {
                    if (i in array) out = callback.call(lib.window, out, array[i], i, array);
                }
                return out;
            }
        },

        reduceRight: function reduceRight(array, callback, initialValue) {
            if (typeof callback != "function") throw new TypeError(callback + " is not a function");

            if ("reduceRight" in array) {
                return array.reduceRight(callback, initialValue);
            } else {
                var len = array.length,
                    isUndefined = typeof initialValue == "undefined";

                if (len == 0 && isUndefined) {
                    throw new TypeError("Reduce of empty array with no initial value");
                }

                var i = len - 1,
                    out = (isUndefined) ? initialValue : array[i--];

                for (; i >= 0; i--) {
                    if (i in array) out = callback.call(lib.window, out, array[i], i, array);
                }
                return out;
            }
        },

        equal: function equal(array) {
            var out = true,
                len = array.length;
            for (var i = 1, argsLen = arguments.length; i < argsLen; i++) {
                if (len != arguments[i].length) return false;
                for (var j = 0; j < len; j++) {
                    if (array[j] instanceof Array || arguments[i][j] instanceof Array) {
                        if (array[j] instanceof Array && arguments[i][j] instanceof Array) {
                            out = this.equal(array[j], arguments[i][j]);
                            if (!out) break;
                        } else {
                            return false;
                        }
                    } else {
                        out = (array[j] == arguments[i][j]);
                        if (!out) break;
                    }
                }
                if (!out) break;
            }
            return out;
        },

        subtract: function subtract(array) {
            var outPrev = array,
                outCurr = [],
                subtrahend = [];

            for (var i = 1, argsLen = arguments.length; i < argsLen; i++) {
                if (arguments[i] instanceof Array) {
                    for (var j = 0, len = arguments[i].length; j < len; j++) {
                        subtrahend.push(arguments[i][j]);
                    }
                } else {
                    subtrahend.push(arguments[i]);
                }
            }

            for (var i = 0, len = subtrahend.length; i < len; i++) {
                for (var j = 0, outLen = outPrev.length; j < outLen; j++) {
                    if (subtrahend[i] instanceof Array) {
                        if (!this.equal(outPrev[j], subtrahend[i])) {
                            outCurr.push(outPrev[j]);
                        }
                    } else {
                        if (outPrev[j] != subtrahend[i]) {
                            outCurr.push(outPrev[j]);
                        }
                    }
                }
                outPrev = outCurr;
                outCurr = [];
            }
            return outPrev;
        },

        intersect: function intersect(array) {
            var out = array;
            for (var i = 1, len = arguments.length; i < len; i++) {
                var tmp = this.subtract(array, arguments[i]);
                out = this.subtract(out, tmp);
            }
            return out;
        }
    };
})(lib);
<commit_msg>array helpers improved<commit_after>(function(lib, undefined) {
    lib.array = {
        toArray: function toArray(object) {
            var array = [];
            try {
                array = Array.prototype.slice.call(object, 0);
            } catch (e) {
                for (var i = 0, len = object.length; i < len; i++) array[i] = object[i];
            }
            return array;
        },

        indexOf: function indexOf(array, object) {
            for (var i = 0, len = array.length; i < len; i++) {
                var found = lib.util.isArray(object)
                            ? this.isEqual(array[i], object)
                            : array[i] === object;
                if (found) return i;
            }
            return -1;
        },

        lastIndexOf: function lastIndexOf(array, object) {
            for (var len = array.length, i = len - 1; i >= 0; i--) {
                var found = lib.util.isArray(object)
                            ? this.isEqual(array[i], object)
                            : array[i] === object;
                if (found) return i;
            }
            return -1;
        },

        inArray: function inArray(array, object) {
            return (this.indexOf(array, object) > -1) ? true : false;
        },

        forEach: function forEach(array, callback, thisObject) {
            if (typeof callback != "function") throw new TypeError(callback + " is not a function");

            if ("forEach" in array) {
                array.forEach(callback, thisObject || lib.window);
            } else {
                for (var i = 0, len = array.length; i < len; i++) {
                    callback.call(thisObject || lib.window, array[i], i, array);
                }
            }
        },

        every: function every(array, callback, thisObject) {
            if (typeof callback != "function") throw new TypeError(callback + " is not a function");

            if ("every" in array) {
                return array.every(callback, thisObject || lib.window);
            } else {
                for (var i = 0, len = array.length; i < len; i++) {
                    if (i in array && !callback.call(thisObject || lib.window, array[i], i, array)) return false;
                }
                return true;
            }
        },

        some: function some(array, callback, thisObject) {
            if (typeof callback != "function") throw new TypeError(callback + " is not a function");

            if ("some" in array) {
                return array.some(callback, thisObject || lib.window);
            } else {
                for (var i = 0, len = array.length; i < len; i++) {
                    if (i in array && callback.call(thisObject || lib.window, array[i], i, array)) return true;
                }
                return false;
            }
        },

        filter: function filter(array, callback, thisObject) {
            if (typeof callback != "function") throw new TypeError(callback + " is not a function");

            if ("filter" in array) {
                return array.filter(callback, thisObject || lib.window);
            } else {
                var out = [];
                for (var i = 0, len = array.length; i < len; i++) {
                    if (i in array) {
                        if (callback.call(thisObject || lib.window, array[i], i, array)) out.push(array[i]);
                    }
                }
                return out;
            }
        },

        map: function map(array, callback, thisObject) {
            if (typeof callback != "function") throw new TypeError(callback + " is not a function");

            if ("map" in array) {
                return array.map(callback, thisObject || lib.window);
            } else {
                var len = array.length,
                    out = new Array(len);
                for (var i = 0; i < len; i++) {
                    if (i in array) out[i] = callback.call(thisObject || lib.window, array[i], i, array);
                }
                return out;
            }
        },

        reduce: function reduce(array, callback, initialValue) {
            if (typeof callback != "function") throw new TypeError(callback + " is not a function");

            if ("reduce" in array) {
                var args = initialValue ? [callback, initialValue] : [callback];
                return Array.prototype.reduce.apply(array, args);
            } else {
                var len = array.length,
                    isUndefined = typeof initialValue == "undefined";

                if (len == 0 && isUndefined) {
                    throw new TypeError("Reduce of empty array with no initial value");
                }

                var i = 0,
                    out = (isUndefined) ? initialValue : array[i++];

                for (; i < len; i++) {
                    if (i in array) out = callback.call(lib.window, out, array[i], i, array);
                }
                return out;
            }
        },

        reduceRight: function reduceRight(array, callback, initialValue) {
            if (typeof callback != "function") throw new TypeError(callback + " is not a function");

            if ("reduceRight" in array) {
                var args = initialValue ? [callback, initialValue] : [callback];
                return Array.prototype.reduceRight.apply(array, args);
            } else {
                var len = array.length,
                    isUndefined = typeof initialValue == "undefined";

                if (len == 0 && isUndefined) {
                    throw new TypeError("Reduce of empty array with no initial value");
                }

                var i = len - 1,
                    out = (isUndefined) ? initialValue : array[i--];

                for (; i >= 0; i--) {
                    if (i in array) out = callback.call(lib.window, out, array[i], i, array);
                }
                return out;
            }
        },

        isEqual: function isEqual(array) {
            var out = true,
                len = array.length;
            for (var i = 1, argsLen = arguments.length; i < argsLen; i++) {
                if (len != arguments[i].length) return false;
                for (var j = 0; j < len; j++) {
                    if (array[j] instanceof Array || arguments[i][j] instanceof Array) {
                        if (array[j] instanceof Array && arguments[i][j] instanceof Array) {
                            out = this.isEqual(array[j], arguments[i][j]);
                            if (!out) break;
                        } else {
                            return false;
                        }
                    } else {
                        out = (array[j] == arguments[i][j]);
                        if (!out) break;
                    }
                }
                if (!out) break;
            }
            return out;
        },

        flatten: function flatten(array) {
            return this.reduce(array, function(prev, curr) {
                return prev.concat(curr);
            });
        },

        unique: function unique(array) {
            return lib.array.reduce(array, lib.bind(function(prev, curr) {
                if (!this.inArray(prev, curr)) prev.push(curr);
                return prev;
            },this), []);
        },

        union: function union() {
            return this.unique(this.flatten(this.toArray(arguments)));
        },

        difference: function difference(array) {
            var rest = this.unique(this.flatten(this.toArray(arguments).slice(1)));
            return this.filter(array, lib.bind(function(value) {
                return !this.inArray(rest, value);
            }, this));
        },

        intersection: function intersection(array) {
            var rest = this.toArray(arguments).slice(1);
            return this.filter(this.unique(array), lib.bind(function(item) {
                return this.every(rest, lib.bind(function(other) {
                    return this.indexOf(other, item) >= 0;
                }, this));
            }, this));
        }
    };
})(lib);
<|endoftext|>


<commit_before>if (typeof (require) != 'undefined') {
	var loader = require('../../node_modules/Butterfly-js/dist/butterfly.min.js').loader;
}

/**
 * Entry point of the game, contains some part of the game engine and deals with
 * the different entities
 */
loader.executeModule('main',
'B', 'Canvas', 'Entities', 'Physics', 'Utils', 'Maps',
function (B, canvas, Entities, Physics, Utils, Maps) {
	var car,
		tracks = [],
		// position of the mouse in the canvas, taking in account the scroll
		// and position of the canvas in the page
		mouseX,
		mouseY,
		fps = 30,
		urlParams = Utils.getUrlParams(window.location.search);

	const DEBUG = urlParams.debug || NO_DEBUG;
	console.log(DEBUG);

	B.on(window, 'load', function () {
		// Init the view
		canvas.init(document.getElementById('game-canvas'));

		setInterval(updateAll, 1000 / fps);

		/*
		 * Create the tracks, The whole game is a grid and tracks are on the grid
		 * The tracks are organised on a rectangle of the grid started at the
		 * position (TRACK_GRID_START_COL, TRACK_GRID_START_COL) and ends at the
		 * position (TRACK_GRID_COL, TRACK_GRID_ROW)
		 * Each track is an instance of the class Entities.Track
		 */
		var col, row,
			trackWidth = canvas.width() / Maps[0].width,
			trackHeight = canvas.height() / Maps[0].height,
			startX, startY;
		for (row = 0; row < Maps[0].height; row++ ) {
			for (col = 0; col < Maps[0].width; col++ ) {
				tracks.push(new Entities.Track(
					// 5 is the initial left margin
					trackWidth * col, trackHeight * row,
					trackWidth, trackHeight,
					// @TODO remove destructable field
					true, Maps[0].map[row][col]
				));

				if (Maps[0].map[row][col] == Entities.Track.STATE_START) {
					startX = trackWidth * col + trackWidth / 2;
					startY = trackHeight * row + trackHeight / 2;
				}
			}
		}

		// Init the car
		car = new Entities.Car(startX, startY, CAR_RADIUS, 0, 0);
		// Position of the car in the grid
		car.setGridCoordinates(TRACK_SPACE_WIDTH, TRACK_SPACE_HEIGHT);

		car.setGraphic(B.create('img'));
		car.graphic.onload = function () {
			car.setGraphicLoaded(true);
		};
		car.graphic.src = '/images/player1car.png';
	});

	/* Events */
	// Event to execute when the player wins
	B.Events.on('win', null, function () {
		car.reset();
	});

	// Event to execute when the player loses
	B.Events.on('lost', null, function () {
	});

	// Event to execute when the mouse move
	B.Events.on('mouse-moved', null, function (mX, mY) {
		mouseX = mX;
		mouseY = mY;

		if (DEBUG) {
			car.x = mouseX;
			car.y = mouseY;
			car.speedX = CAR_SPEED_X;
			car.speedY = CAR_SPEED_Y * -1;
		}
	});
	/* End of Events */

	/**
	 * Method to convert a pair of coordinates to the index of the cell in the
	 * grid the coordinates are in
	 */
	colRowToGridIndex = function (col, row) {
		return col - TRACK_GRID_START_COL +
			(TRACK_GRID_COL - TRACK_GRID_START_COL) * (row - TRACK_GRID_START_ROW);
	};

	/**
	 * Method to update the game state and the objects's position
	 */
	function moveAll () {
		// Update the car position
		car.updatePosition();
		car.setGridCoordinates(TRACK_SPACE_WIDTH, TRACK_SPACE_HEIGHT);

		/* Car and edges collision*/
		var wallBounded = Physics.sphereBounceAgainstInnerRectangle(car, {x: 0, y: 0, w: canvas.width(), h: canvas.height()});
		if (wallBounded == 'down') {
			car.reset();
			console.log('fire lost');
			B.Events.fire('lost');
		}
		/* End of Car and edges collision*/

		/* Car and active track collision */
		var track,
			trackSide,
			trackTopBot;

		track = tracks[colRowToGridIndex(
			car.gridCellCol,
			car.gridCellRow
		)];

		// if the car is on an active track
		if (TRACK_GRID_START_COL <= car.gridCellCol && car.gridCellCol < TRACK_GRID_COL
			&& TRACK_GRID_START_COL <= car.gridCellRow && car.gridCellRow < TRACK_GRID_ROW
			&& track.state == Entities.Track.STATE_ACTIVE
		) {
			// track next to the current one, according to car's old position
			trackSide = tracks[colRowToGridIndex(car.oldGridCellCol, car.gridCellRow)];
			trackSide = trackSide && trackSide.state == Entities.Track.STATE_ACTIVE && trackSide || undefined;

			// track under or above to the current one, according to car's old position
			trackTopBot = tracks[colRowToGridIndex(car.gridCellCol, car.oldGridCellRow)];
			trackTopBot = trackTopBot && trackTopBot.state == Entities.Track.STATE_ACTIVE && trackTopBot || undefined;

			Physics.sphereBounceAgainstGridRectangle(car, track, trackSide, trackTopBot);
		}
		/* End of Car and active track collision */
	}

	/**
	 * Method to execute on each frame to update the game state and the
	 * objects's position and then redraw the canvas
	 */
	function updateAll () {
		moveAll();
		canvas.drawAll([car, tracks]);

		if (DEBUG) {
			canvas.drawText('(' +
				Math.floor(mouseX / TRACK_SPACE_WIDTH) + ', ' +
				Math.floor(mouseY / TRACK_SPACE_HEIGHT) + ', ' +
				colRowToGridIndex(Math.floor(mouseX / TRACK_SPACE_WIDTH), Math.floor(mouseY / TRACK_SPACE_HEIGHT)) + ')', mouseX, mouseY, 'white');

			canvas.line([car.x, car.y], [car.x + car.speedX * 30, car.y + car.speedY * 30]);
		}
	}
});
<commit_msg>car speed reapplied<commit_after>if (typeof (require) != 'undefined') {
	var loader = require('../../node_modules/Butterfly-js/dist/butterfly.min.js').loader;
}

/**
 * Entry point of the game, contains some part of the game engine and deals with
 * the different entities
 */
loader.executeModule('main',
'B', 'Canvas', 'Entities', 'Physics', 'Utils', 'Maps',
function (B, canvas, Entities, Physics, Utils, Maps) {
	var car,
		tracks = [],
		// position of the mouse in the canvas, taking in account the scroll
		// and position of the canvas in the page
		mouseX,
		mouseY,
		fps = 30,
		urlParams = Utils.getUrlParams(window.location.search);

	const DEBUG = urlParams.debug || NO_DEBUG;
	console.log(DEBUG);

	B.on(window, 'load', function () {
		// Init the view
		canvas.init(document.getElementById('game-canvas'));

		setInterval(updateAll, 1000 / fps);

		/*
		 * Create the tracks, The whole game is a grid and tracks are on the grid
		 * The tracks are organised on a rectangle of the grid started at the
		 * position (TRACK_GRID_START_COL, TRACK_GRID_START_COL) and ends at the
		 * position (TRACK_GRID_COL, TRACK_GRID_ROW)
		 * Each track is an instance of the class Entities.Track
		 */
		var col, row,
			trackWidth = canvas.width() / Maps[0].width,
			trackHeight = canvas.height() / Maps[0].height,
			startX, startY;
		for (row = 0; row < Maps[0].height; row++ ) {
			for (col = 0; col < Maps[0].width; col++ ) {
				tracks.push(new Entities.Track(
					// 5 is the initial left margin
					trackWidth * col, trackHeight * row,
					trackWidth, trackHeight,
					// @TODO remove destructable field
					true, Maps[0].map[row][col]
				));

				if (Maps[0].map[row][col] == Entities.Track.STATE_START) {
					startX = trackWidth * col + trackWidth / 2;
					startY = trackHeight * row + trackHeight / 2;
				}
			}
		}

		// Init the car
		car = new Entities.Car(startX, startY, CAR_RADIUS, CAR_SPEED_X, CAR_SPEED_Y);
		// Position of the car in the grid
		car.setGridCoordinates(TRACK_SPACE_WIDTH, TRACK_SPACE_HEIGHT);

		car.setGraphic(B.create('img'));
		car.graphic.onload = function () {
			car.setGraphicLoaded(true);
		};
		car.graphic.src = '/images/player1car.png';
	});

	/* Events */
	// Event to execute when the player wins
	B.Events.on('win', null, function () {
		car.reset();
	});

	// Event to execute when the player loses
	B.Events.on('lost', null, function () {
	});

	// Event to execute when the mouse move
	B.Events.on('mouse-moved', null, function (mX, mY) {
		mouseX = mX;
		mouseY = mY;

		if (DEBUG) {
			car.x = mouseX;
			car.y = mouseY;
			car.speedX = CAR_SPEED_X;
			car.speedY = CAR_SPEED_Y * -1;
		}
	});
	/* End of Events */

	/**
	 * Method to convert a pair of coordinates to the index of the cell in the
	 * grid the coordinates are in
	 */
	colRowToGridIndex = function (col, row) {
		return col - TRACK_GRID_START_COL +
			(TRACK_GRID_COL - TRACK_GRID_START_COL) * (row - TRACK_GRID_START_ROW);
	};

	/**
	 * Method to update the game state and the objects's position
	 */
	function moveAll () {
		// Update the car position
		car.updatePosition();
		car.setGridCoordinates(TRACK_SPACE_WIDTH, TRACK_SPACE_HEIGHT);

		/* Car and edges collision*/
		var wallBounded = Physics.sphereBounceAgainstInnerRectangle(car, {x: 0, y: 0, w: canvas.width(), h: canvas.height()});
		if (wallBounded == 'down') {
			car.reset();
			console.log('fire lost');
			B.Events.fire('lost');
		}
		/* End of Car and edges collision*/

		/* Car and active track collision */
		var track,
			trackSide,
			trackTopBot;

		track = tracks[colRowToGridIndex(
			car.gridCellCol,
			car.gridCellRow
		)];

		// if the car is on an active track
		if (TRACK_GRID_START_COL <= car.gridCellCol && car.gridCellCol < TRACK_GRID_COL
			&& TRACK_GRID_START_COL <= car.gridCellRow && car.gridCellRow < TRACK_GRID_ROW
			&& track.state == Entities.Track.STATE_ACTIVE
		) {
			// track next to the current one, according to car's old position
			trackSide = tracks[colRowToGridIndex(car.oldGridCellCol, car.gridCellRow)];
			trackSide = trackSide && trackSide.state == Entities.Track.STATE_ACTIVE && trackSide || undefined;

			// track under or above to the current one, according to car's old position
			trackTopBot = tracks[colRowToGridIndex(car.gridCellCol, car.oldGridCellRow)];
			trackTopBot = trackTopBot && trackTopBot.state == Entities.Track.STATE_ACTIVE && trackTopBot || undefined;

			Physics.sphereBounceAgainstGridRectangle(car, track, trackSide, trackTopBot);
		}
		/* End of Car and active track collision */
	}

	/**
	 * Method to execute on each frame to update the game state and the
	 * objects's position and then redraw the canvas
	 */
	function updateAll () {
		moveAll();
		canvas.drawAll([car, tracks]);

		if (DEBUG) {
			canvas.drawText('(' +
				Math.floor(mouseX / TRACK_SPACE_WIDTH) + ', ' +
				Math.floor(mouseY / TRACK_SPACE_HEIGHT) + ', ' +
				colRowToGridIndex(Math.floor(mouseX / TRACK_SPACE_WIDTH), Math.floor(mouseY / TRACK_SPACE_HEIGHT)) + ')', mouseX, mouseY, 'white');

			canvas.line([car.x, car.y], [car.x + car.speedX * 30, car.y + car.speedY * 30]);
		}
	}
});
<|endoftext|>


<commit_before>/*
 * grunt-jssourcemaprev
 * https://github.com/richardbolt/grunt-jssourcemaprev
 *
 * Copyright (c) 2013 Richard Bolt
 * Licensed under the MIT license.
 */

'use strict';

var fs = require('fs'),
    path = require('path');

module.exports = function(grunt) {
  // Does not take a dest argument, modifies src files in place.
  // A revved js file points to a source map and we want to change the
  // source map and, optionally, the source files so that all are unique.
  // We change four things:
  // 1. The sourcemap name
  // 2. The sourceMappingURL line in the src javascript file to point ot the new map
  // 3. The location of the source files - rename their directory to match the source map (revving them)
  // 4. The sourceRoot attribute in the sourcemap itself to point to the moved source files.
  grunt.registerMultiTask('jssourcemaprev', 'Rename a js sourcemap and all related source files.', function() {
      var self = this,
          options = self.options({
            moveSrc: true
          });

    self.filesSrc.forEach(function (file) {
      var js = grunt.file.read(file);
      var re = /^\/\/[@|#]\ssourceMappingURL\=([\/a-zA-Z0-9_\-\.]+)$/gm;
      var match = js.match(re);
      if (!match) {
          return;
      }

      // Find the sourceMappingUrl based on match.
      var mapUrl = match[0].split('=')[1];
      var mapFile = path.join(path.dirname(file), mapUrl);
      var newMapName = path.basename(file, path.extname(file)) + '.map.json';
      var newMapFile = path.join(path.dirname(mapFile), newMapName);

      // 1. Rename the source map file.
      if (mapFile !== newMapFile) {
        grunt.file.copy(mapFile, newMapFile);
        grunt.file.delete(mapFile);
        grunt.log.writeln('✔ '.green + mapFile + (' changed to ').grey + newMapFile);
      }

      // 2. Update sourceMappingUrl in the js file.
      var newMapRelativeUrl = path.join(path.relative(path.dirname(file), path.dirname(newMapFile)), path.basename(newMapFile));
      var newJs = js.replace(re, '//@ sourceMappingURL=' + newMapRelativeUrl);
      if (newJs !== js) {
        grunt.file.write(file, newJs);
        grunt.log.writeln('✔ '.green + file + (' sourceMappingURL changed to point to ').grey + newMapFile);
      }

      var sourceMap = grunt.file.readJSON(newMapFile);
      if (sourceMap.sourceRoot) {
        // 3. Move the source files location based on sourceRoot
        var srcPath = path.join(path.dirname(newMapFile), sourceMap.sourceRoot),
            newSrcPath = path.join(path.dirname(file), path.basename(file, path.extname(file))),
            moved = 0,
            srcFiles = grunt.file.expandMapping(
              '**/*.*', // src
              path.join(path.dirname(file), path.basename(file, path.extname(file))), // dest
              { cwd: srcPath }
            );
        srcFiles.forEach(function(f){
          grunt.file.copy(f.src, f.dest);
          moved += 1;
        });
        // Remove srcFiles (since we moved it already) according to options.
        if (moved) {
          grunt.log.writeln('✔ '.green + srcPath + (' moved to ').grey + newSrcPath);
          var safeToDeleteSrcPath = (
            options.moveSrc &&
            grunt.file.isDir(srcPath) &&
            !grunt.file.isPathCwd(srcPath)
          );
          if (safeToDeleteSrcPath) {
            grunt.file.delete(srcPath);
          }
        }

        // 4. Update the sourceRoot attribute in the source map file.
        sourceMap.sourceRoot = path.relative(path.dirname(newMapFile), newSrcPath) + '/';
        grunt.file.write(newMapFile, JSON.stringify(sourceMap));
        grunt.log.writeln('✔ '.green + newMapFile + (' sourceRoot changed to point to ').grey + newSrcPath);
      }
    });
  });
};
<commit_msg>Two spaces, not four.<commit_after>/*
 * grunt-jssourcemaprev
 * https://github.com/richardbolt/grunt-jssourcemaprev
 *
 * Copyright (c) 2013 Richard Bolt
 * Licensed under the MIT license.
 */

'use strict';

var fs = require('fs'),
    path = require('path');

module.exports = function(grunt) {
  // Does not take a dest argument, modifies src files in place.
  // A revved js file points to a source map and we want to change the
  // source map and, optionally, the source files so that all are unique.
  // We change four things:
  // 1. The sourcemap name
  // 2. The sourceMappingURL line in the src javascript file to point ot the new map
  // 3. The location of the source files - rename their directory to match the source map (revving them)
  // 4. The sourceRoot attribute in the sourcemap itself to point to the moved source files.
  grunt.registerMultiTask('jssourcemaprev', 'Rename a js sourcemap and all related source files.', function() {
      var self = this,
        options = self.options({
          moveSrc: false
        });

    self.filesSrc.forEach(function (file) {
      var js = grunt.file.read(file);
      var re = /^\/\/[@|#]\ssourceMappingURL\=([\/a-zA-Z0-9_\-\.]+)$/gm;
      var match = js.match(re);
      if (!match) {
        return;
      }

      // Find the sourceMappingUrl based on match.
      var mapUrl = match[0].split('=')[1];
      var mapFile = path.join(path.dirname(file), mapUrl);
      var newMapName = path.basename(file, path.extname(file)) + '.map.json';
      var newMapFile = path.join(path.dirname(mapFile), newMapName);

      // 1. Rename the source map file.
      if (mapFile !== newMapFile) {
        grunt.file.copy(mapFile, newMapFile);
        grunt.file.delete(mapFile);
        grunt.log.writeln('✔ '.green + mapFile + (' changed to ').grey + newMapFile);
      }

      // 2. Update sourceMappingUrl in the js file.
      var newMapRelativeUrl = path.join(path.relative(path.dirname(file), path.dirname(newMapFile)), path.basename(newMapFile));
      var newJs = js.replace(re, '//@ sourceMappingURL=' + newMapRelativeUrl);
      if (newJs !== js) {
        grunt.file.write(file, newJs);
        grunt.log.writeln('✔ '.green + file + (' sourceMappingURL changed to point to ').grey + newMapFile);
      }

      var sourceMap = grunt.file.readJSON(newMapFile);
      if (sourceMap.sourceRoot) {
        // 3. Move the source files location based on sourceRoot
        var srcPath = path.join(path.dirname(newMapFile), sourceMap.sourceRoot),
          newSrcPath = path.join(path.dirname(file), path.basename(file, path.extname(file))),
          moved = 0,
          srcFiles = grunt.file.expandMapping(
            '**/*.*', // src
            path.join(path.dirname(file), path.basename(file, path.extname(file))), // dest
            { cwd: srcPath }
          );
        srcFiles.forEach(function(f){
          grunt.file.copy(f.src, f.dest);
          moved += 1;
        });
        // Remove srcFiles (since we moved it already) according to options.
        if (moved) {
          grunt.log.writeln('✔ '.green + srcPath + (' moved to ').grey + newSrcPath);
          var safeToDeleteSrcPath = (
            options.moveSrc &&
            grunt.file.isDir(srcPath) &&
            !grunt.file.isPathCwd(srcPath)
          );
          if (safeToDeleteSrcPath) {
            grunt.file.delete(srcPath);
          }
        }

        // 4. Update the sourceRoot attribute in the source map file.
        sourceMap.sourceRoot = path.relative(path.dirname(newMapFile), newSrcPath) + '/';
        grunt.file.write(newMapFile, JSON.stringify(sourceMap));
        grunt.log.writeln('✔ '.green + newMapFile + (' sourceRoot changed to point to ').grey + newSrcPath);
      }
    });
  });
};
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013-2014 node-coap contributors.
 *
 * node-coap is licensed under an MIT +no-false-attribs license.
 * All rights not explicitly granted in the MIT license are reserved.
 * See the included LICENSE file for more details.
 */

const optionsConv     = require('./lib/option_converter')
    , Server          = require('./lib/server')
    , Agent           = require('./lib/agent')
    , net             = require('net')
    , URL             = require('url')
    , globalAgent     = new Agent({ type: 'udp4' })
    , globalAgentV6   = new Agent({ type: 'udp6' })

module.exports.request = function(url) {
  var agent, req, ipv6

  if (typeof url === 'string')
    url = URL.parse(url)

  ipv6 = net.isIPv6(url.hostname || url.host)

  if (url.agent)
    agent = url.agent
  else if (url.agent === false && !ipv6)
    agent = new Agent({ type: 'udp4' })
  else if (url.agent === false && ipv6)
    agent = new Agent({ type: 'udp6' })
  else if (ipv6)
    agent = globalAgentV6
  else
    agent = globalAgent

  return agent.request(url)
}

module.exports.createServer = Server

module.exports.Agent = Agent
module.exports.globalAgent = globalAgent
module.exports.globalAgentIPv6 = globalAgentV6

module.exports.registerOption = optionsConv.registerOption
module.exports.registerFormat = optionsConv.registerFormat
<commit_msg>Expose the parameters.<commit_after>/*
 * Copyright (c) 2013-2014 node-coap contributors.
 *
 * node-coap is licensed under an MIT +no-false-attribs license.
 * All rights not explicitly granted in the MIT license are reserved.
 * See the included LICENSE file for more details.
 */

const optionsConv     = require('./lib/option_converter')
    , Server          = require('./lib/server')
    , Agent           = require('./lib/agent')
    , parameters      = require('./lib/parameters')
    , net             = require('net')
    , URL             = require('url')
    , globalAgent     = new Agent({ type: 'udp4' })
    , globalAgentV6   = new Agent({ type: 'udp6' })

module.exports.request = function(url) {
  var agent, req, ipv6

  if (typeof url === 'string')
    url = URL.parse(url)

  ipv6 = net.isIPv6(url.hostname || url.host)

  if (url.agent)
    agent = url.agent
  else if (url.agent === false && !ipv6)
    agent = new Agent({ type: 'udp4' })
  else if (url.agent === false && ipv6)
    agent = new Agent({ type: 'udp6' })
  else if (ipv6)
    agent = globalAgentV6
  else
    agent = globalAgent

  return agent.request(url)
}

module.exports.createServer = Server

module.exports.Agent = Agent
module.exports.globalAgent = globalAgent
module.exports.globalAgentIPv6 = globalAgentV6

module.exports.registerOption = optionsConv.registerOption
module.exports.registerFormat = optionsConv.registerFormat

module.exports.parameters = parameters
<|endoftext|>


<commit_before>/**
 * LabelPoint.js
 *
 * Class to find the optimum placement for a label inside an irregular polygon using
 * Polls of Inaccessibility algorithm.
 *
 * George Gardiner
 * www.commonmode.co.uk
 */

(function (window, undefined) {
    var LabelPoint = {
        find: function (points, precision) {
            if (precision == undefined) {
                precision = 1;
            }
            var x_min, y_min, x_max, y_max;
            for (var i = 0; i < points.length; i++) {
                if (i == 0) {
                    x_min = x_max = points[i].x;
                    y_min = y_max = points[i].y;
                }
                else {
                    x_min = Math.min(x_min, points[i].x);
                    x_max = Math.max(x_max, points[i].x);
                    y_min = Math.min(y_min, points[i].y);
                    y_max = Math.max(y_max, points[i].y);
                }
            }
            var lp = this.pollScan(x_min, y_min, x_max, y_max, points);
            if (precision > 0) {
                var r = ((x_max - x_min) * (y_max - y_min));
                var dx, dy;
                while (r > precision) {
                    lp = this.pollScan(x_min, y_min, x_max, y_max, points);
                    dx = (x_max - x_min) / 24;
                    dy = (y_max - y_min) / 24;
                    x_min = lp.x - dx;
                    x_max = lp.x + dx;
                    y_min = lp.y - dy;
                    y_max = lp.y + dy;
                    r = dx * dy;
                }
            }
            return lp;
        },
        pointToLineDistance: function (x, y, x1, y1, x2, y2) {
            var A = x - x1;
            var B = y - y1;
            var C = x2 - x1;
            var D = y2 - y1;
            var dot = A * C + B * D;
            var len_sq = C * C + D * D;
            var param = -1;
            if (len_sq != 0) {
                param = dot / len_sq;
            }
            var xx, yy;
            if (param < 0) {
                xx = x1;
                yy = y1;
            }
            else if (param > 1) {
                xx = x2;
                yy = y2;
            }
            else {
                xx = x1 + param * C;
                yy = y1 + param * D;
            }
            var dx = x - xx;
            var dy = y - yy;
            return Math.sqrt(dx * dx + dy * dy);
        },
        pointToPerimeterDistance: function (x, y, points) {
            var d, p1, p2, minDistance;
            for (var i = 0; i < points.length; i++) {
                p1 = points[i];
                if ((i + 1) < points.length) {
                    p2 = points[i + 1];
                }
                else {
                    p2 = points[0];
                }
                d = this.pointToLineDistance(x, y, p1.x, p1.y, p2.x, p2.y);
                if (i == 0) {
                    minDistance = d;
                }
                else {
                    if (d < minDistance) {
                        minDistance = d;
                    }
                }
            }
            return minDistance;
        },
        isInside: function (x, y, points) {
            for (var c = false, i = -1, l = points.length, j = l - 1; ++i < l; j = i)
                ((points[i].y <= y && y < points[j].y) || (points[j].y <= y && y < points[i].y))
                    && (x < (points[j].x - points[i].x) * (y - points[i].y) / (points[j].y - points[i].y) + points[i].x)
                && (c = !c);
            return c;
        },
        pollScan: function (x_min, y_min, x_max, y_max, points) {
            var px, py, pd, maxDistance = 0;
            for (var y = y_min; y < y_max; y += ((y_max - y_min) / 24)) {
                for (var x = x_min; x < x_max; x += ((x_max - x_min) / 24)) {
                    if (this.isInside(x, y, points)) {
                        pd = this.pointToPerimeterDistance(x, y, points);
                        if (pd > maxDistance) {
                            maxDistance = pd;
                            px = x;
                            py = y;
                        }
                    }
                }
            }
            return {
                x: px,
                y: py
            };
        }
    };
    window.LabelPoint = LabelPoint;
})(window);
<commit_msg>Update LabelPoint.js<commit_after>/**
 * LabelPoint.js
 *
 * Class to find the optimum placement for a label inside an irregular polygon using
 * Poles of Inaccessibility algorithm.
 *
 * George Gardiner
 * www.commonmode.co.uk
 */

(function (window, undefined) {
    var LabelPoint = {
        find: function (points, precision) {
            if (precision == undefined) {
                precision = 1;
            }
            var x_min, y_min, x_max, y_max;
            for (var i = 0; i < points.length; i++) {
                if (i == 0) {
                    x_min = x_max = points[i].x;
                    y_min = y_max = points[i].y;
                }
                else {
                    x_min = Math.min(x_min, points[i].x);
                    x_max = Math.max(x_max, points[i].x);
                    y_min = Math.min(y_min, points[i].y);
                    y_max = Math.max(y_max, points[i].y);
                }
            }
            var lp = this.poleScan(x_min, y_min, x_max, y_max, points);
            if (precision > 0) {
                var r = ((x_max - x_min) * (y_max - y_min));
                var dx, dy;
                while (r > precision) {
                    lp = this.pollScan(x_min, y_min, x_max, y_max, points);
                    dx = (x_max - x_min) / 24;
                    dy = (y_max - y_min) / 24;
                    x_min = lp.x - dx;
                    x_max = lp.x + dx;
                    y_min = lp.y - dy;
                    y_max = lp.y + dy;
                    r = dx * dy;
                }
            }
            return lp;
        },
        pointToLineDistance: function (x, y, x1, y1, x2, y2) {
            var A = x - x1;
            var B = y - y1;
            var C = x2 - x1;
            var D = y2 - y1;
            var dot = A * C + B * D;
            var len_sq = C * C + D * D;
            var param = -1;
            if (len_sq != 0) {
                param = dot / len_sq;
            }
            var xx, yy;
            if (param < 0) {
                xx = x1;
                yy = y1;
            }
            else if (param > 1) {
                xx = x2;
                yy = y2;
            }
            else {
                xx = x1 + param * C;
                yy = y1 + param * D;
            }
            var dx = x - xx;
            var dy = y - yy;
            return Math.sqrt(dx * dx + dy * dy);
        },
        pointToPerimeterDistance: function (x, y, points) {
            var d, p1, p2, minDistance;
            for (var i = 0; i < points.length; i++) {
                p1 = points[i];
                if ((i + 1) < points.length) {
                    p2 = points[i + 1];
                }
                else {
                    p2 = points[0];
                }
                d = this.pointToLineDistance(x, y, p1.x, p1.y, p2.x, p2.y);
                if (i == 0) {
                    minDistance = d;
                }
                else {
                    if (d < minDistance) {
                        minDistance = d;
                    }
                }
            }
            return minDistance;
        },
        isInside: function (x, y, points) {
            for (var c = false, i = -1, l = points.length, j = l - 1; ++i < l; j = i)
                ((points[i].y <= y && y < points[j].y) || (points[j].y <= y && y < points[i].y))
                    && (x < (points[j].x - points[i].x) * (y - points[i].y) / (points[j].y - points[i].y) + points[i].x)
                && (c = !c);
            return c;
        },
        poleScan: function (x_min, y_min, x_max, y_max, points) {
            var px, py, pd, maxDistance = 0;
            for (var y = y_min; y < y_max; y += ((y_max - y_min) / 24)) {
                for (var x = x_min; x < x_max; x += ((x_max - x_min) / 24)) {
                    if (this.isInside(x, y, points)) {
                        pd = this.pointToPerimeterDistance(x, y, points);
                        if (pd > maxDistance) {
                            maxDistance = pd;
                            px = x;
                            py = y;
                        }
                    }
                }
            }
            return {
                x: px,
                y: py
            };
        }
    };
    window.LabelPoint = LabelPoint;
})(window);
<|endoftext|>


<commit_before>/*!
 * jquery.iparallax.js | jQuery iParallax v0.0.1
 *
 * https://github.com/iJos/jquery.iParallax
 *
 * Copyright 2014 Jose Luis Jimenez | @iJos
 *
 * Released under MIT License
 */

(function($){

    var methods = {
        init : function(options) {
            var defaults = {

            };
            var options = $.extend(defaults, options);
            var o = options;
        },
    };

    $.fn.iParallax = function(methodOrOptions) {
        if(methods[methodOrOptions]){
            //Methods
            return methods[methodOrOptions].apply(this, Array.prototype.slice.call(arguments, 1));
        }else if(typeof methodOrOptions === 'object' || ! methodOrOptions){
            // Default to "init"

            //var arguments = $.extend(defaults, methodOrOptions); console.log();
            return methods.init.apply(this, arguments);
        }else{
            //Error
            $.error('Method ' +  methodOrOptions + ' does not exist on jQuery.icountdown');
        }
    };

})(jQuery);<commit_msg>Working code<commit_after>/*!
 * jquery.iparallax.js | jQuery iParallax v0.0.1
 *
 * https://github.com/iJos/jquery.iParallax.js
 *
 * Copyright 2014 Jose Luis Jimenez | @iJos
 *
 * Released under MIT License
 */

(function($){

    var methods = {
        init : function(options) {
            var defaults = {
                parallax_binder     : document,
                parallax_element    : "",
                velocity_ratio_x    : 100,
                velocity_ratio_y    : 100
            };
            var options = $.extend(defaults, options);
            new_iParallax_obj(options);
        }
    };

    $.fn.iParallax = function(methodOrOptions) {
        if(methods[methodOrOptions]){
            //Methods

            return methods[methodOrOptions].apply(this, Array.prototype.slice.call(arguments, 1));
        }else if(typeof methodOrOptions === 'object' || ! methodOrOptions){
            // Default to "init"

            //var arguments = $.extend(defaults, methodOrOptions); console.log();
            return methods.init.apply(this, arguments);
        }else{
            //Error
            $.error('Method ' +  methodOrOptions + ' does not exist on jQuery.iParallax');
        }
    };

    function new_iParallax_obj(options) {
        var start_left = parseInt($(options.parallax_element).css("left"));
        var start_top  = parseInt($(options.parallax_element).css("top"));
        $(options.parallax_binder).mousemove(function(e){
            var amountMovedX = (e.pageX * -1 / options.velocity_ratio_x);
            var amountMovedY = (e.pageY * -1 / options.velocity_ratio_y);
            $(options.parallax_element).css({
                'left': start_left + amountMovedX,
                'top' : start_top  + amountMovedY
            });
        });
    }

})(jQuery);<|endoftext|>


<commit_before>

var App;
var RaphaelElement;

var ActivityElements = new ActivityList;
var StartElements = new StartList;
var EndElements = new EndList;
var SwimlaneElements = new SwimlaneList;
var GatewayElements = new GatewayList;
var RelationElements = new RelationList;
var AllElements = new AllElementsList;

window.onload = function() {

    connections = [];

    RaphaelElement = Raphael(10, 100, "100%", "100%");

    App = new AppView;

};

function updateall(){
    //var uusi = new activity({"modelProcessId":1,"elementTypeId":4,"relationId":4,"value":"Activity","size":0,"cx":170,"cy":110});
	//var uusi = new activity({cx: 500, cy: 250, id: 4});
    //var uusi = ActivityElements.at(1);

    //var testjson = uusi.toJSON();

    //alert(testjson);
	//uusi.save();
    ActivityElements.at(1).save();
    alert("testi");
	/*
	for (var i=0; i<ActivityElements.length; i++){
		var testi = ActivityElements.pop(i);
		var testinSisaltamaRaphaelElementti = testi.get("element");
		var xArvo = testinSisaltamaRaphaelElementti.attr("x");
		var yArvo = testinSisaltamaRaphaelElementti.attr("y");
		//testi.set({cx: xArvo, cy: yArvo});
		//alert("x " +xArvo+ " y " +yArvo+ " cx " + testi.get("cx") + " cy " + testi.get("cy"))
		//testi.collection = ActivityElements;
		testi.save({cx: xArvo, cy: yArvo});
		alert("ei vittu toimi!");
	}
   	*/

}
<commit_msg>siistitty updateall()<commit_after>

var App;
var RaphaelElement;

var ActivityElements = new ActivityList;
var StartElements = new StartList;
var EndElements = new EndList;
var SwimlaneElements = new SwimlaneList;
var GatewayElements = new GatewayList;
var RelationElements = new RelationList;
var AllElements = new AllElementsList;

window.onload = function() {

    connections = [];

    RaphaelElement = Raphael(10, 100, "100%", "100%");

    App = new AppView;

};

function updateall(){
	for (var i=0; i<ActivityElements.length; i++) {
		//TEE JOTAIN!
	}
    ActivityElements.at(1).save();
    alert("testi");

}
<|endoftext|>


<commit_before>var ok = require('assert').ok

// We need to transform a strata page into an array or records. Ulimately, we
// might operate on a page directly, but it is easier to test this algorithm if
// it has been transformed into something specific to the algorithm. You can
// expose the concept of x, y, height, width and area however you would like to
// the end user, so it's on you to transform that into an array of partitioning
// records. In each record, tuck your key. When you get the records back,
// grouped into pages, you split your page based on the keys in those records.
//
// There must be at least two rectangles in the collection.
//
// Determine which pair would require the biggest rectangle to enclose them.

function getQuadraticSeeds (rectified) {
    var candidate = new Rectangle(0, 0, 0, 0)
    var i, j, seed1, seed2

    // For all unique pairs.
    for (j = 0; j < rectified.length; j++) {
        for (i = 0; i < rectified.length; i++) {
            if (i == j) continue
            var combination = rectified[i].rect.combine(rectified[j].rect)
            if (combination.area > candidate.area) {
                candidate = combination
                seed1 = i
                seed2 = j
            }
        }
    }
    return [ seed1, seed2 ]
}

function distToGroup (rectified, left, right) {
    // Using pickNext(), give each entry to the group that would have to grow
    // _least_ to accomodate it If groups tie, choose by: smallest area > fewest
    // rectified > either one
    var i, leftDiff, rightDiff, temp

    while (rectified.length) {
        temp = rectified.splice(pickNext(), 1).pop()
        leftDiff = left.rect.combine(temp.rect).area - left.rect.area
        rightDiff = right.rect.combine(temp.rect).area - right.rect.area
        if (leftDiff > rightDiff) {
            right.rect = right.rect.combine(temp.rect)
            right.records.push(temp.record)
        } else if (rightDiff > leftDiff) {
            left.rect = left.rect.combine(temp.rect)
            left.records.push(temp.record)
        } else {
            // do you have have to grow the rectangles here? Yes!
            //place in group with smallest area
            if (left.rect.area > right.rect.area) {
                right.rect = right.rect.combine(temp.rect)
                right.records.push(temp.record)
            }
            else if (right.rect.area > left.rect.area) {
                left.rect = left.rect.combine(temp.rect)
                left.records.push(temp.record)
            }
            //if tie, place in group with fewest records
            else if (left.records.length > right.records.length) {
                right.rect = right.rect.combine(temp.rect)
                right.records.push(temp.record)
            }
            else {
                left.rect = left.rect.combine(temp.rect)
                left.records.push(temp.record)
                //if tie, does not matter
            }
        }
    }

    return [ left, right ]

    function pickNext () {
        // remember this one: gqj

        // Takes all records not yet grouped find the amount both groups would
        // have to grow to include that entry, return entry with max diff
        // between group growths.
        var candidate = 0
        var pick = 0
        for (var i = 0; i < rectified.length; i++) {
            var leftArea = left.rect.combine(rectified[i].rect).area
            var rightArea = right.rect.combine(rectified[i].rect).area
            var difference = Math.abs(leftArea - rightArea)
            if (difference > candidate) {
                candidate = difference
                pick = i
            }
        }

        return pick
    }
}

function Rectangle (x, y, bottom, right) { // :: Int -> Int -> Int -> Int -> Rectangle
    ok(x <= right, 'x <= right')
    ok(bottom <= y, 'bottom <= y')
    // Extend an array to include width and height. This will be our page and
    // the array will include our records.
    this.x = x
    this.y = y
    this.bottom = bottom
    this.right = right
    this.height = this.y - bottom
    this.width = right - this.x
    this.area = this.width * this.height
    this.children = []
}
Rectangle.prototype.combine = function (other) { // :: Rectangle -> Rectangle
    ok(other instanceof Rectangle, 'other instanceof Rectangle')
    var x = Math.min(this.x, other.x)
    var y = Math.max(this.y, other.y)

    // The following lines will not work, since we are
    // not receiving rectangles. Will need to recalculate
    // bottom and right.
    //
    var bottom = Math.min(this.bottom, other.bottom)
    var right = Math.max(this.right, other.right)
    return new Rectangle(x, y, bottom, right)
}
Rectangle.prototype.intersect = function (other) { // :: Rectangle -> Rectangle
  x = Math.max(this.x, other.x)
  y = Math.min(this.y, other.y)
  right = Math.min(this.right, other.right)
  bottom = Math.max(this.bottom, other.bottom)
  width = right - x
  height = y - bottom
  if (width < 0 || height < 0) {
    return null
  }
  return new Rectangle(x, y, bottom, right)
}
Rectangle.prototype.containsPoint = function (x, y) { // :: Int -> Int -> Bool
  return (x <= this.x && x >= this.right && y <= this.y && y >= this.bottom)
}
Rectangle.prototype.containsRect = function (other) { // :: Rectangle -> Bool
  return this.containsPoint(other.x, other.y) && this.containsPoint(other.right, other.bottom)
}
Rectangle.prototype.overlap = function (other) { // :: Rectangle -> Int
  return this.intersect(other).area
}
Rectangle.prototype.diagonal = function () { // :: -> Int
  return Math.sqrt(((this.width * this.width) + (this.height * this.height)))
}

exports.quadraticPartition = function (records) {
    var rectified = records.map(function (record) {
        var x = +(record.x)
        var y = +(record.y)
        return {
            rect: new Rectangle(x, y, y, x),
            record: record
        }
    })

    return quadraticSplit(rectified)

    function quadraticSplit (rectified) {
        var seeds = getQuadraticSeeds(rectified)
        seeds.sort()
        var right = { rect: rectified[seeds[1]].rect }
        right.records = [ rectified.splice(seeds[1], 1)[0].record ]

        var left = { rect: rectified[seeds[0]].rect }
        left.records = [ rectified.splice(seeds[0], 1)[0].record ]

        return distToGroup(rectified, left, right)
    }

}
<commit_msg>Rename `distToGroup` to `distToGroupQuad`.<commit_after>var ok = require('assert').ok

// We need to transform a strata page into an array or records. Ulimately, we
// might operate on a page directly, but it is easier to test this algorithm if
// it has been transformed into something specific to the algorithm. You can
// expose the concept of x, y, height, width and area however you would like to
// the end user, so it's on you to transform that into an array of partitioning
// records. In each record, tuck your key. When you get the records back,
// grouped into pages, you split your page based on the keys in those records.
//
// There must be at least two rectangles in the collection.
//
// Determine which pair would require the biggest rectangle to enclose them.

function getQuadraticSeeds (rectified) {
    var candidate = new Rectangle(0, 0, 0, 0)
    var i, j, seed1, seed2

    // For all unique pairs.
    for (j = 0; j < rectified.length; j++) {
        for (i = 0; i < rectified.length; i++) {
            if (i == j) continue
            var combination = rectified[i].rect.combine(rectified[j].rect)
            if (combination.area > candidate.area) {
                candidate = combination
                seed1 = i
                seed2 = j
            }
        }
    }
    return [ seed1, seed2 ]
}

function distToGroupQuad (rectified, left, right) {
    // Using pickNext(), give each entry to the group that would have to grow
    // _least_ to accomodate it If groups tie, choose by: smallest area > fewest
    // rectified > either one
    var i, leftDiff, rightDiff, temp

    while (rectified.length) {
        temp = rectified.splice(pickNext(), 1).pop()
        leftDiff = left.rect.combine(temp.rect).area - left.rect.area
        rightDiff = right.rect.combine(temp.rect).area - right.rect.area
        if (leftDiff > rightDiff) {
            right.rect = right.rect.combine(temp.rect)
            right.records.push(temp.record)
        } else if (rightDiff > leftDiff) {
            left.rect = left.rect.combine(temp.rect)
            left.records.push(temp.record)
        } else {
            // do you have have to grow the rectangles here? Yes!
            //place in group with smallest area
            if (left.rect.area > right.rect.area) {
                right.rect = right.rect.combine(temp.rect)
                right.records.push(temp.record)
            }
            else if (right.rect.area > left.rect.area) {
                left.rect = left.rect.combine(temp.rect)
                left.records.push(temp.record)
            }
            //if tie, place in group with fewest records
            else if (left.records.length > right.records.length) {
                right.rect = right.rect.combine(temp.rect)
                right.records.push(temp.record)
            }
            else {
                left.rect = left.rect.combine(temp.rect)
                left.records.push(temp.record)
                //if tie, does not matter
            }
        }
    }

    return [ left, right ]

    function pickNext () {
        // remember this one: gqj

        // Takes all records not yet grouped find the amount both groups would
        // have to grow to include that entry, return entry with max diff
        // between group growths.
        var candidate = 0
        var pick = 0
        for (var i = 0; i < rectified.length; i++) {
            var leftArea = left.rect.combine(rectified[i].rect).area
            var rightArea = right.rect.combine(rectified[i].rect).area
            var difference = Math.abs(leftArea - rightArea)
            if (difference > candidate) {
                candidate = difference
                pick = i
            }
        }

        return pick
    }
}

function Rectangle (x, y, bottom, right) { // :: Int -> Int -> Int -> Int -> Rectangle
    ok(x <= right, 'x <= right')
    ok(bottom <= y, 'bottom <= y')
    // Extend an array to include width and height. This will be our page and
    // the array will include our records.
    this.x = x
    this.y = y
    this.bottom = bottom
    this.right = right
    this.height = this.y - bottom
    this.width = right - this.x
    this.area = this.width * this.height
    this.children = []
}
Rectangle.prototype.combine = function (other) { // :: Rectangle -> Rectangle
    ok(other instanceof Rectangle, 'other instanceof Rectangle')
    var x = Math.min(this.x, other.x)
    var y = Math.max(this.y, other.y)

    // The following lines will not work, since we are
    // not receiving rectangles. Will need to recalculate
    // bottom and right.
    //
    var bottom = Math.min(this.bottom, other.bottom)
    var right = Math.max(this.right, other.right)
    return new Rectangle(x, y, bottom, right)
}
Rectangle.prototype.intersect = function (other) { // :: Rectangle -> Rectangle
  x = Math.max(this.x, other.x)
  y = Math.min(this.y, other.y)
  right = Math.min(this.right, other.right)
  bottom = Math.max(this.bottom, other.bottom)
  width = right - x
  height = y - bottom
  if (width < 0 || height < 0) {
    return null
  }
  return new Rectangle(x, y, bottom, right)
}
Rectangle.prototype.containsPoint = function (x, y) { // :: Int -> Int -> Bool
  return (x <= this.x && x >= this.right && y <= this.y && y >= this.bottom)
}
Rectangle.prototype.containsRect = function (other) { // :: Rectangle -> Bool
  return this.containsPoint(other.x, other.y) && this.containsPoint(other.right, other.bottom)
}
Rectangle.prototype.overlap = function (other) { // :: Rectangle -> Int
  return this.intersect(other).area
}
Rectangle.prototype.diagonal = function () { // :: -> Int
  return Math.sqrt(((this.width * this.width) + (this.height * this.height)))
}

exports.quadraticPartition = function (records) {
    var rectified = records.map(function (record) {
        var x = +(record.x)
        var y = +(record.y)
        return {
            rect: new Rectangle(x, y, y, x),
            record: record
        }
    })

    return quadraticSplit(rectified)

    function quadraticSplit (rectified) {
        var seeds = getQuadraticSeeds(rectified)
        seeds.sort()
        var right = { rect: rectified[seeds[1]].rect }
        right.records = [ rectified.splice(seeds[1], 1)[0].record ]

        var left = { rect: rectified[seeds[0]].rect }
        left.records = [ rectified.splice(seeds[0], 1)[0].record ]

        return distToGroupQuad(rectified, left, right)
    }

}

exports.linearPartition = function (records) {
    var rectified = records.map(function (record) {
        var x = +(record.x)
        var y = +(record.y)
        return {
            rect: new Rectangle(x, y, y, x),
            record: record
        }
    })

    return linearSplit(rectified)

    function linearSplit (rectified) {
        var seeds = getlinearSeeds(rectified)
        seeds.sort()
        var right = { rect: rectified[seeds[1]].rect }
        right.records = [ rectified.splice(seeds[1], 1)[0].record ]

        var left = { rect: rectified[seeds[0]].rect }
        left.records = [ rectified.splice(seeds[0], 1)[0].record ]

        return distToGroupLin(rectified, left, right)
    }

}
<|endoftext|>


<commit_before>"use strict";

let app = require('express')();

let bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies

let serverResponse = {};

app.get('/', function (request, response) {
    const statusCode = serverResponse.statusCode;

    response.writeHead(statusCode || 200, { 'Content-Type': 'text/html' });
    response.end(serverResponse.body || "This is the testserver");
});

app.post('/setServerResponse', function(request, response) {
    serverResponse.statusCode = request.body.statusCode
    serverResponse.body = request.body.body;

    console.log("Response set");
    response.send("Response set");
});

let server = app.listen(8080, function () {
    const host = 'localhost';
    const port = server.address().port;

    console.log('Testing server listening at http://%s:%s', host, port);
});
<commit_msg>remove es6 features<commit_after>"use strict";

var app = require('express')();

var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies

var serverResponse = {};

app.get('/', function (request, response) {
    var statusCode = serverResponse.statusCode;

    response.writeHead(statusCode || 200, { 'Content-Type': 'text/html' });
    response.end(serverResponse.body || "This is the testserver");
});

app.post('/setServerResponse', function(request, response) {
    serverResponse.statusCode = request.body.statusCode
    serverResponse.body = request.body.body;

    console.log("Response set");
    response.send("Response set");
});

let server = app.listen(8080, function () {
    var host = 'localhost';
    var port = server.address().port;

    console.log('Testing server listening at http://%s:%s', host, port);
});
<|endoftext|>


<commit_before>Package.describe({
  name: 'jacksingleton:accounts-sandstorm-dev',

  version: '0.0.2',

  summary: 'Stubs Sandstorm user headers and provides helper methods to control their values in tests',

  git: 'https://github.com/jacksingleton/accounts-sandstorm-dev.git',

  documentation: 'README.md',

  debugOnly: true
});

Package.onUse(function(api) {
  api.versionsFrom('1.1.0.3');

  api.use('http@1.1.0');

  api.addFiles('insert-stub-headers.js', 'server');
  api.addFiles('test-helpers.js', 'client');

  api.export('withUserLoggedIn', 'client');
  api.export('withPermissions', 'client');
  api.export('withOwner', 'client');
  api.export('withNonOwner', 'client');
});
<commit_msg>Fix the name of a test helper export to match the actual function name<commit_after>Package.describe({
  name: 'jacksingleton:accounts-sandstorm-dev',

  version: '0.0.2',

  summary: 'Stubs Sandstorm user headers and provides helper methods to control their values in tests',

  git: 'https://github.com/jacksingleton/accounts-sandstorm-dev.git',

  documentation: 'README.md',

  debugOnly: true
});

Package.onUse(function(api) {
  api.versionsFrom('1.1.0.3');

  api.use('http@1.1.0');

  api.addFiles('insert-stub-headers.js', 'server');
  api.addFiles('test-helpers.js', 'client');

  api.export('withUserLoggedIn', 'client');
  api.export('withPermissions', 'client');
  api.export('withOwner', 'client');
  api.export('withNoPermissions', 'client');
});
<|endoftext|>


<commit_before>/*
 * newsfader
 * https://github.com/nolawi/newsfader
 *
 * Copyright (c) 2017 Nolawi Petros
 * Licensed under the MIT license.
 */

(function($) {
  $.fn.dropdown = function(opts) {
    // default configuration
    var config = $.extend({}, {
            fadeInTime: 800,
            fadeOutTime: 800,
            interval: 5600
        }, opts);
    // main function
    function init(obj) {
        console.log ('newsfader');
            var dNewsticker = obj;
            var dFrame = dNewsticker.find('.js-frame');
            var dItem = dFrame.find('.js-item');
            var dCurrent;
            var stop = false;

            dItem.eq(0).addClass('current');
            dItem.eq(0).show();

            var move = setInterval(function(){
                if(!stop){
                    dCurrent = dFrame.find('.current');
                    dCurrent.fadeOut(config.fadeOutTime, function(){
                        if(dCurrent.next().length !== 0){
                            dCurrent.removeClass('current');
                            dCurrent.next().addClass('current');
                            dCurrent.next().fadeIn(config.fadeInTime);
                        }
                        else{
                            dCurrent.removeClass('current');
                            dItem.eq(0).addClass('current');
                            dItem.eq(0).fadeIn(config.fadeInTime);
                        }
                    });
                }
            }, config.interval);

            dNewsticker.on('mouseover mouseout', function(e){
                if(e.type == 'mouseover'){
                    stop = true;
                }
                else{
                    stop = false;
                }
            });
        }
    // initialize every element
    this.each(function() {
      init($(this));
    });
    return this;
  };
  // start
  $(function() {
    $('.js-newsticker').dropdown();
  });
})(jQuery);<commit_msg>remove initiation<commit_after>/*
 * newsfader
 * https://github.com/nolawi/newsfader
 *
 * Copyright (c) 2017 Nolawi Petros
 * Licensed under the MIT license.
 */

(function($) {
  $.fn.dropdown = function(opts) {
    // default configuration
    var config = $.extend({}, {
            fadeInTime: 800,
            fadeOutTime: 800,
            interval: 5600
        }, opts);
    // main function
    function init(obj) {
        console.log ('newsfader');
            var dNewsticker = obj;
            var dFrame = dNewsticker.find('.js-frame');
            var dItem = dFrame.find('.js-item');
            var dCurrent;
            var stop = false;

            dItem.eq(0).addClass('current');
            dItem.eq(0).show();

            var move = setInterval(function(){
                if(!stop){
                    dCurrent = dFrame.find('.current');
                    dCurrent.fadeOut(config.fadeOutTime, function(){
                        if(dCurrent.next().length !== 0){
                            dCurrent.removeClass('current');
                            dCurrent.next().addClass('current');
                            dCurrent.next().fadeIn(config.fadeInTime);
                        }
                        else{
                            dCurrent.removeClass('current');
                            dItem.eq(0).addClass('current');
                            dItem.eq(0).fadeIn(config.fadeInTime);
                        }
                    });
                }
            }, config.interval);

            dNewsticker.on('mouseover mouseout', function(e){
                if(e.type == 'mouseover'){
                    stop = true;
                }
                else{
                    stop = false;
                }
            });
        }
    // initialize every element
    this.each(function() {
      init($(this));
    });
    return this;
  };
  // start

})(jQuery);<|endoftext|>


<commit_before>app.controller("loginCreateAccountCtrl", function($scope, $location, loginSvc) {

  $scope.loginTest =
    "This test is from the Login/CreateAccount Controller file from $scope";
  $scope.createAccountTest =
    "This test is from the Login/CreateAccount Controller file from $scope";

  $scope.login = function(data) {
    console.log('this is login data', data);
    loginSvc.logInUser(data).then(function(response) {
      console.log('this is login response', response);
      if (response === "authentication failed") {
        $scope.user = "";
        $location.path("/login");
      } else {
        $scope.user = "";
        $location.path("/profiles");
      }
    })
  }

  $scope.register = function(data) {
    console.log('this is register data', data);
    loginSvc.register(data).then(function(response) {
      console.log('this is register response', response);
      $scope.user = "";
    })
  }

});
<commit_msg>added account creation redirect to profile page<commit_after>app.controller("loginCreateAccountCtrl", function($scope, $location, loginSvc) {

  $scope.loginTest =
    "This test is from the Login/CreateAccount Controller file from $scope";
  $scope.createAccountTest =
    "This test is from the Login/CreateAccount Controller file from $scope";

  $scope.login = function(data) {
    console.log('this is login data', data);
    loginSvc.logInUser(data).then(function(response) {
      console.log('this is login response', response);
      if (response === "authentication failed") {
        $scope.user = "";
        $location.path("/login");
      } else {
        $scope.user = "";
        $location.path("/profiles");
      }
    })
  }

  $scope.register = function(data) {
    console.log('this is register data', data);
    loginSvc.register(data).then(function(response) {
      console.log('this is register response', response);
      $scope.user = "";
      $location.path("/profiles");
    })
  }

});
<|endoftext|>


<commit_before>'use strict'

var fs = require('fs')
var util = require('util')
var http = require('http')
var patterns = require('patterns')()
var request = require('request')
var csv = require('csv-parser')
var pkg = require('./package')

var env = process.env.NODE_ENV || 'development'
var userAgent = pkg.name + '/' + pkg.version
var head = '<!doctype html><meta charset=utf-8><title>GitHub followers</title>'
var top10k = []

console.log('Loading top 10k Github users')
fs.createReadStream('./top-10k.csv')
  .pipe(csv())
  .on('data', function (data) {
    top10k.push(data.login)
  })
  .on('end', function () {
    console.log('Finished loading top 10k Github users')
  })

patterns.add('GET /', function (req, res) {
  res.end(head + '<input type=text name=username id=username placeholder="Enter GitHub username"><button onclick="window.location = document.getElementById(\'username\').value">Submit</button>')
})

patterns.add('GET /{username}', function (req, res) {
  if (env !== 'production') console.log(req.method, req.url)

  var opts = {
    uri: 'https://api.github.com/users/' + req.params.username + '/followers',
    json: true,
    headers: {
      'User-Agent': userAgent
    }
  }
  request(opts, function (err, response, data) {
    if (err) {
      res.writeHead(500)
      res.end(err.message)
      return
    }
    if (!Array.isArray(data)) {
      res.writeHead(404)
      res.end()
      return
    }

    var rank = top10k.indexOf(req.params.username)
    rank = rank === -1 ? 'unknown' : rank + 1

    res.write(head)
    res.write('
Listing followers of ' + req.params.username + ' (rank: ' + rank + ')')
    res.write('

	Username	Rank

')

    data
      .sort(function (a, b) {
        a = top10k.indexOf(a.login)
        b = top10k.indexOf(b.login)
        if (a === b) return 0
        if (a === -1) return 1
        if (b === -1) return -1
        return a - b
      })
      .forEach(function (user) {
        var rank = top10k.indexOf(user.login)
        rank = rank === -1 ? 'unknown' : rank + 1
        res.write(util.format('
	%s	%s
', user.avatar_url, user.login, user.login, rank))
      })

    res.end('

')
  })
})

var server = http.createServer(function (req, res) {
  var match = patterns.match(req.method + ' ' + req.url)

  if (!match) {
    res.writeHead(404)
    res.end()
    return
  }

  var fn = match.value
  req.params = match.params
  fn(req, res)
})

server.listen(process.env.PORT, function () {
  console.log('Server listening on port', server.address().port)
})
<commit_msg>Set size of user avatar to 50px<commit_after>'use strict'

var fs = require('fs')
var util = require('util')
var http = require('http')
var patterns = require('patterns')()
var request = require('request')
var csv = require('csv-parser')
var pkg = require('./package')

var env = process.env.NODE_ENV || 'development'
var userAgent = pkg.name + '/' + pkg.version
var head = '<!doctype html><meta charset=utf-8><title>GitHub followers</title>'
var top10k = []

console.log('Loading top 10k Github users')
fs.createReadStream('./top-10k.csv')
  .pipe(csv())
  .on('data', function (data) {
    top10k.push(data.login)
  })
  .on('end', function () {
    console.log('Finished loading top 10k Github users')
  })

patterns.add('GET /', function (req, res) {
  res.end(head + '<input type=text name=username id=username placeholder="Enter GitHub username"><button onclick="window.location = document.getElementById(\'username\').value">Submit</button>')
})

patterns.add('GET /{username}', function (req, res) {
  if (env !== 'production') console.log(req.method, req.url)

  var opts = {
    uri: 'https://api.github.com/users/' + req.params.username + '/followers',
    json: true,
    headers: {
      'User-Agent': userAgent
    }
  }
  request(opts, function (err, response, data) {
    if (err) {
      res.writeHead(500)
      res.end(err.message)
      return
    }
    if (!Array.isArray(data)) {
      res.writeHead(404)
      res.end()
      return
    }

    var rank = top10k.indexOf(req.params.username)
    rank = rank === -1 ? 'unknown' : rank + 1

    res.write(head)
    res.write('
Listing followers of ' + req.params.username + ' (rank: ' + rank + ')')
    res.write('

	Username	Rank

')

    data
      .sort(function (a, b) {
        a = top10k.indexOf(a.login)
        b = top10k.indexOf(b.login)
        if (a === b) return 0
        if (a === -1) return 1
        if (b === -1) return -1
        return a - b
      })
      .forEach(function (user) {
        var rank = top10k.indexOf(user.login)
        rank = rank === -1 ? 'unknown' : rank + 1
        res.write(util.format('
	%s	%s
', user.avatar_url, user.login, user.login, rank))
      })

    res.end('

')
  })
})

var server = http.createServer(function (req, res) {
  var match = patterns.match(req.method + ' ' + req.url)

  if (!match) {
    res.writeHead(404)
    res.end()
    return
  }

  var fn = match.value
  req.params = match.params
  fn(req, res)
})

server.listen(process.env.PORT, function () {
  console.log('Server listening on port', server.address().port)
})
<|endoftext|>


<commit_before>importPackage(java.io);

power_tracker = mote.getSimulation().getCooja().getStartedPlugin("PowerTracker");
serial_log_file = new FileWriter("serial.log");
power_tracker_file = new FileWriter("powertracker.log", false);

function time_prefix(val){
      var i= 0;

      var array1 = val.split("\n");
      for ( i = 0; i < array1.length; i++) {
        array1[i] = time + array1[i];
  }
  val = array1.join("\n");
}

function printStatistics() {

      /* Extract power tracker statistics */

      if (power_tracker != null) {
            stats = power_tracker.radioStatistics();
            log.log("PowerTracker: Extracted statistics:\n" + stats + "\n");
            time_prefix(stats);
            power_tracker_file.write(stats);
            power_tracker_file.flush();
      } else {
            log.log("No PowerTracker plugin\n");
      }
}

TIMEOUT({{ timeout }}, log.log("last msg: " + msg + "\n"));
counter = 0;
powertracker_frequency = {{ powertracker_frequency }};

while(1) {

      serial_log_file.write(time + " ID:" + id.toString() + " " + msg + "\n");
      serial_log_file.flush();

      //This is the tricky part. The Script is terminated using
      // an exception. This needs to be caught.
      try{
            YIELD();
            if (counter < time){
                log.log(counter);
                printStatistics();
                counter += powertracker_frequency;
          }

    } catch (e) {
      //Close files.
      serial_log_file.close();
      power_tracker_file.close();
      //Rethrow exception again, to end the script.
      throw('test script killed');
      log.testOK();
    }
}
log.testOK();<commit_msg>Adding a js script<commit_after>importPackage(java.io);

serial_log_file = new FileWriter("serial.log");
//power_tracker = mote.getSimulation().getCooja().getStartedPlugin("PowerTracker");
//power_tracker_file = new FileWriter("powertracker.log", false);

//function time_prefix(val){
//      var i= 0;
//
//      var array1 = val.split("\n");
//      for ( i = 0; i < array1.length; i++) {
//        array1[i] = time + array1[i];
//  }
//  val = array1.join("\n");
//}
//
//function printStatistics() {
//
//      /* Extract power tracker statistics */
//
//      if (power_tracker != null) {
//            stats = power_tracker.radioStatistics();
//            log.log("PowerTracker: Extracted statistics:\n" + stats + "\n");
//            time_prefix(stats);
//            power_tracker_file.write(stats);
//            power_tracker_file.flush();
//      } else {
//            log.log("No PowerTracker plugin\n");
//      }
//}

TIMEOUT({{ timeout }}, log.testOK());
//counter = 0;
//powertracker_frequency = {{ powertracker_frequency }};

while(1) {

  serial_log_file.write(time + " ID:" + id.toString() + " " + msg + "\n");
  serial_log_file.flush();

  //This is the tricky part. The Script is terminated using
  // an exception. This needs to be caught.
  //try{
  YIELD();
  //    if (counter < time){
  //        log.log(counter);
  //        printStatistics();
  //        counter += powertracker_frequency;
  //  }

  //} catch (e) {
  //Close files.
  //serial_log_file.close();
  //power_tracker_file.close();
  //Rethrow exception again, to end the script.
  //throw('test script killed');
  //log.testOK();
  //}
}
<|endoftext|>


<commit_before>'use strict';

var utils = require('../lib/utils');

module.exports = function(options) {
  return function() {
    /**
     * **bold** message.
     *
     * @return {String}
     * @api public
     */

    this.style('subhead', {type: 'logger'}, function() {
      return this.stylize('bold', arguments);
    });

    /**
     * Get the current time using `.toLocaleTimeString()`.
     *
     * @return {String}
     */

    this.style('time', {type: 'logger'}, function() {
      var time = new Date().toLocaleTimeString();
      return this.bgBlack.white(time) + ' ';
    });

    /**
     * Display a **gray** timestamp.
     *
     * @return {String}
     * @api public
     */

    this.style('timestamp', {type: 'logger'}, function() {
      var args = [].slice.call(arguments);
      args[0] = this.time() + this.gray(args[0]);
      return args;
    });

    /**
     * Display a **gray** informational message.
     *
     * @return {String}
     * @api public
     */

    this.style('inform', {type: 'logger'}, function() {
      return this.stylize('gray', arguments);
    });

    /**
     * Display a **cyan** informational message.
     *
     * @return {String}
     * @api public
     */

    this.style('info', {type: 'logger'}, function() {
      return this.stylize('cyan', arguments);
    });

    /**
     * Display a **yellow** warning message.
     *
     * @return {String}
     * @api public
     */

    this.style('warn', {type: 'logger'}, function() {
      return this.stylize('yellow', arguments);
    });

    /**
     * Display a **red** error message.
     *
     * @return {String}
     * @api public
     */

    this.style('error', {type: 'logger'}, function() {
      return this.stylize('red', arguments);
    });

    /**
     * Display a **green** success message.
     *
     * @return {String}
     * @api public
     */

    this.style('success', {type: 'logger'}, function() {
      return this.stylize('green', arguments);
    });

    /**
     * Display a **red** error message and exit with `process.exit(1)`

     * @return {String}
     * @api public
     */

    this.style('fatal', {type: 'logger'}, function() {
      var args = [].slice.call(arguments);
      args[0] = (this.red('  ' + this.runner + ' [FAIL]:') + this.gray(' · ') + args[0]);
      console.log();
      console.log.apply(this, args);
      process.exit(1);
    });
  };
};
<commit_msg>override default `.log` method with custom stylized `.log` method<commit_after>'use strict';

var utils = require('../lib/utils');

module.exports = function(options) {
  return function() {
    /**
     * **bold** message.
     *
     * @return {String}
     * @api public
     */

    this.style('log', {type: 'logger'}, function() {
      return this.stylize('bold', arguments);
    });

    /**
     * **bold** message.
     *
     * @return {String}
     * @api public
     */

    this.style('subhead', {type: 'logger'}, function() {
      return this.stylize('bold', arguments);
    });

    /**
     * Get the current time using `.toLocaleTimeString()`.
     *
     * @return {String}
     */

    this.style('time', {type: 'logger'}, function() {
      var time = new Date().toLocaleTimeString();
      return this.bgBlack.white(time) + ' ';
    });

    /**
     * Display a **gray** timestamp.
     *
     * @return {String}
     * @api public
     */

    this.style('timestamp', {type: 'logger'}, function() {
      var args = [].slice.call(arguments);
      args[0] = this.time() + this.gray(args[0]);
      return args;
    });

    /**
     * Display a **gray** informational message.
     *
     * @return {String}
     * @api public
     */

    this.style('inform', {type: 'logger'}, function() {
      return this.stylize('gray', arguments);
    });

    /**
     * Display a **cyan** informational message.
     *
     * @return {String}
     * @api public
     */

    this.style('info', {type: 'logger'}, function() {
      return this.stylize('cyan', arguments);
    });

    /**
     * Display a **yellow** warning message.
     *
     * @return {String}
     * @api public
     */

    this.style('warn', {type: 'logger'}, function() {
      return this.stylize('yellow', arguments);
    });

    /**
     * Display a **red** error message.
     *
     * @return {String}
     * @api public
     */

    this.style('error', {type: 'logger'}, function() {
      return this.stylize('red', arguments);
    });

    /**
     * Display a **green** success message.
     *
     * @return {String}
     * @api public
     */

    this.style('success', {type: 'logger'}, function() {
      return this.stylize('green', arguments);
    });

    /**
     * Display a **red** error message and exit with `process.exit(1)`

     * @return {String}
     * @api public
     */

    this.style('fatal', {type: 'logger'}, function() {
      var args = [].slice.call(arguments);
      args[0] = (this.red('  ' + this.runner + ' [FAIL]:') + this.gray(' · ') + args[0]);
      console.log();
      console.log.apply(this, args);
      process.exit(1);
    });
  };
};
<|endoftext|>