<commit_before>//
//  game-world.js
//
//  Created by Karol Kozub on 2014-12-06.
//  Copyright (c) 2014 Karol Kozub. All rights reserved.
//

(function () {
    "use strict";

    var GameWorld = function () {
	this._node = document.createElement("div");
	this._node.className = "game-world";
	this._relativeNode = document.createElement("div");
	this._relativeNode.className = "relative";
	this._node.appendChild(this._relativeNode);
	this._backgroundCanvas = document.createElement("canvas");
	this._backgroundCanvas.className = "background";
	this._relativeNode.appendChild(this._backgroundCanvas);
	this._crosshair = new window.Crosshair();
	this._crosshair.attachTo(this._relativeNode);
	this._player = new window.Player();
	this._player.attachTo(this._relativeNode);
	this._enemies = [];
	this._bullets = [];
	this._deadEnemies = [];
	this._numberOfKills = 0;
	this._tick = 0;
    };

    GameWorld.prototype.attachTo = function (node) {
	var self = this;
	window.addEventListener("resize", function () {
	    delete self._size;
	});
	node.appendChild(this._node);
	this._player.setPosition({x: this.size().width / 2, y: this.size().height / 2});
	this._backgroundCanvas.width = this.size().width;
	this._backgroundCanvas.height = this.size().height;
    };

    GameWorld.prototype.update = function (tick, input) {
	var self = this;
	this._tick = tick;
	this._crosshair.handleInput(input);
	this._handleInput(input);
	this._player.handleInput(input);
	this._player.updateWithBoundingBox(this.box());
	this._enemies.forEach(function (enemy) {
	    enemy.update(tick, self._player.position());

	    if (enemy.hitTestBox(self._player.box())) {
		var recoil = {
		    x: -1 + Math.random() * 2,
		    y: -1 + Math.random() * 2
		};

		self._player.loseHealth();
		self._player.slowDown();
		self._player.handleRecoil(recoil);
		self._player.drawBloodOntoCanvas(self._backgroundCanvas, recoil);
	    }
	});
	this._bullets = this._bullets.filter(function (bullet) {
	    bullet.update();

	    var bulletHitEnemy = false;
	    var bulletIsOutsideWorld = bullet.position().x < 0 || bullet.position().x > self.size().width || bullet.position().y < 0 || bullet.position().y > self.size().height;

	    self._enemies.forEach(function (enemy) {
		if (bullet.didCrossObject(enemy)) {
		    var recoil = {
			x: bullet.velocity().x * 0.02 -0.5 + Math.random(),
			y: bullet.velocity().y * 0.02 -0.5 + Math.random()
		    };

		    bulletHitEnemy = true;
		    enemy.loseHealth();
		    enemy.handleRecoil(recoil);
		    enemy.drawBloodOntoCanvas(self._backgroundCanvas, bullet.velocity());
		}
	    });

	    if (bulletHitEnemy || bulletIsOutsideWorld) {
		bullet.detachFrom(self._relativeNode);
		return false;
	    } else {
		return true;
	    }
	});
	this._enemies = this._enemies.filter(function (enemy) {
	    if (enemy.isDead()) {
		enemy.detachFrom(self._relativeNode);
		enemy.drawDeadBodyOntoCanvas(self._backgroundCanvas);
		enemy.drawBloodOntoCanvas(self._backgroundCanvas, {x: 0, y: 0});
		self._numberOfKills += 1;
		return false;
	    } else {
		return true;
	    }
	});
	this._addEnemies();
    };

    GameWorld.prototype.size = function () {
	if (!this._size) {
	    this._size = {width: this._node.clientWidth, height: this._node.clientHeight};
	}
	return this._size;
    };

    GameWorld.prototype.box = function () {
	return {x: 0, y: 0, width: this.size().width, height: this.size().height};
    };

    GameWorld.prototype.difficulty = function () {
	return 1 + this._tick / 3600;
    };

    GameWorld.prototype._handleInput = function (input) {
	if (input.isMouseDown) {
	    this._shootFromPositionToPosition(this._player.position(), input.mousePosition);
	}
    };

    GameWorld.prototype._shootFromPositionToPosition = function (fromPosition, toPosition) {
	var distance = {x: toPosition.x -  fromPosition.x, y: toPosition.y -  fromPosition.y};
	var speed = 20 + Math.random() * 10;
	var angle = Math.PI / 2 - Math.atan2(distance.x, distance.y) + (Math.random() - 0.5) * Math.PI / 100;

	var bullet = new window.Bullet();
	bullet.setPosition({x: fromPosition.x, y: fromPosition.y});
	bullet.setVelocity({x: speed * Math.cos(angle), y: speed * Math.sin(angle)});
	bullet.setRotation(angle);
	bullet.attachTo(this._relativeNode);
	this._bullets.push(bullet);
    };

    GameWorld.prototype._addEnemies = function () {
	if (Math.random() < 0.025) {
	    var enemy = this._newRandomEnemy();
	    var margin = 10;
	    var x = -margin + Math.random() * (this.size().width  + 2 * margin);
	    var y = -margin + Math.random() * (this.size().height + 2 * margin);

	    if (Math.random() < 0.5) {
		x = Math.random() < 0.5 ? -margin : (this.size().width  + margin);
	    } else {
	    	y = Math.random() < 0.5 ? -margin : (this.size().height + margin);
	    }

	    enemy.setPosition({x: x, y: y});
	    enemy.attachTo(this._relativeNode);
	    this._enemies.push(enemy);
	}
    };

    GameWorld.prototype._newRandomEnemy = function () {
	var type = Math.floor(Math.random() * 3);

	switch (type) {
	case 0:
	    return new window.SpiderEnemy(this.difficulty());
	case 1:
	    return new window.WormEnemy(this.difficulty());
	case 2:
	default:
	    return new window.Enemy(this.difficulty());
	}
    }

    GameWorld.prototype.isGameOver = function () {
	return this._player && this._player.isDead();
    };

    GameWorld.prototype.numberOfKills = function () {
	return this._numberOfKills;
    };

    GameWorld.prototype.numberOfEnemies = function () {
	return this._enemies.length;
    };

    GameWorld.prototype.playerHealth = function () {
	return this._player.health();
    };

    window.GameWorld = GameWorld;
}());
<commit_msg>Added background canvas resizing when needed.<commit_after>//
//  game-world.js
//
//  Created by Karol Kozub on 2014-12-06.
//  Copyright (c) 2014 Karol Kozub. All rights reserved.
//

(function () {
    "use strict";

    var GameWorld = function () {
	this._node = document.createElement("div");
	this._node.className = "game-world";
	this._relativeNode = document.createElement("div");
	this._relativeNode.className = "relative";
	this._node.appendChild(this._relativeNode);
	this._backgroundCanvas = document.createElement("canvas");
	this._backgroundCanvas.className = "background";
	this._relativeNode.appendChild(this._backgroundCanvas);
	this._crosshair = new window.Crosshair();
	this._crosshair.attachTo(this._relativeNode);
	this._player = new window.Player();
	this._player.attachTo(this._relativeNode);
	this._enemies = [];
	this._bullets = [];
	this._deadEnemies = [];
	this._numberOfKills = 0;
	this._tick = 0;
    };

    GameWorld.prototype.attachTo = function (node) {
	var self = this;
	window.addEventListener("resize", function () {
	    delete self._size;
	});
	node.appendChild(this._node);
	this._player.setPosition({x: this.size().width / 2, y: this.size().height / 2});
	this._backgroundCanvas.width = this.size().width;
	this._backgroundCanvas.height = this.size().height;
    };

    GameWorld.prototype.update = function (tick, input) {
	var self = this;
	this._tick = tick;
	this._crosshair.handleInput(input);
	this._handleInput(input);
	this._player.handleInput(input);
	this._player.updateWithBoundingBox(this.box());
	this._enemies.forEach(function (enemy) {
	    enemy.update(tick, self._player.position());

	    if (enemy.hitTestBox(self._player.box())) {
		var recoil = {
		    x: -1 + Math.random() * 2,
		    y: -1 + Math.random() * 2
		};

		self._player.loseHealth();
		self._player.slowDown();
		self._player.handleRecoil(recoil);
		self._player.drawBloodOntoCanvas(self._backgroundCanvas, recoil);
	    }
	});
	this._bullets = this._bullets.filter(function (bullet) {
	    bullet.update();

	    var bulletHitEnemy = false;
	    var bulletIsOutsideWorld = bullet.position().x < 0 || bullet.position().x > self.size().width || bullet.position().y < 0 || bullet.position().y > self.size().height;

	    self._enemies.forEach(function (enemy) {
		if (bullet.didCrossObject(enemy)) {
		    var recoil = {
			x: bullet.velocity().x * 0.02 -0.5 + Math.random(),
			y: bullet.velocity().y * 0.02 -0.5 + Math.random()
		    };

		    bulletHitEnemy = true;
		    enemy.loseHealth();
		    enemy.handleRecoil(recoil);
		    enemy.drawBloodOntoCanvas(self._backgroundCanvas, bullet.velocity());
		}
	    });

	    if (bulletHitEnemy || bulletIsOutsideWorld) {
		bullet.detachFrom(self._relativeNode);
		return false;
	    } else {
		return true;
	    }
	});
	this._enemies = this._enemies.filter(function (enemy) {
	    if (enemy.isDead()) {
		enemy.detachFrom(self._relativeNode);
		enemy.drawDeadBodyOntoCanvas(self._backgroundCanvas);
		enemy.drawBloodOntoCanvas(self._backgroundCanvas, {x: 0, y: 0});
		self._numberOfKills += 1;
		return false;
	    } else {
		return true;
	    }
	});
	this._addEnemies();
	this._resizeBackgroundCanvasIfNeeded();
    };

    GameWorld.prototype.size = function () {
	if (!this._size) {
	    this._size = {width: this._node.clientWidth, height: this._node.clientHeight};
	}
	return this._size;
    };

    GameWorld.prototype.box = function () {
	return {x: 0, y: 0, width: this.size().width, height: this.size().height};
    };

    GameWorld.prototype.difficulty = function () {
	return 1 + this._tick / 3600;
    };

    GameWorld.prototype._handleInput = function (input) {
	if (input.isMouseDown) {
	    this._shootFromPositionToPosition(this._player.position(), input.mousePosition);
	}
    };

    GameWorld.prototype._shootFromPositionToPosition = function (fromPosition, toPosition) {
	var distance = {x: toPosition.x -  fromPosition.x, y: toPosition.y -  fromPosition.y};
	var speed = 20 + Math.random() * 10;
	var angle = Math.PI / 2 - Math.atan2(distance.x, distance.y) + (Math.random() - 0.5) * Math.PI / 100;

	var bullet = new window.Bullet();
	bullet.setPosition({x: fromPosition.x, y: fromPosition.y});
	bullet.setVelocity({x: speed * Math.cos(angle), y: speed * Math.sin(angle)});
	bullet.setRotation(angle);
	bullet.attachTo(this._relativeNode);
	this._bullets.push(bullet);
    };

    GameWorld.prototype._addEnemies = function () {
	if (Math.random() < 0.025) {
	    var enemy = this._newRandomEnemy();
	    var margin = 10;
	    var x = -margin + Math.random() * (this.size().width  + 2 * margin);
	    var y = -margin + Math.random() * (this.size().height + 2 * margin);

	    if (Math.random() < 0.5) {
		x = Math.random() < 0.5 ? -margin : (this.size().width  + margin);
	    } else {
	    	y = Math.random() < 0.5 ? -margin : (this.size().height + margin);
	    }

	    enemy.setPosition({x: x, y: y});
	    enemy.attachTo(this._relativeNode);
	    this._enemies.push(enemy);
	}
    };

    GameWorld.prototype._newRandomEnemy = function () {
	var type = Math.floor(Math.random() * 3);

	switch (type) {
	case 0:
	    return new window.SpiderEnemy(this.difficulty());
	case 1:
	    return new window.WormEnemy(this.difficulty());
	case 2:
	default:
	    return new window.Enemy(this.difficulty());
	}
    };

    GameWorld.prototype._resizeBackgroundCanvasIfNeeded = function () {
	var parentWidth = this._backgroundCanvas.parentElement.offsetWidth;
	var parentHeight = this._backgroundCanvas.parentElement.offsetHeight;
	var shouldBeWider  = this._backgroundCanvas.width  < parentWidth
	var shouldBeHigher = this._backgroundCanvas.height < parentHeight;

	if (shouldBeWider || shouldBeHigher) {
	    var image = new window.Image();
	    var self = this;
	    image.src = this._backgroundCanvas.toDataURL();
	    image.onload = function () {
		self._backgroundCanvas.width = Math.max(parentWidth, self._backgroundCanvas.width);
		self._backgroundCanvas.height = Math.max(parentHeight, self._backgroundCanvas.height);
		self._backgroundCanvas.getContext("2d").drawImage(image, 0, 0);
	    };
	}
    };

    GameWorld.prototype.isGameOver = function () {
	return this._player && this._player.isDead();
    };

    GameWorld.prototype.numberOfKills = function () {
	return this._numberOfKills;
    };

    GameWorld.prototype.numberOfEnemies = function () {
	return this._enemies.length;
    };

    GameWorld.prototype.playerHealth = function () {
	return this._player.health();
    };

    window.GameWorld = GameWorld;
}());
<|endoftext|>


<commit_before>#!/usr/bin/env node
"use strict";

const ghpages = require("gh-pages");
const path = require("path");
const yargs = require("yargs");
const argv = yargs.options({
        "b": {
            alias: "build",
            describe: "Build the project using prod build settings",
            boolean: true
        },
        "d": {
            alias: "deploy",
            describe: "Deploy the project to gh-pages",
            boolean: true
        },
        "q": {
            alias: "quiet",
            describe: "Minimal output from commands",
            boolean: true
        }
    })
    .help("h").alias("h", "help")
    .usage("Usage: $0 [-b] [-d]")
    .argv;

// Local variables:
let runBuild = argv.b;
let runDeploy = argv.d;
let quiet = argv.q;

if (!(runBuild || runDeploy)) {
    yargs.showHelp();
    process.exit();
}

if (runBuild) {
    console.log("Building for production...");
    runCommand("npm", ["run", "build:prod"]);
}

if (runDeploy) {
    console.log("Deploying to gh-pages...");
    ghpages.publish(path.join(__dirname, "dist"),
        {
            message: "Auto-generated commit",
            logger: function(message) {
                console.log(message);
            }
        },
        function(err) {
            if (err) {
                console.error(`Finished with errors:\n${err}`);
                return;
            }
            console.log("Done!");
        }
    );
}

// Helper functions:
function runCommand(command, args) {
    let options = {};
    if (!quiet) {
        options["stdio"] = "inherit";
    }
    let result = cp.spawnSync(command, args, options);
    return result.status;
}
<commit_msg>Not updating this for a long-ass time<commit_after>#!/usr/bin/env node
"use strict";

const ghpages = require("gh-pages");
const path = require("path");
const cp = require("child_process");
const yargs = require("yargs");
const argv = yargs.options({
        "b": {
            alias: "build",
            describe: "Build the project using prod build settings",
            boolean: true
        },
        "q": {
            alias: "quiet",
            describe: "Minimal output from commands",
            boolean: true
        }
    })
    .help("h").alias("h", "help")
    .usage("Usage: $0 [-b] [-d]")
    .argv;

// Local variables:
let runBuild = argv.b;
let quiet = argv.q;

if (runBuild) {
    console.log("Building for production...");
    runCommand("npm", ["run", "build:prod"]);
}

console.log("\nDeploying to gh-pages...");
ghpages.publish(path.join(__dirname, "dist"),
    {
        message: "Deployment script commit",
        logger: function(message) {
            console.log(message);
        }
    },
    function(err) {
        if (err) {
            console.error(`Finished with errors:\n${err}`);
            return;
        }
        console.log("Done!");
    }
);

// Helper functions:
function runCommand(command, args) {
    let options = {};
    if (!quiet) {
        options["stdio"] = "inherit";
    }
    let result = cp.spawnSync(command, args, options);
    return result.status;
}
<|endoftext|>


<commit_before>'use strict';

const uuid = require('uuid');
const baseX = require('base-x');
const base62 = baseX('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
const OUTPUT_LENGTH = 22;
const UUID_LENGTH = 32;

class UUID62 {
	constructor() {
		this.base = base62;
	}

	get uuid() {
		return uuid;
	}

	get baseX() {
		return baseX;
	}

	get customBase() {
		return this.base;
	}

	set customBase(base) {
		this.base = base;
	}

	get length() {
		return OUTPUT_LENGTH;
	}

	get uuidLength() {
		return UUID_LENGTH;
	}

	v4() {
		const args = Array.prototype.slice.call(arguments);
		if (!args[1]) {
			// make sure we use a buffer to avoid getting a uuid with dashes
			args[1] = new Buffer(16);
		}
		const id = uuid.v4.apply(this, args);
		return this.encode(id);
	}

	v1() {
		const args = Array.prototype.slice.call(arguments);
		if (!args[1]) {
			// make sure we use a buffer to avoid getting a uuid with dashes
			args[1] = new Buffer(16);
		}
		const id = uuid.v1.apply(this, args);
		return this.encode(id);
	}

	encode(input, encoding) {
		encoding = encoding || 'hex';
		if (typeof input === 'string') {
			// remove the dashes to save some space
			input = new Buffer(input.replace(/-/g, ''), encoding);
		}
		return ensureLength(this.base.encode(input), OUTPUT_LENGTH);
	}

	decode(input, encoding) {
		encoding = encoding || 'hex';
		const res = ensureLength(
			new Buffer(this.base.decode(input)).toString(encoding),
			UUID_LENGTH
		);
		// insert dashes on return
		return `${res.slice(0, 8)}-${res.slice(8, 12)}-${res.slice(12, 16)}-${res.slice(16, 20)}-${res.slice(20)}`;
	}
}

function ensureLength(input, targetLength) {
	input = input.toString();
	return `${'0'.repeat(32)}${input}`.slice(-targetLength);
}

module.exports = new UUID62();
<commit_msg>replace unnecessary getters<commit_after>'use strict';

const uuid = require('uuid');
const baseX = require('base-x');
const base62 = baseX('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
const OUTPUT_LENGTH = 22;
const UUID_LENGTH = 32;

class UUID62 {
	constructor() {
		this.base = base62;
		// expose underlying methods for convenience
		this.uuid = uuid;
		this.baseX = baseX;
	}

	get customBase() {
		return this.base;
	}

	set customBase(base) {
		this.base = base;
	}

	get length() {
		return OUTPUT_LENGTH;
	}

	get uuidLength() {
		return UUID_LENGTH;
	}

	v4() {
		const args = Array.prototype.slice.call(arguments);
		if (!args[1]) {
			// make sure we use a buffer to avoid getting a uuid with dashes
			args[1] = new Buffer(16);
		}
		const id = uuid.v4.apply(this, args);
		return this.encode(id);
	}

	v1() {
		const args = Array.prototype.slice.call(arguments);
		if (!args[1]) {
			// make sure we use a buffer to avoid getting a uuid with dashes
			args[1] = new Buffer(16);
		}
		const id = uuid.v1.apply(this, args);
		return this.encode(id);
	}

	encode(input, encoding) {
		encoding = encoding || 'hex';
		if (typeof input === 'string') {
			// remove the dashes to save some space
			input = new Buffer(input.replace(/-/g, ''), encoding);
		}
		return ensureLength(this.base.encode(input), OUTPUT_LENGTH);
	}

	decode(input, encoding) {
		encoding = encoding || 'hex';
		const res = ensureLength(
			new Buffer(this.base.decode(input)).toString(encoding),
			UUID_LENGTH
		);
		// insert dashes on return
		return `${res.slice(0, 8)}-${res.slice(8, 12)}-${res.slice(12, 16)}-${res.slice(16, 20)}-${res.slice(20)}`;
	}
}

function ensureLength(input, targetLength) {
	input = input.toString();
	return `${'0'.repeat(32)}${input}`.slice(-targetLength);
}

module.exports = new UUID62();
<|endoftext|>


<commit_before>/*! Graphics2D CatmullRom 1.0
 *  Author: Keyten aka Dmitriy Miroshnichenko
 *  License: MIT / LGPL
 */
(function(window, $, undefined){

	var catmullRom = function(numbers, curves, path){
		this._arguments = numbers;
		this._points = 20;
		this._path = path;
		this.update = path.update.bind(path);

		this.h1x = numbers[0];
		this.h1y = numbers[1];
		this.h2x = numbers[5];
		this.h2y = numbers[7];
		this.x1 = numbers[2]
		this.y1 = numbers[3];
		this.x2 = numbers[4];
		this.y2 = numbers[5];
	}

	$.util.pathFunctions.catmullRom = catmullRom;

	catmullRom.prototype.process = function(ctx){
		var max = this._points,
			step = 100 / max,
			point;
		for(var i = 0; i <= 100; i+=step){
			point = this.pointAt(i / 100);
			ctx.lineTo(point.x, point.y);
		}
		if(i-step < 100){
			point = this.pointAt(1);
			ctx.lineTo(point.x, point.y);
		}
	}

	catmullRom.prototype.pointAt = function(t){
		return catmullRom.pointAt.apply(0, this._arguments.concat([t]));
	}

	catmullRom.prototype.length = function(){
		var max = this._points,
			step = 100 / max,
			point,
			length = 0,
			last;
		point = this.pointAt(0);
		last = point;
		for(var i = 1; i <= 100; i+=step){
			point = this.pointAt(i / 100);
			length += Math.sqrt( Math.pow(point.x - last.x, 2) + Math.pow(point.y - last.y, 2) );
			last = point;
		}
		return length;
	}

	// utils
	catmullRom.prototype.arguments = function(value){
		if(value === undefined)
			return this._arguments;
		if(arguments.length > 1)
			value = Array.prototype.slice.call(arguments);
		this._arguments = value;
		this.h1x = value[0];
		this.h1y = value[1];
		this.h2x = value[5];
		this.h2y = value[7];
		this.x1 = value[2];
		this.y1 = value[3];
		this.x2 = value[4];
		this.y2 = value[5];
		this.update();
		return this;
	}

	catmullRom.parameters = ['h1x', 'h1y', 'x1', 'y1', 'x2', 'y2', 'h2x', 'h2y'];
	catmullRom.prototype.set = function(name, value){
		var index = catmullRom.parameters.indexOf(name);
		this._arguments[index] = value;
		this[name] = value;
		this.update();
		return this;
	}

	// CR
	catmullRom.pointAt = function(x1, y1, x2, y2, x3, y3, x4, y4, t){
		return {
			x: 0.5 * ((-x1 + 3*x2 - 3*x3 + x4)*t*t*t
					+ (2*x1 - 5*x2 + 4*x3 - x4)*t*t
					+ (-x1 + x3)*t
					+ 2*x2),
			y: 0.5 * ((-y1 + 3*y2 - 3*y3 + y4)*t*t*t
					+ (2*y1 - 5*y2 + 4*y3 - y4)*t*t
					+ (-y1 + y3)*t
					+ 2*y2),
		};
	}

})(window, Graphics2D);<commit_msg>Added name field to the catmullrom curve<commit_after>/*! Graphics2D CatmullRom 1.0
 *  Author: Keyten aka Dmitriy Miroshnichenko
 *  License: MIT / LGPL
 */
(function(window, $, undefined){

	var catmullRom = function(numbers, curves, path){
		this._arguments = numbers;
		this._points = 20;
		this._path = path;
		this.update = path.update.bind(path);

		this.name = 'catmullRom';
		this.h1x = numbers[0];
		this.h1y = numbers[1];
		this.h2x = numbers[5];
		this.h2y = numbers[7];
		this.x1 = numbers[2]
		this.y1 = numbers[3];
		this.x2 = numbers[4];
		this.y2 = numbers[5];
	}

	$.util.pathFunctions.catmullRom = catmullRom;

	catmullRom.prototype.process = function(ctx){
		var max = this._points,
			step = 100 / max,
			point;
		for(var i = 0; i <= 100; i+=step){
			point = this.pointAt(i / 100);
			ctx.lineTo(point.x, point.y);
		}
		if(i-step < 100){
			point = this.pointAt(1);
			ctx.lineTo(point.x, point.y);
		}
	}

	catmullRom.prototype.pointAt = function(t){
		return catmullRom.pointAt.apply(0, this._arguments.concat([t]));
	}

	catmullRom.prototype.length = function(){
		var max = this._points,
			step = 100 / max,
			point,
			length = 0,
			last;
		point = this.pointAt(0);
		last = point;
		for(var i = 1; i <= 100; i+=step){
			point = this.pointAt(i / 100);
			length += Math.sqrt( Math.pow(point.x - last.x, 2) + Math.pow(point.y - last.y, 2) );
			last = point;
		}
		return length;
	}

	// utils
	catmullRom.prototype.arguments = function(value){
		if(value === undefined)
			return this._arguments;
		if(arguments.length > 1)
			value = Array.prototype.slice.call(arguments);
		this._arguments = value;
		this.h1x = value[0];
		this.h1y = value[1];
		this.h2x = value[5];
		this.h2y = value[7];
		this.x1 = value[2];
		this.y1 = value[3];
		this.x2 = value[4];
		this.y2 = value[5];
		this.update();
		return this;
	}

	catmullRom.parameters = ['h1x', 'h1y', 'x1', 'y1', 'x2', 'y2', 'h2x', 'h2y'];
	catmullRom.prototype.set = function(name, value){
		var index = catmullRom.parameters.indexOf(name);
		this._arguments[index] = value;
		this[name] = value;
		this.update();
		return this;
	}

	// CR
	catmullRom.pointAt = function(x1, y1, x2, y2, x3, y3, x4, y4, t){
		return {
			x: 0.5 * ((-x1 + 3*x2 - 3*x3 + x4)*t*t*t
					+ (2*x1 - 5*x2 + 4*x3 - x4)*t*t
					+ (-x1 + x3)*t
					+ 2*x2),
			y: 0.5 * ((-y1 + 3*y2 - 3*y3 + y4)*t*t*t
					+ (2*y1 - 5*y2 + 4*y3 - y4)*t*t
					+ (-y1 + y3)*t
					+ 2*y2),
		};
	}

})(window, Graphics2D);<|endoftext|>


<commit_before>"use strict";

var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database(':memory:');

db.serialize(function() {
  db.run("CREATE TABLE lorem (info TEXT)");

  db.run("INSERT INTO lorem VALUES('simple run')");

  var stmt = db.prepare("INSERT INTO lorem VALUES (?)");
  for (var i = 0; i < 10; i++) {
      stmt.run("Ipsum " + i);
  }
  stmt.finalize();

  db.each("SELECT rowid AS id, info FROM lorem", function(err, row) {
      console.log(row.id + ": " + row.info);
  });

});

db.close();
<commit_msg>Modifico test sqlite para probar con db en archivo<commit_after>"use strict";

var sqlite3 = require('sqlite3').verbose();
//var db = new sqlite3.Database(':memory:');
var db = new sqlite3.Database('PEPE.db', sqlite3.OPEN_CREATE |sqlite3.OPEN_READWRITE);

console.log("db", db);

db.serialize(function() {
  db.run("DROP TABLE IF EXISTS lorem");
  db.run("CREATE TABLE lorem (info TEXT)");

  db.run("INSERT INTO lorem VALUES('simple run')");

  var stmt = db.prepare("INSERT INTO lorem VALUES (?)");
  console.log("stmt", stmt);
  for (var i = 0; i < 10; i++) {
      stmt.run("Ipsum " + i);
  }
  stmt.finalize();

  db.each("SELECT rowid AS id, info FROM lorem", function(err, row) {
      console.log(row.id + ": " + row.info);
  });

});

db.close();
<|endoftext|>


<commit_before>angular.module('yds').directive('ydsPie', ['Data', 'Filters', function(Data, Filters){
    return {
        restrict: 'E',
        scope: {
            projectId: '@',     //id of the project that the data belong
            viewType: '@',      //name of the array that contains the visualised data
            lang: '@',          //lang of the visualised data

            extraParams: '=',   //extra attributes to pass to the API, if needed

            showLegend: '@',    //enable or disable the chart's legend
            exporting: '@',     //enable or disable the export of the chart
            elementH: '@',      //set the height of the component
            titleSize: '@',     //the size of the chart's main title

            addToBasket: '@',   //enable or disable "add to basket" functionality, values: true, false
            basketBtnX: '@',    //x-axis position of the basket button
            basketBtnY: '@',    //y-axis position of the basket button

            embeddable: '@',    //enable or disable the embedding of the component
            embedBtnX: '@',     //x-axis position of the embed button
            embedBtnY: '@',     //y-axis position of the embed button
            popoverPos: '@'     //the side of the embed button from which the embed information window will appear
        },
        templateUrl: ((typeof Drupal != 'undefined')? Drupal.settings.basePath  + Drupal.settings.yds_project.modulePath  +'/' :'') +  'templates/pie.html',
        link: function (scope, element, attrs) {
            var pieContainer = angular.element(element[0].querySelector('.pie-container'));

            //create a random id for the element that will render the chart
            var elementId = "pie" + Data.createRandomId();
            pieContainer[0].id = elementId;

            var projectId = scope.projectId;
            var viewType = scope.viewType;
            var lang = scope.lang;
            var showLegend = scope.showLegend;
            var exporting = scope.exporting;
            var elementH = scope.elementH;
            var titleSize = scope.titleSize;
            var extraParams = scope.extraParams;

            // If extra params exist, add them to Filters
            if (!_.isUndefined(extraParams) && !_.isEmpty(extraParams)) {
                Filters.addExtraParamsFilter(elementId, extraParams);
            }

            //check if the projectId is defined, else stop the process
            if (_.isUndefined(projectId) || projectId.trim()=="") {
                scope.ydsAlert = "The YDS component is not properly configured. " +
                    "Please check the corresponding documentation section";
                return false;
            }

            //check if pie-type attribute is empty and assign the default value
            if(_.isUndefined(viewType) || viewType.trim()=="")
                viewType = "default";

            //check if the language attr is defined, else assign default value
            if(_.isUndefined(lang) || lang.trim()=="")
                lang = "en";

            //check if the showLegend attr is defined, else assign default value
            if(_.isUndefined(showLegend) || (showLegend!="true" && showLegend!="false"))
                showLegend = "true";

            //check if the exporting attr is defined, else assign default value
            if(_.isUndefined(exporting) || (exporting!="true" && exporting!="false"))
                exporting = "true";

            //check if the component's height attr is defined, else assign default value
            if(_.isUndefined(elementH) || _.isNaN(elementH))
                elementH = 200;

            //check if the component's title size attr is defined, else assign default value
            if(_.isUndefined(titleSize) || titleSize.length == 0 || _.isNaN(titleSize))
                titleSize = 18;

            //set the height of the chart
            pieContainer[0].style.height = elementH + 'px';

            //get the pie data from the server
            Data.getProjectVis("pie", scope.projectId, viewType, lang, extraParams)
                .then(function(response) {
                    var pieData = response.data.data;
                    var pieSeries = response.data.series;
                    var pieTitleAttr = _.first(response.view).attribute;
                    var pieTitle = Data.deepObjSearch(response.data, pieTitleAttr);

                    //check if the component is properly rendered
                    if (_.isUndefined(pieData) || !_.isArray(pieData) || _.isUndefined(pieSeries) || _.isUndefined(pieTitle)) {
                        scope.ydsAlert = "The YDS component is not properly configured. " +
                            "Please check the corresponding documentation section";
                        return false;
                    }

                    var options = {
                        chart: {
                            plotBackgroundColor: null,
                            plotBorderWidth: null,
                            plotShadow: false,
                            type: 'pie',
                            renderTo: elementId
                        },
                        title: {
                            text: pieTitle,
                            style: {
                                fontSize: titleSize + "px"
                            }
                        },
                        tooltip: {
                            pointFormat: '({point.y}) {point.percentage:.1f}%'
                        },
                        legend: {
                            enabled: (showLegend === "true")
                        },
                        exporting: {
                            buttons: {
                                contextButton: {
                                    symbol: 'url(' + ((typeof Drupal != 'undefined')? Drupal.settings.basePath + Drupal.settings.yds_project.modulePath + '/' :'') + 'img/fa-download-small.png)',
                                    symbolX: 12,
                                    symbolY: 12
                                }
                            },
                            enabled: (exporting === "true")
                        },
                        plotOptions: {
                            pie: {
                                allowPointSelect: true,
                                showInLegend: (showLegend === "true"),
                                cursor: 'pointer',
                                dataLabels: {
                                    enabled: true,
                                    format: '{point.name}: {point.percentage:.1f} %',
                                    style: {
                                        color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                                    }
                                }
                            }
                        },
                        series: [{
                            name: pieSeries,
                            colorByPoint: true,
                            data: pieData
                        }]
                    };

                    var chart = new Highcharts.Chart(options);
                }, function(error) {
                    if (_.isNull(error) || _.isUndefined(error) || _.isUndefined(error.message))
                        scope.ydsAlert = "An error has occurred, please check the configuration of the component";
                    else
                        scope.ydsAlert = error.message;
                });
        }
    };
}]);<commit_msg>Limit pie chart data label length to 45 characters<commit_after>angular.module('yds').directive('ydsPie', ['Data', 'Filters', function(Data, Filters){
    return {
        restrict: 'E',
        scope: {
            projectId: '@',     //id of the project that the data belong
            viewType: '@',      //name of the array that contains the visualised data
            lang: '@',          //lang of the visualised data

            extraParams: '=',   //extra attributes to pass to the API, if needed

            showLegend: '@',    //enable or disable the chart's legend
            exporting: '@',     //enable or disable the export of the chart
            elementH: '@',      //set the height of the component
            titleSize: '@',     //the size of the chart's main title

            addToBasket: '@',   //enable or disable "add to basket" functionality, values: true, false
            basketBtnX: '@',    //x-axis position of the basket button
            basketBtnY: '@',    //y-axis position of the basket button

            embeddable: '@',    //enable or disable the embedding of the component
            embedBtnX: '@',     //x-axis position of the embed button
            embedBtnY: '@',     //y-axis position of the embed button
            popoverPos: '@'     //the side of the embed button from which the embed information window will appear
        },
        templateUrl: ((typeof Drupal != 'undefined')? Drupal.settings.basePath  + Drupal.settings.yds_project.modulePath  +'/' :'') +  'templates/pie.html',
        link: function (scope, element, attrs) {
            var pieContainer = angular.element(element[0].querySelector('.pie-container'));

            //create a random id for the element that will render the chart
            var elementId = "pie" + Data.createRandomId();
            pieContainer[0].id = elementId;

            var projectId = scope.projectId;
            var viewType = scope.viewType;
            var lang = scope.lang;
            var showLegend = scope.showLegend;
            var exporting = scope.exporting;
            var elementH = scope.elementH;
            var titleSize = scope.titleSize;
            var extraParams = scope.extraParams;

            // If extra params exist, add them to Filters
            if (!_.isUndefined(extraParams) && !_.isEmpty(extraParams)) {
                Filters.addExtraParamsFilter(elementId, extraParams);
            }

            //check if the projectId is defined, else stop the process
            if (_.isUndefined(projectId) || projectId.trim()=="") {
                scope.ydsAlert = "The YDS component is not properly configured. " +
                    "Please check the corresponding documentation section";
                return false;
            }

            //check if pie-type attribute is empty and assign the default value
            if(_.isUndefined(viewType) || viewType.trim()=="")
                viewType = "default";

            //check if the language attr is defined, else assign default value
            if(_.isUndefined(lang) || lang.trim()=="")
                lang = "en";

            //check if the showLegend attr is defined, else assign default value
            if(_.isUndefined(showLegend) || (showLegend!="true" && showLegend!="false"))
                showLegend = "true";

            //check if the exporting attr is defined, else assign default value
            if(_.isUndefined(exporting) || (exporting!="true" && exporting!="false"))
                exporting = "true";

            //check if the component's height attr is defined, else assign default value
            if(_.isUndefined(elementH) || _.isNaN(elementH))
                elementH = 200;

            //check if the component's title size attr is defined, else assign default value
            if(_.isUndefined(titleSize) || titleSize.length == 0 || _.isNaN(titleSize))
                titleSize = 18;

            //set the height of the chart
            pieContainer[0].style.height = elementH + 'px';

            //get the pie data from the server
            Data.getProjectVis("pie", scope.projectId, viewType, lang, extraParams)
                .then(function(response) {
                    var pieData = response.data.data;
                    var pieSeries = response.data.series;
                    var pieTitleAttr = _.first(response.view).attribute;
                    var pieTitle = Data.deepObjSearch(response.data, pieTitleAttr);

                    //check if the component is properly rendered
                    if (_.isUndefined(pieData) || !_.isArray(pieData) || _.isUndefined(pieSeries) || _.isUndefined(pieTitle)) {
                        scope.ydsAlert = "The YDS component is not properly configured. " +
                            "Please check the corresponding documentation section";
                        return false;
                    }

                    var options = {
                        chart: {
                            plotBackgroundColor: null,
                            plotBorderWidth: null,
                            plotShadow: false,
                            type: 'pie',
                            renderTo: elementId
                        },
                        title: {
                            text: pieTitle,
                            style: {
                                fontSize: titleSize + "px"
                            }
                        },
                        tooltip: {
                            pointFormat: '({point.y}) {point.percentage:.1f}%'
                        },
                        legend: {
                            enabled: (showLegend === "true")
                        },
                        exporting: {
                            buttons: {
                                contextButton: {
                                    symbol: 'url(' + ((typeof Drupal != 'undefined')? Drupal.settings.basePath + Drupal.settings.yds_project.modulePath + '/' :'') + 'img/fa-download-small.png)',
                                    symbolX: 12,
                                    symbolY: 12
                                }
                            },
                            enabled: (exporting === "true")
                        },
                        plotOptions: {
                            pie: {
                                allowPointSelect: true,
                                showInLegend: (showLegend === "true"),
                                cursor: 'pointer',
                                dataLabels: {
                                    enabled: true,
                                    formatter: function() {
                                        if (this.key.length > 45) {
                                            this.key = this.key.substring(0, 45) + "…";
                                        }

                                        return this.key + ": " + this.percentage.toFixed(1) + "%";
                                    },
                                    style: {
                                        color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                                    }
                                }
                            }
                        },
                        series: [{
                            name: pieSeries,
                            colorByPoint: true,
                            data: pieData
                        }]
                    };

                    var chart = new Highcharts.Chart(options);
                }, function(error) {
                    if (_.isNull(error) || _.isUndefined(error) || _.isUndefined(error.message))
                        scope.ydsAlert = "An error has occurred, please check the configuration of the component";
                    else
                        scope.ydsAlert = error.message;
                });
        }
    };
}]);<|endoftext|>


<commit_before>window.G = (function () {
    "use strict";

    var Frame = function (elem) {
        if (typeof elem === 'string') {
            elem = document.getElementById(elem);
        }

        var height = elem.scrollHeight;
        var width = elem.scrollWidth;

        var viewAngle = 45;
        var aspect = width / (1.0 * height);
        var near = 0.1;
        var far = 10000;

        this.scene = new THREE.Scene();

        this.camera = new THREE.PerspectiveCamera(viewAngle, aspect, near, far);
        this.camera.position.z = 10;
        this.scene.add(this.camera);

        this.renderer = new THREE.WebGLRenderer();
        this.renderer.setSize(width, height);

        elem.appendChild(this.renderer.domElement);
    };

    Frame.prototype.addNode = function (node) {
        this.scene.add(node.mesh);
    };

    Frame.prototype.addEdge = function (edge) {
        this.scene.add(edge.line);
    };

    Frame.prototype.render = function () {
        this.renderer.render(this.scene, this.camera);
    };

    var Node = function (x, y, z) {
        var geometry = new THREE.SphereGeometry(0.5, 8, 8);
        var material = new THREE.MeshBasicMaterial({color: 0x00ff00, wireframe: true});
        this.mesh = new THREE.Mesh(geometry, material);
        this.mesh.position = new THREE.Vector3(x, y, z);
    };

    Node.prototype.addTo = function (frame) {
        frame.addNode(this);
        return this;
    };

    var Edge = function (n1, n2) {
        var material = new THREE.LineBasicMaterial({color: 0x0000ff});
        var geometry = new THREE.Geometry();

        var n1Coords = n1.mesh.position;
        var n2Coords = n2.mesh.position;

        geometry.vertices.push(n1Coords);
        geometry.vertices.push(n2Coords);

        this.line = new THREE.Line(geometry, material);
    };

    return {
        "Frame": Frame,
        "Node": Node,
        "Edge": Edge,
    };
}());
<commit_msg>No longer wireframe by default<commit_after>window.G = (function () {
    "use strict";

    var Frame = function (elem) {
        if (typeof elem === 'string') {
            elem = document.getElementById(elem);
        }

        var height = elem.scrollHeight;
        var width = elem.scrollWidth;

        var viewAngle = 45;
        var aspect = width / (1.0 * height);
        var near = 0.1;
        var far = 10000;

        this.scene = new THREE.Scene();

        this.camera = new THREE.PerspectiveCamera(viewAngle, aspect, near, far);
        this.camera.position.z = 10;
        this.scene.add(this.camera);

        this.renderer = new THREE.WebGLRenderer();
        this.renderer.setSize(width, height);

        elem.appendChild(this.renderer.domElement);
    };

    Frame.prototype.addNode = function (node) {
        this.scene.add(node.mesh);
    };

    Frame.prototype.addEdge = function (edge) {
        this.scene.add(edge.line);
    };

    Frame.prototype.render = function () {
        this.renderer.render(this.scene, this.camera);
    };

    var Node = function (x, y, z) {
        var geometry = new THREE.SphereGeometry(0.5, 8, 8);
        var material = new THREE.MeshBasicMaterial({color: 0x00ff00});
        this.mesh = new THREE.Mesh(geometry, material);
        this.mesh.position = new THREE.Vector3(x, y, z);
    };

    Node.prototype.addTo = function (frame) {
        frame.addNode(this);
        return this;
    };

    var Edge = function (n1, n2) {
        var material = new THREE.LineBasicMaterial({color: 0x0000ff});
        var geometry = new THREE.Geometry();

        var n1Coords = n1.mesh.position;
        var n2Coords = n2.mesh.position;

        geometry.vertices.push(n1Coords);
        geometry.vertices.push(n2Coords);

        this.line = new THREE.Line(geometry, material);
    };

    return {
        "Frame": Frame,
        "Node": Node,
        "Edge": Edge,
    };
}());
<|endoftext|>


<commit_before>(function () { "use strict";

var _ = require('underscore');
var util = require('util');
var assert = require('assert');
var buscomponent = require('./buscomponent.js');

function Database () {
	this.dbmod = null;
	this.connectionPool = null;
	this.openQueries = 0;
	this.isShuttingDown = false;
}

util.inherits(Database, buscomponent.BusComponent);

Database.prototype._init = function(cb) {
	this.getServerConfig(function(cfg) {
		this.dbmod = cfg['dbmod'] || require('mysql');
		this.connectionPool = this.dbmod.createPool(cfg['db']);
		this.inited = true;
		this.openQueries = 0;

		/*
		 * Note: We don't set isShuttingDown = true here.
		 * This happens so we can actually resurrect the database connection
		 * during the shutdown process temporarily, so other components can complete
		 * any remaining work in progress.
		 */

		cb();
	});
};

Database.prototype.shutdown = buscomponent.listener('localMasterShutdown', function() {
	this.isShuttingDown = true;

	if (this.connectionPool && this.openQueries == 0) {
		this.connectionPool.end();
		this.connectionPool = null;
		this.inited = false;
	}
});

Database.prototype._query = buscomponent.needsInit(function(query, args, cb) {
	this._getConnection(function(err, connection) {
		if (err)
			return cb(err, null);
		connection.query(query, args, function() {
			connection.release();
			cb.apply(this, arguments);
		});
	});
});

Database.prototype._getConnection = buscomponent.needsInit(function(cb) {
	assert.ok (this.connectionPool);

	this.openQueries++;

	var db = this;
	this.connectionPool.getConnection(function(err, conn) {
		if (conn == null)
			return cb(err, null);

		cb(err, {
			query: _.bind(conn.query, conn),
			release: function() {
				db.openQueries--;

				if (db.openQueries == 0 && db.isShuttingDown)
					db.shutdown();

				return conn.release();
			}
		});
	});
});

Database.prototype.escape = buscomponent.needsInit(function(str) {
	return this.dbmod.escape(str);
});

Database.prototype.timeQueryWrap = function(fn, connid, wrapCb) {
	wrapCb = _.bind(wrapCb, this);

	this.getServerConfig(function(cfg) {
		if (cfg && cfg.timeQueries) {
			wrapCb(_.bind(function(query, data, cb) {
				var tStart = new Date().getTime();

				fn(query, data, _.bind(function() {
					var tEnd = new Date().getTime();
					this.message('queryTiming', 'Query ' + connid + ' ' + query.substr(0, 60) + ' took ' + (tEnd - tStart) + ' ms');

					cb.apply(this, arguments);
				}, this));
			}, this));
		} else {
			wrapCb(_.bind(fn, this));
		}
	});
};

Database.prototype.query = buscomponent.provide('dbQuery', ['query', 'args', 'reply'], function(query, data, cb) {
	data = data || [];

	this.timeQueryWrap(_.bind(this._query, this), '*', _.bind(function(f) {
		f(query, data, this.queryCallback(cb, query, data));
	}, this));
});

Database.prototype.getConnection = buscomponent.provide('dbGetConnection', ['reply'], function(conncb) {
	this._getConnection(_.bind(function(err, cn) {
		if (err)
			this.emit('error', err);

		if (!this.dbconnid)
			this.dbconnid = 0;
		var connid = ++this.dbconnid;

		conncb({
			query: _.bind(function(q, data, cb) {
				data = data || [];
				this.timeQueryWrap(_.bind(cn.query, cn), connid, _.bind(function(f) {
					this.emit('dbBoundQueryLog', [q, data]);
					f(q, data, this.queryCallback(cb, q, data));
				}, this));
			}, this),
			release: _.bind(function() {
				cn.release();
			}, this)
		});
	}, this));
});

Database.prototype.queryCallback = function(cb, query, data) {
	return _.bind(function(err, res) {
		var datajson = JSON.stringify(data);

		if (err) {
			var querydesc = '<<' + query + '>>' + (datajson.length <= 1024 ? ' with arguments [' + new Buffer(datajson).toString('base64') + ']' : '');

			this.emit('error', query ? new Error(
				err + '\nCaused by ' + querydesc
			) : err);
		} else if (cb) {
			try {
				_.bind(cb, this)(res);
			} catch (e) {
				this.query('ROLLBACK; SET autocommit = 1');
				this.emit('error', e);
			}
		}
	}, this);
};

exports.Database = Database;

})();
<commit_msg><commit_after>(function () { "use strict";

var _ = require('underscore');
var util = require('util');
var assert = require('assert');
var buscomponent = require('./buscomponent.js');

function Database () {
	this.dbmod = null;
	this.connectionPool = null;
	this.openQueries = 0;
	this.isShuttingDown = false;
}

util.inherits(Database, buscomponent.BusComponent);

Database.prototype._init = function(cb) {
	this.getServerConfig(function(cfg) {
		this.dbmod = cfg['dbmod'] || require('mysql');
		this.connectionPool = this.dbmod.createPool(cfg['db']);
		this.inited = true;
		this.openQueries = 0;

		/*
		 * Note: We don't set isShuttingDown = true here.
		 * This happens so we can actually resurrect the database connection
		 * during the shutdown process temporarily, so other components can complete
		 * any remaining work in progress.
		 */

		cb();
	});
};

Database.prototype.shutdown = buscomponent.listener('localMasterShutdown', function() {
	this.isShuttingDown = true;

	if (this.connectionPool && this.openQueries == 0) {
		this.connectionPool.end();
		this.connectionPool = null;
		this.inited = false;
	}
});

Database.prototype._query = buscomponent.needsInit(function(query, args, cb) {
	this._getConnection(function(err, connection) {
		if (err)
			return cb(err, null);
		connection.query(query, args, function() {
			connection.release();
			cb.apply(this, arguments);
		});
	});
});

Database.prototype._getConnection = buscomponent.needsInit(function(cb) {
	assert.ok (this.connectionPool);

	this.openQueries++;

	var db = this;
	this.connectionPool.getConnection(function(err, conn) {
		if (conn == null)
			return cb(err, null);

		var release = function() {
			db.openQueries--;

			if (db.openQueries == 0 && db.isShuttingDown)
				db.shutdown();

			return conn.release();
		};

		cb(err, {
			query: function(q, args, cb) {
				conn.query(q, args, function(err, res) {
					var exception = null;
					try {
						cb(err, res);
					} catch (e) {
						exception = e;
					}

					if (err || exception) {
						conn.query('ROLLBACK; UNLOCK TABLES; SET autocommit = 1');
						release();
						if (exception)
							this.emit('error', exception);
					}
				});
			}, release: release
		});
	});
});

Database.prototype.escape = buscomponent.needsInit(function(str) {
	return this.dbmod.escape(str);
});

Database.prototype.query = buscomponent.provide('dbQuery', ['query', 'args', 'reply'], function(query, data, cb) {
	data = data || [];

	this._query(query, data, this.queryCallback(cb, query, data));
});

Database.prototype.getConnection = buscomponent.provide('dbGetConnection', ['reply'], function(conncb) {
	this._getConnection(_.bind(function(err, cn) {
		if (err)
			this.emit('error', err);

		if (!this.dbconnid)
			this.dbconnid = 0;
		var connid = ++this.dbconnid;

		conncb({
			query: _.bind(function(q, data, cb) {
				data = data || [];

				this.emit('dbBoundQueryLog', [q, data]);
				cn.query(q, data, this.queryCallback(cb, q, data));
			}, this),
			release: _.bind(function() {
				cn.release();
			}, this)
		});
	}, this));
});

Database.prototype.queryCallback = function(cb, query, data) {
	return _.bind(function(err, res) {
		var datajson = JSON.stringify(data);

		if (err) {
			var querydesc = '<<' + query + '>>' + (datajson.length <= 1024 ? ' with arguments [' + new Buffer(datajson).toString('base64') + ']' : '');

			this.emit('error', query ? new Error(
				err + '\nCaused by ' + querydesc
			) : err);
		} else if (cb) {
			_.bind(cb, this)(res);
		}
	}, this);
};

exports.Database = Database;

})();
<|endoftext|>


<commit_before>'use strict';

/**
 * This file/module contains all configuration for nw things
 */

// NPM modules
var _ = require('lodash');
var nw = require('nw');

// Current app version
var version = require('./../package.json').version;

// Platforms to expect for the compression
var platforms = ['win64', 'osx64', 'linux64'];

/*
 * Helper function to generate our compress object
 */
var nwCompress = function(platforms) {

  // Start up an empty
  var compress = {};

  // Iterate through our platforms and add to the compress array
  _.forEach(platforms, function(platform) {

    // Our zippy ext is different depending on the platform
    var zippyExt = (_.includes(platform, 'win')) ? '.zip' : '.tar.gz';

    // Build our copress object
    compress[platform] = {
      options: {
        archive: 'dist/kalabox-' + platform + '-' + version + zippyExt
      },
      files: [
        {
          expand: true,
          cwd: 'nw/kalabox/' + platform + '/',
          src: ['**'],
          dest: 'Kalabox/'
        }
      ]
    };

  });

  // And finally return that which is compressed
  return compress;

};

/*
 * Helper function to generate our nw-builder objects
 * NOTE: we need to do this because our deps are different for each
 * platform
 */
var nwBuilder = function(platforms) {

  // Start up an empty
  var builder = {};

  // Iterate through our platforms and add to the compress array
  _.forEach(platforms, function(platform) {

    // Build our copress object
    builder[platform] = {
      options: {
        version: '0.12.3',
        platforms: [platform],
        buildDir: 'nw',
      },
      src: [
        './build/*',
        './build/assets/**/*',
        './build/deps/iso/*',
        './build/deps/' + platform + '/*',
        './build/images/**/*',
        './build/node_modules/**/*',
        './build/src/**/*'
      ]
    };

  });

  // And finally return that which is compressed
  return builder;

};

/*
 * Helper function to generate npm build commands for a given platform
 */
var npmBuildCmd = function() {

  // Start a command collector
  var cmd = [];

  // Normal CMDz
  cmd.push('cd ./<%= buildDir %>');
  cmd.push('npm install --production --ignore-script');

  // Give up all the glory
  return cmd.join(' && ');

};

// Return the codes
module.exports = {

  /*
   * Compress our built NW packages
   */
  compress: nwCompress(platforms),

  /*
   * Build our NW packages
   */
  nwjs: nwBuilder(platforms),

  /*
   * Helpers shell commands
   */
  shell: {

    /*
     * Run our NW app from built source
     */
    nw: {
      command: nw.findpath() + ' <%= buildDir %>',
      options: {
        execOptions: {
          maxBuffer: Infinity
        }
      }
    },

    /*
     * Npm install our prod deps before we nwjs task
     */
    build: {
      command: npmBuildCmd()
    }

  },

  /**
   * Clean out the nw dirs
   */
  clean: {
    nw: [
      './nw',
      './dist'
    ]
  }

};
<commit_msg>#928: Need to package in docker images if available<commit_after>'use strict';

/**
 * This file/module contains all configuration for nw things
 */

// NPM modules
var _ = require('lodash');
var nw = require('nw');

// Current app version
var version = require('./../package.json').version;

// Platforms to expect for the compression
var platforms = ['win64', 'osx64', 'linux64'];

/*
 * Helper function to generate our compress object
 */
var nwCompress = function(platforms) {

  // Start up an empty
  var compress = {};

  // Iterate through our platforms and add to the compress array
  _.forEach(platforms, function(platform) {

    // Our zippy ext is different depending on the platform
    var zippyExt = (_.includes(platform, 'win')) ? '.zip' : '.tar.gz';

    // Build our copress object
    compress[platform] = {
      options: {
        archive: 'dist/kalabox-' + platform + '-' + version + zippyExt
      },
      files: [
        {
          expand: true,
          cwd: 'nw/kalabox/' + platform + '/',
          src: ['**'],
          dest: 'Kalabox/'
        }
      ]
    };

  });

  // And finally return that which is compressed
  return compress;

};

/*
 * Helper function to generate our nw-builder objects
 * NOTE: we need to do this because our deps are different for each
 * platform
 */
var nwBuilder = function(platforms) {

  // Start up an empty
  var builder = {};

  // Iterate through our platforms and add to the compress array
  _.forEach(platforms, function(platform) {

    // Build our copress object
    builder[platform] = {
      options: {
        version: '0.12.3',
        platforms: [platform],
        buildDir: 'nw',
      },
      src: [
        './build/*',
        './build/assets/**/*',
        './build/deps/iso/*',
        './build/deps/' + platform + '/*',
        './build/deps/images/*',
        './build/images/**/*',
        './build/node_modules/**/*',
        './build/src/**/*'
      ]
    };

  });

  // And finally return that which is compressed
  return builder;

};

/*
 * Helper function to generate npm build commands for a given platform
 */
var npmBuildCmd = function() {

  // Start a command collector
  var cmd = [];

  // Normal CMDz
  cmd.push('cd ./<%= buildDir %>');
  cmd.push('npm install --production --ignore-script');

  // Give up all the glory
  return cmd.join(' && ');

};

// Return the codes
module.exports = {

  /*
   * Compress our built NW packages
   */
  compress: nwCompress(platforms),

  /*
   * Build our NW packages
   */
  nwjs: nwBuilder(platforms),

  /*
   * Helpers shell commands
   */
  shell: {

    /*
     * Run our NW app from built source
     */
    nw: {
      command: nw.findpath() + ' <%= buildDir %>',
      options: {
        execOptions: {
          maxBuffer: Infinity
        }
      }
    },

    /*
     * Npm install our prod deps before we nwjs task
     */
    build: {
      command: npmBuildCmd()
    }

  },

  /**
   * Clean out the nw dirs
   */
  clean: {
    nw: [
      './nw',
      './dist'
    ]
  }

};
<|endoftext|>


<commit_before>var Maki = require('maki');
var config = require('./config');
var decentral = new Maki( config );

var mongoose = decentral.mongoose;
var Schema = mongoose.Schema;
var ObjectId = Schema.Types.ObjectId;

var Passport = require('maki-passport-local');
var passport = new Passport({ resource: 'Person' });

var Torrent = require('node-torrent-stream');
var readTorrent = require('read-torrent');
var magnet = require('magnet-uri');

var crypto = require('crypto');
var stream = require('stream');

decentral.use( passport );

var Credit = decentral.define('Credit', {
  internal: true,
  attributes: {
    _person: { type: ObjectId , ref: 'Person', required: true },
    role: { type: String , enum: ['host', 'producer', 'guest'] }
  }
});

var Show = decentral.define('Show', {
  attributes: {
    name:    { type: String , max: 35 , required: true , slug: true },
    created: { type: Date , default: Date.now , required: true },
    description: { type: String },
    credits:     [ Credit.Schema ],
    donations: {
      type: { type: String , enum: ['bitcoin'] },
      destination: { type: String , max: 35 }
    }
  },
  icon: 'unmute'
});

var Recording = decentral.define('Recording', {
  attributes: {
    _show:    { type: ObjectId , ref: 'Show', required: false , alias: 'show' },
    title:    { type: String , max: 35 , required: true , slug: true },
    media:    { type: 'File', required: true },
    torrent:  { type: ObjectId , render: { create: false } },
    magnet:   { type: String , max: 24 , render: { create: false } },
    type:     { type: String , max: 5 , render: { create: false } },
    filename: { type: String , max: 255 , render: { create: false } },
    size:   { type: Number , render: { create: false } },
    recorded: { type: Date },
    released: { type: Date , default: Date.now , required: true },
    description: { type: String , format: 'markdown' },
    hash: { type: String , max: 32 , render: { create: false } },
    credits:  [ Credit.Schema ],
    // TODO: remove this in favor of a "Sources" object
    youtube: { type: String }
  },
  icon: 'sound'
});

var Checksum = decentral.define('Checksum', {
  attributes: {
    filename: { type: String },
    _file: { type: ObjectId },
    _recording: { type: ObjectId },
    hash: { type: String , max: 35 },
    type: { type: String , enum: ['md5'] },
    created: { type: Date , default: Date.now }
  },
  icon: 'lock'
});

Recording.post('query', function(next, done) {
  var recordings = this;
  Show.Model.populate( recordings , {
    path: '_show'
  }, function(err, populatedRecordings) {
    if (err) return done(err);
    return next( null , populatedRecordings );
  });
});

Recording.on('file:media', function(media) {
  console.log('received media:', media);

  var torrent = new Torrent({
    name: media.filename,
    trackers: config.torrents.trackers,
    webseeds: config.service.seeds.map(function(x) {
      return x + '/files/' + media._id
    })
  });
  var file = decentral.datastore.gfs.createReadStream({
    _id: media._id
  });
  var torrentstore = decentral.datastore.gfs.createWriteStream({
    mode: 'w',
    filename: media.filename + '.torrent',
    content_type: 'application/x-bittorrent'
  });
  torrentstore.on('error', function(data) {
    console.log('error!' , data );
  });
  torrentstore.on('close', function( torrentFile ) {
    readTorrent('http://localhost:15005/files/' + torrentFile._id , function(err, parsed) {
      if (err) console.error( err );
      var magnetURI = magnet.encode( parsed );

      Recording.patch({
        _id: media.metadata.document
      }, [
        { op: 'add', path: '/torrent' , value: torrentFile._id },
        { op: 'add', path: '/magnet' , value: magnetURI },
        { op: 'add', path: '/type' , value: media.contentType },
        { op: 'add', path: '/filename' , value: media.filename },
        { op: 'add', path: '/size' , value: media.length }
      ], function(err, num) {
        if (err) console.error( err );
        console.log('all done,', num , 'affected');
      });

    });
  });

  torrent.pipe( torrentstore );
  file.pipe( torrent );

});

Recording.pre('create', function(next, done) {
  var recording = this;
  if (!recording.media) return next();

  var db = decentral.datastore.mongoose.connections[0].db;
  var files = db.collection('fs.files');
  files.findOne({ _id: recording.media }, function(err, thing) {
    return Checksum.create({
      filename: thing.filename,
      _file: thing._id,
      hash: thing.md5,
      type: 'md5'
    }, function() {
      recording.hash = thing.md5;
      return next();
    });
  });
});

var Person = decentral.define('Person', {
  attributes: {
    name: {
      given: { type: String , max: 30 },
      family: { type: String , max: 70 }
    },
    username: { type: String , max: 35 , slug: true },
    password: { type: String , max: 70 , masked: true }
  },
  virtuals: {
    'name.full': function() {
      return [ this.name.given , this.name.family ].join(' ');
    }
  },
  icon: 'user'
});

decentral.serve(['http']).start(function() {

  decentral.app.get('/about', function(req, res, next) {
    return res.render('about');
  });

  // TODO: internalize to maki, provide sane defaults
  decentral.app.get('/recordings/:recordingSlug/edit', function(req, res, next) {
    Recording.get({ slug: req.param('recordingSlug') }, function(err, recording) {
      return res.render('recording-edit', {
        item: recording
      });
    });
  });

  decentral.app.post('/recordings/:recordingSlug', function(req, res, next) {
    Recording.update({ slug: req.param('recordingSlug') }, req.body , function(err, recording) {
      req.flash('success', 'Content edited successfully!');
      return res.redirect('/recordings/' + req.param('recordingSlug'));
    });
  });

  decentral.app.get('/search', function(req, res, next) {
    Show.query({}, function(err, shows) {
      return res.send({
        results: shows.map(function(x) {
          return {
            title: x.name
          }
        })
      });
    });
  });
});
<commit_msg>Fix Credit Schema definition.<commit_after>var Maki = require('maki');
var config = require('./config');
var decentral = new Maki( config );

var mongoose = decentral.mongoose;
var Schema = mongoose.Schema;
var ObjectId = Schema.Types.ObjectId;

var Passport = require('maki-passport-local');
var passport = new Passport({ resource: 'Person' });

var Torrent = require('node-torrent-stream');
var readTorrent = require('read-torrent');
var magnet = require('magnet-uri');

var crypto = require('crypto');
var stream = require('stream');

decentral.use( passport );

var Credit = new decentral.mongoose.Schema({
  _person: { type: ObjectId , ref: 'Person', required: true },
  role: { type: String , enum: ['host', 'producer', 'guest'] , required: true }
});

var Show = decentral.define('Show', {
  attributes: {
    name:    { type: String , max: 35 , required: true , slug: true },
    created: { type: Date , default: Date.now , required: true },
    description: { type: String },
    credits:     [ Credit ],
    donations: {
      type: { type: String , enum: ['bitcoin'] },
      destination: { type: String , max: 35 }
    }
  },
  icon: 'unmute'
});

console.log( Credit );

var Recording = decentral.define('Recording', {
  attributes: {
    _show:    { type: ObjectId , ref: 'Show', required: false , alias: 'show' },
    title:    { type: String , max: 35 , required: true , slug: true },
    media:    { type: 'File', required: true },
    torrent:  { type: ObjectId , render: { create: false } },
    magnet:   { type: String , max: 24 , render: { create: false } },
    type:     { type: String , max: 5 , render: { create: false } },
    filename: { type: String , max: 255 , render: { create: false } },
    size:   { type: Number , render: { create: false } },
    recorded: { type: Date },
    released: { type: Date , default: Date.now , required: true },
    description: { type: String , format: 'markdown' },
    hash: { type: String , max: 32 , render: { create: false } },
    credits:  [ Credit ],
    // TODO: remove this in favor of a "Sources" object
    youtube: { type: String }
  },
  icon: 'sound'
});

var Checksum = decentral.define('Checksum', {
  attributes: {
    filename: { type: String },
    _file: { type: ObjectId },
    _recording: { type: ObjectId },
    hash: { type: String , max: 35 },
    type: { type: String , enum: ['md5'] },
    created: { type: Date , default: Date.now }
  },
  icon: 'lock'
});

Recording.post('query', function(next, done) {
  var recordings = this;
  Show.Model.populate( recordings , {
    path: '_show'
  }, function(err, populatedRecordings) {
    if (err) return done(err);
    return next( null , populatedRecordings );
  });
});

Recording.on('file:media', function(media) {
  console.log('received media:', media);

  var torrent = new Torrent({
    name: media.filename,
    trackers: config.torrents.trackers,
    webseeds: config.service.seeds.map(function(x) {
      return x + '/files/' + media._id
    })
  });
  var file = decentral.datastore.gfs.createReadStream({
    _id: media._id
  });
  var torrentstore = decentral.datastore.gfs.createWriteStream({
    mode: 'w',
    filename: media.filename + '.torrent',
    content_type: 'application/x-bittorrent'
  });
  torrentstore.on('error', function(data) {
    console.log('error!' , data );
  });
  torrentstore.on('close', function( torrentFile ) {
    readTorrent('http://localhost:15005/files/' + torrentFile._id , function(err, parsed) {
      if (err) console.error( err );
      var magnetURI = magnet.encode( parsed );

      Recording.patch({
        _id: media.metadata.document
      }, [
        { op: 'add', path: '/torrent' , value: torrentFile._id },
        { op: 'add', path: '/magnet' , value: magnetURI },
        { op: 'add', path: '/type' , value: media.contentType },
        { op: 'add', path: '/filename' , value: media.filename },
        { op: 'add', path: '/size' , value: media.length }
      ], function(err, num) {
        if (err) console.error( err );
        console.log('all done,', num , 'affected');
      });

    });
  });

  torrent.pipe( torrentstore );
  file.pipe( torrent );

});

Recording.pre('create', function(next, done) {
  var recording = this;
  if (!recording.media) return next();

  var db = decentral.datastore.mongoose.connections[0].db;
  var files = db.collection('fs.files');
  files.findOne({ _id: recording.media }, function(err, thing) {
    return Checksum.create({
      filename: thing.filename,
      _file: thing._id,
      hash: thing.md5,
      type: 'md5'
    }, function() {
      recording.hash = thing.md5;
      return next();
    });
  });
});

var Person = decentral.define('Person', {
  attributes: {
    name: {
      given: { type: String , max: 30 },
      family: { type: String , max: 70 }
    },
    username: { type: String , max: 35 , slug: true },
    password: { type: String , max: 70 , masked: true }
  },
  virtuals: {
    'name.full': function() {
      return [ this.name.given , this.name.family ].join(' ');
    }
  },
  icon: 'user'
});

decentral.serve(['http']).start(function() {

  decentral.app.get('/about', function(req, res, next) {
    return res.render('about');
  });

  // TODO: internalize to maki, provide sane defaults
  decentral.app.get('/recordings/:recordingSlug/edit', function(req, res, next) {
    Recording.get({ slug: req.param('recordingSlug') }, function(err, recording) {
      return res.render('recording-edit', {
        item: recording
      });
    });
  });

  decentral.app.post('/recordings/:recordingSlug', function(req, res, next) {
    Recording.update({ slug: req.param('recordingSlug') }, req.body , function(err, recording) {
      req.flash('success', 'Content edited successfully!');
      return res.redirect('/recordings/' + req.param('recordingSlug'));
    });
  });

  decentral.app.get('/search', function(req, res, next) {
    Show.query({}, function(err, shows) {
      return res.send({
        results: shows.map(function(x) {
          return {
            title: x.name
          }
        })
      });
    });
  });
});
<|endoftext|>


<commit_before>module.exports = require('./config.json')<commit_msg>crufty<commit_after><|endoftext|>


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

// https://github.com/cheeriojs/cheerio
const cheerio = require('cheerio');

const movieData = {};

request('https://booking.sfcinemacity.com/visPrintShowTimes.aspx?visLang=1&visCinemaId=9936', (err, httpResponse, body) => {
  const $ = cheerio.load(body);

  let currentMovie;
  let currentDate;
  $('#tblShowTimes td').each(function () {
    //console.log($(this).text());
    if ($(this).hasClass('PrintShowTimesFilm')) {
      currentMovie = $(this).text();
      movieData[currentMovie] = {};
    } else if ($(this).hasClass('PrintShowTimesDay')) {
      currentDate = $(this).text();
    } else if ($(this).hasClass('PrintShowTimesSession')) {
      movieData[currentMovie][currentDate] = $(this).text();
    }
  });

  console.log(movieData);
});
<commit_msg>fetching, collating and outputting movie data<commit_after>const request = require('request');

// https://github.com/cheeriojs/cheerio
const cheerio = require('cheerio');

const movieData = {};

// collate the movie data
request('https://booking.sfcinemacity.com/visPrintShowTimes.aspx?visLang=1&visCinemaId=9936', (err, httpResponse, body) => {
  const $ = cheerio.load(body);

  let currentMovie;
  let currentDate;
  $('#tblShowTimes td').each(function () {
    if ($(this).hasClass('PrintShowTimesFilm')) {
      currentMovie = $(this).text();
      movieData[currentMovie] = {};
    } else if ($(this).hasClass('PrintShowTimesDay')) {
      currentDate = $(this).text();
    } else if ($(this).hasClass('PrintShowTimesSession')) {
      movieData[currentMovie][currentDate] = $(this).text();
    }
  });

  // test out the data by showing movie info for x days ahead..
  const daysAhead = 1;
  const targetDate = new Date();
  targetDate.setDate(targetDate.getDate() + daysAhead);

  console.log(`Target date is ${targetDate.toDateString()}`);

  for (const movieName of Object.keys(movieData)) {
    for (const movieDate of Object.keys(movieData[movieName])) {
      if (movieDate.includes(` ${targetDate.getDate()} `)) {
        console.log(`${movieName} is showing at ${movieData[movieName][movieDate]}`);
      }
    }
  }
});
<|endoftext|>


<commit_before>/*global describe it before after = */

"use client";

require(["lib/architect/architect", "lib/chai/chai", "/vfs-root"],
  function (architect, chai, baseProc) {
    var expect = chai.expect;

    expect.setupArchitectTest([
        {
            packagePath: "plugins/c9.core/c9",
            workspaceId: "ubuntu/ip-10-35-77-180",
            startdate: new Date(),
            debug: true,
            hosted: true,
            local: false,
            hostname: "dev.javruben.c9.io",
            davPrefix: "/"
        },

        "plugins/c9.core/ext",
        "plugins/c9.core/http-xhr",
        "plugins/c9.core/util",
        "plugins/c9.ide.ui/lib_apf",
        "plugins/c9.ide.ui/anims",
        {
            packagePath: "plugins/c9.core/settings",
            settings: { state: { console: {
                type: "pane",
                nodes: [
                    {
                        type: "tab",
                        editorType: "output",
                        active: "true",
                        document: {
                            title: "Build",
                            output: {
                                id: "build"
                            }
                        }
                    }
                ]
            }}}
        },
        {
            packagePath: "plugins/c9.ide.ui/ui",
            staticPrefix: "plugins/c9.ide.ui"
        },
        "plugins/c9.ide.editors/document",
        "plugins/c9.ide.editors/undomanager",
        "plugins/c9.ide.editors/editors",
        "plugins/c9.ide.editors/editor",
        {
            packagePath: "plugins/c9.ide.editors/tabmanager",
            testing: 2
        },
        "plugins/c9.ide.ui/focus",
        "plugins/c9.ide.editors/pane",
        "plugins/c9.ide.editors/tab",
        "plugins/c9.ide.terminal/terminal",
        "plugins/c9.ide.run/output",
        "plugins/c9.ide.console/console",
        "plugins/c9.fs/proc",
        "plugins/c9.fs/fs",
        "plugins/c9.vfs.client/vfs_client",
        "plugins/c9.vfs.client/endpoint",
        "plugins/c9.ide.auth/auth",
        "plugins/c9.core/api",
        {
            packagePath: "plugins/c9.ide.run/run",
            testing: true,
            base: baseProc,
            runners: {
                "node": {
                    "caption": "Node.js (current)",
                    "cmd": ["node", "${debug?--debug-brk=15454}", "$file"],
                    "debugger": "v8",
                    "debugport": 15454,
                    "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
                    "selector": "source.js",
                    "info": "Your code is running at \\033[01;34m$hostname\\033[00m.\n"
                        + "\\033[01;31mImportant:\\033[00m use \\033[01;32mprocess.env.PORT\\033[00m as the port and \\033[01;32mprocess.env.IP\\033[00m as the host in your scripts!\n"
                },
                "coffee": {
                    "caption": "Coffee",
                    "cmd": ["coffee", "$file"],
                    "debug": ["--debug-brk=5454"],
                    "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
                    "selector": "source.coffee",
                    "info": "Your code is running at \\033[01;34m$hostname\\033[00m.\n"
                        + "\\033[01;31mImportant:\\033[00m use \\033[01;32mprocess.env.PORT\\033[00m as the port and \\033[01;32mprocess.env.IP\\033[00m as the host in your scripts!\n"
                },
                "pythoni": {
                    "caption": "Python in interactive mode",
                    "cmd": ["python", "-i"],
                    "selector": "source.python",
                    "info": "Hit \\033[01;34mCtrl-D\\033[00m to exit.\n"
                },
                "typescript": {
                    "caption": "Typescript",
                    "cmd": ["tsc", "-e", "$file"],
                    "selector": "source.ts",
                    "info": "Your code is running at \\033[01;34m$hostname\\033[00m.\n"
                        + "\\033[01;31mImportant:\\033[00m use \\033[01;32mprocess.env.PORT\\033[00m as the port and \\033[01;32mprocess.env.IP\\033[00m as the host in your scripts!\n"
                }
            }
        },
        {
            packagePath: "plugins/c9.ide.run.build/build",
            base: baseProc,
            builders: {
                "coffee": {
                    "caption": "Coffee",
                    "cmd": ["coffee", "-c", "$file"],
                    "selector": "source.coffee",
                },
                "scss": {
                    "caption": "SASS (scss)",
                    "cmd": ["sass", "${debug?--debug-info}", "--scss", "--update", "$file:${file/\\.scss/\\.css/}"],
                    "selector": "source.scss"
                },
                "less": {
                    "caption": "LESS",
                    "cmd": ["lessc", "$file", ">", "${file/\\.less/\\.css/}"],
                    "selector": "source.less"
                },
                "typescript": {
                    "caption": "Typescript",
                    "cmd": ["tsc", "--out", "${file/\\.ts/\\.js/}", "$file"],
                    "selector": "source.ts"
                }
            }
        },
        {
            packagePath: "plugins/c9.ide.run.build/gui"
        },

        {
            consumes: ["build", "run", "fs", "tabManager", "console", "output", "save"],
            provides: [],
            setup: main
        }
    ], architect);

    function main(options, imports, register) {
        var run = imports.run;
        var build = imports.build;
        var fs = imports.fs;
        var tabs = imports.tabManager;
        var save = imports.save;
        var cnsl = imports.console;

        expect.html.setConstructor(function(tab) {
            if (typeof tab == "object")
                return tab.pane.aml.getPage("editor::" + tab.editorType).$ext;
        });

        function countEvents(count, expected, done) {
            if (count == expected)
                done();
            else
                throw new Error("Wrong Event Count: "
                    + count + " of " + expected);
        }

        describe('build gui', function() {
            before(function(done) {

                bar.$ext.style.background = "rgba(220, 220, 220, 0.93)";
                bar.$ext.style.position = "fixed";
                bar.$ext.style.left = "20px";
                bar.$ext.style.right = "20px";
                bar.$ext.style.bottom = "20px";
                bar.$ext.style.height = "150px";

                document.body.style.marginBottom = "150px";
                done();
            });

            this.timeout(10000);

            it('should build a file automatically based on a selector', function(done) {
                build.getBuilder("coffee", false, function(err, builder) {
                    if (err) throw err.message;

                    expect(builder).to.ok;

                    builder.selector = "source.coffee";

                    var c = "console.log 'Hello Coffee'";

                    fs.rmfile("/helloworld.js", function() {
                        fs.writeFile("/helloworld.coffee", c, "utf8", function(err) {
                            if (err) throw err.message;
                        });

                        save.emit("afterSave", { path: "/helloworld.coffee" });

                        build.on("stopped", function c1(e) {
                            var process = e.process;

                            expect(process.running).is.equal(run.STOPPED);
                            build.off("stopped", c1);

                            fs.readFile("/helloworld.js", "utf8", function(err, data) {
                                expect(data).to.match(/console.log\('Hello Coffee'\)/);

                                fs.rmfile("/helloworld.js", function() {
                                    fs.rmfile("/helloworld.coffee", function() {
                                        delete builder.selector;
                                        done();
                                    });
                                });
                            });
                        });
                    });
                });
            });

            if (!onload.remain) {
               after(function(done) {
                    run.unload();
                    build.unload();
                    tabs.unload();
                    cnsl.unload();

                   document.body.style.marginBottom = "";
                   done();
               });
            }
        });

        register();
    }
});<commit_msg>remove confusing globals from eslint config<commit_after>/*global describe it before after bar */

"use client";

require(["lib/architect/architect", "lib/chai/chai", "/vfs-root"],
  function (architect, chai, baseProc) {
    var expect = chai.expect;

    expect.setupArchitectTest([
        {
            packagePath: "plugins/c9.core/c9",
            workspaceId: "ubuntu/ip-10-35-77-180",
            startdate: new Date(),
            debug: true,
            hosted: true,
            local: false,
            hostname: "dev.javruben.c9.io",
            davPrefix: "/"
        },

        "plugins/c9.core/ext",
        "plugins/c9.core/http-xhr",
        "plugins/c9.core/util",
        "plugins/c9.ide.ui/lib_apf",
        "plugins/c9.ide.ui/anims",
        {
            packagePath: "plugins/c9.core/settings",
            settings: { state: { console: {
                type: "pane",
                nodes: [
                    {
                        type: "tab",
                        editorType: "output",
                        active: "true",
                        document: {
                            title: "Build",
                            output: {
                                id: "build"
                            }
                        }
                    }
                ]
            }}}
        },
        {
            packagePath: "plugins/c9.ide.ui/ui",
            staticPrefix: "plugins/c9.ide.ui"
        },
        "plugins/c9.ide.editors/document",
        "plugins/c9.ide.editors/undomanager",
        "plugins/c9.ide.editors/editors",
        "plugins/c9.ide.editors/editor",
        {
            packagePath: "plugins/c9.ide.editors/tabmanager",
            testing: 2
        },
        "plugins/c9.ide.ui/focus",
        "plugins/c9.ide.editors/pane",
        "plugins/c9.ide.editors/tab",
        "plugins/c9.ide.terminal/terminal",
        "plugins/c9.ide.run/output",
        "plugins/c9.ide.console/console",
        "plugins/c9.fs/proc",
        "plugins/c9.fs/fs",
        "plugins/c9.vfs.client/vfs_client",
        "plugins/c9.vfs.client/endpoint",
        "plugins/c9.ide.auth/auth",
        "plugins/c9.core/api",
        {
            packagePath: "plugins/c9.ide.run/run",
            testing: true,
            base: baseProc,
            runners: {
                "node": {
                    "caption": "Node.js (current)",
                    "cmd": ["node", "${debug?--debug-brk=15454}", "$file"],
                    "debugger": "v8",
                    "debugport": 15454,
                    "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
                    "selector": "source.js",
                    "info": "Your code is running at \\033[01;34m$hostname\\033[00m.\n"
                        + "\\033[01;31mImportant:\\033[00m use \\033[01;32mprocess.env.PORT\\033[00m as the port and \\033[01;32mprocess.env.IP\\033[00m as the host in your scripts!\n"
                },
                "coffee": {
                    "caption": "Coffee",
                    "cmd": ["coffee", "$file"],
                    "debug": ["--debug-brk=5454"],
                    "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
                    "selector": "source.coffee",
                    "info": "Your code is running at \\033[01;34m$hostname\\033[00m.\n"
                        + "\\033[01;31mImportant:\\033[00m use \\033[01;32mprocess.env.PORT\\033[00m as the port and \\033[01;32mprocess.env.IP\\033[00m as the host in your scripts!\n"
                },
                "pythoni": {
                    "caption": "Python in interactive mode",
                    "cmd": ["python", "-i"],
                    "selector": "source.python",
                    "info": "Hit \\033[01;34mCtrl-D\\033[00m to exit.\n"
                },
                "typescript": {
                    "caption": "Typescript",
                    "cmd": ["tsc", "-e", "$file"],
                    "selector": "source.ts",
                    "info": "Your code is running at \\033[01;34m$hostname\\033[00m.\n"
                        + "\\033[01;31mImportant:\\033[00m use \\033[01;32mprocess.env.PORT\\033[00m as the port and \\033[01;32mprocess.env.IP\\033[00m as the host in your scripts!\n"
                }
            }
        },
        {
            packagePath: "plugins/c9.ide.run.build/build",
            base: baseProc,
            builders: {
                "coffee": {
                    "caption": "Coffee",
                    "cmd": ["coffee", "-c", "$file"],
                    "selector": "source.coffee",
                },
                "scss": {
                    "caption": "SASS (scss)",
                    "cmd": ["sass", "${debug?--debug-info}", "--scss", "--update", "$file:${file/\\.scss/\\.css/}"],
                    "selector": "source.scss"
                },
                "less": {
                    "caption": "LESS",
                    "cmd": ["lessc", "$file", ">", "${file/\\.less/\\.css/}"],
                    "selector": "source.less"
                },
                "typescript": {
                    "caption": "Typescript",
                    "cmd": ["tsc", "--out", "${file/\\.ts/\\.js/}", "$file"],
                    "selector": "source.ts"
                }
            }
        },
        {
            packagePath: "plugins/c9.ide.run.build/gui"
        },

        {
            consumes: ["build", "run", "fs", "tabManager", "console", "output", "save"],
            provides: [],
            setup: main
        }
    ], architect);

    function main(options, imports, register) {
        var run = imports.run;
        var build = imports.build;
        var fs = imports.fs;
        var tabs = imports.tabManager;
        var save = imports.save;
        var cnsl = imports.console;

        expect.html.setConstructor(function(tab) {
            if (typeof tab == "object")
                return tab.pane.aml.getPage("editor::" + tab.editorType).$ext;
        });

        function countEvents(count, expected, done) {
            if (count == expected)
                done();
            else
                throw new Error("Wrong Event Count: "
                    + count + " of " + expected);
        }

        describe('build gui', function() {
            before(function(done) {

                bar.$ext.style.background = "rgba(220, 220, 220, 0.93)";
                bar.$ext.style.position = "fixed";
                bar.$ext.style.left = "20px";
                bar.$ext.style.right = "20px";
                bar.$ext.style.bottom = "20px";
                bar.$ext.style.height = "150px";

                document.body.style.marginBottom = "150px";
                done();
            });

            this.timeout(10000);

            it('should build a file automatically based on a selector', function(done) {
                build.getBuilder("coffee", false, function(err, builder) {
                    if (err) throw err.message;

                    expect(builder).to.ok;

                    builder.selector = "source.coffee";

                    var c = "console.log 'Hello Coffee'";

                    fs.rmfile("/helloworld.js", function() {
                        fs.writeFile("/helloworld.coffee", c, "utf8", function(err) {
                            if (err) throw err.message;
                        });

                        save.emit("afterSave", { path: "/helloworld.coffee" });

                        build.on("stopped", function c1(e) {
                            var process = e.process;

                            expect(process.running).is.equal(run.STOPPED);
                            build.off("stopped", c1);

                            fs.readFile("/helloworld.js", "utf8", function(err, data) {
                                expect(data).to.match(/console.log\('Hello Coffee'\)/);

                                fs.rmfile("/helloworld.js", function() {
                                    fs.rmfile("/helloworld.coffee", function() {
                                        delete builder.selector;
                                        done();
                                    });
                                });
                            });
                        });
                    });
                });
            });

            if (!onload.remain) {
               after(function(done) {
                    run.unload();
                    build.unload();
                    tabs.unload();
                    cnsl.unload();

                   document.body.style.marginBottom = "";
                   done();
               });
            }
        });

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


<commit_before>'use strict';

function MainController() {
  var vm = this;

  vm.selectedNodes = [];

  vm.template = {
    id: '_id',
    nodes: 'nodes',
    title: 'title'
  };

  vm.tree = [
    {
      _id: '123412341234',
      title: 'Title one',
      nodes: [
        {
          _id: '12341234123414531234',
          title: 'Subtitle one',
          nodes: [
            {
              _id: '4634575647',
              title: 'Subsubtitle one',
              nodes: [
                {
                  _id: '123123123123',
                  title: 'Subsubsubtitle one'
                }
              ]
            }
          ]
        },
        {
          _id: '16789',
          title: 'Subtitle two'
        }
      ]
    },
    {
      _id: '2134123412341234',
      title: 'Title two',
      nodes: [
        {
          _id: '00678234559',
          title: 'Subtitle one'
        },
        {
          _id: '34632463574',
          title: 'Subtitle two'
        }
      ]
    },
    {
      _id: '46783721376',
      title: 'Curriculum Items',
      nodes: [
        {
          _id: '0578234547635',
          title: 'RCPCH Paediatric Immunology, Infectious Diseases and Allergy',
          nodes: [
            {
              _id: '3450963402-5892345',
              title: 'Detailed knowledge of common and serious paediatric conditions and their management in General Paediatrics or in a paediatric sub-specialty',
              nodes: [
                  {
                  _id: '23459817234012734',
                  title: 'Emphasis on Immunology and infectious diseases',
                  nodes: [
                    {
                      _id: '12093481023984',
                      title: 'Know and understand the complexities of the relationship between the host and infecting organisms'
                    }
                  ]
                }
              ]
            }
          ]
        }
      ]
    }
  ];

  vm.treeOptions = {
    canEdit: true,
    addNode: function(nodes) {
      var id = Math.floor((Math.random() * 10000) + 1);
      nodes.push({
        _id: id,
        title: 'Title ' + id,
        nodes: []
      });
    }
  };

}

var app = angular.module('sequioaDemo', ['ngSequoia']);

app.controller('MainController', MainController);<commit_msg>Add buttons demo code #nochangelog<commit_after>'use strict';

function MainController() {
  var vm = this;

  vm.selectedNodes = [];

  vm.template = {
    id: '_id',
    nodes: 'nodes',
    title: 'title'
  };

  vm.tree = [
    {
      _id: '123412341234',
      title: 'Title one',
      nodes: [
        {
          _id: '12341234123414531234',
          title: 'Subtitle one',
          nodes: [
            {
              _id: '4634575647',
              title: 'Subsubtitle one',
              nodes: [
                {
                  _id: '123123123123',
                  title: 'Subsubsubtitle one'
                }
              ]
            }
          ]
        },
        {
          _id: '16789',
          title: 'Subtitle two'
        }
      ]
    },
    {
      _id: '2134123412341234',
      title: 'Title two',
      nodes: [
        {
          _id: '00678234559',
          title: 'Subtitle one'
        },
        {
          _id: '34632463574',
          title: 'Subtitle two'
        }
      ]
    },
    {
      _id: '46783721376',
      title: 'Curriculum Items',
      nodes: [
        {
          _id: '0578234547635',
          title: 'RCPCH Paediatric Immunology, Infectious Diseases and Allergy',
          nodes: [
            {
              _id: '3450963402-5892345',
              title: 'Detailed knowledge of common and serious paediatric conditions and their management in General Paediatrics or in a paediatric sub-specialty',
              nodes: [
                  {
                  _id: '23459817234012734',
                  title: 'Emphasis on Immunology and infectious diseases',
                  nodes: [
                    {
                      _id: '12093481023984',
                      title: 'Know and understand the complexities of the relationship between the host and infecting organisms'
                    }
                  ]
                }
              ]
            }
          ]
        }
      ]
    }
  ];

  vm.treeOptions = {
    canEdit: true,
    buttons: {
      edit: 'Edit nodes',
      select: 'Select node'
    },
    addNode: function(nodes) {
      var id = Math.floor((Math.random() * 10000) + 1);
      nodes.push({
        _id: id,
        title: 'Title ' + id,
        nodes: []
      });
    }
  };

}

var app = angular.module('sequioaDemo', ['ngSequoia', 'ngSanitize']);

app.controller('MainController', MainController);<|endoftext|>