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

	questkit.ui.addText = function (text) {
		$('#questkit-output').append(text + '
');
	};
})();

$(function () {
	$('#questkit-input').keydown(function (e) {
		if (e.which != 13) return;
		var input = $('#questkit-input').val();
		$('#questkit-input').val('');
		msg('
> ' + input + '
');
		questkit.handleCommand(input);
	});
});<commit_msg>Migrating some output functions<commit_after>/* jshint quotmark: single */

(function () {
	'use strict';

	var currentDiv = null;
	var outputSections = [];
	var divCount = -1;
	var beginningOfCurrentTurnScrollPosition = 0;

	questkit.ui.addText = function (text) {
		if (getCurrentDiv() === null) {
			createNewDiv('left');
		}

		$('#questkit-output').append(text + '
');
		$('#questkit-output').css('min-height', $('#questkit-output').height());
	};

	var createNewDiv = function (alignment) {
		var classes = outputSections.join(' ');
		setDivCount(getDivCount() + 1);
		$('
', {
			id: 'questkit-output-section' + getDivCount(),
			style: 'text-align: ' + alignment,
			'class': classes
		}).appendTo('#questkit-output');
		setCurrentDiv('#questkit-output-section' + getDivCount());
	};

	var getCurrentDiv = function () {
		if (currentDiv) return currentDiv;

		var divId = questkit.get('~ui.divid');
		if (divId) {
			currentDiv = $(divId);
			return currentDiv;
		}

		return null;
	};

	var setCurrentDiv = function (div) {
		currentDiv = $(div);
		questkit.set('~ui.divid', div);
	};

	var getDivCount = function () {
		if (divCount == -1) {
			divCount = questkit.get('~ui.divcount') || 0;
		}
		return divCount;
	};

	var setDivCount = function (count) {
		divCount = count;
		questkit.set('~ui.divcount', divCount);
	};

	questkit.ui.scrollToEnd = function () {
		var scrollTo = beginningOfCurrentTurnScrollPosition;
		var currentScrollTop = Math.max($('body').scrollTop(), $('html').scrollTop());
		if (scrollTo > currentScrollTop) {
			var maxScrollTop = $(document).height() - $(window).height();
			if (scrollTo > maxScrollTop) scrollTo = maxScrollTop;
			var distance = scrollTo - currentScrollTop;
			var duration = distance / 0.4;
			// TODO: 'easeInOutCubic' is nice here
			$('body,html').stop().animate({ scrollTop: scrollTo }, duration);
		}
		$('#questkit-input').focus();
	};

	questkit.ui.markScrollPosition = function () {
		beginningOfCurrentTurnScrollPosition = $('#questkit-output').height();
	};
})();

$(function () {
	$('#questkit-input').keydown(function (e) {
		if (e.which != 13) return;
		var input = $('#questkit-input').val();
		$('#questkit-input').val('');
		questkit.ui.markScrollPosition();
		msg('
> ' + input + '
');
		questkit.handleCommand(input);
		questkit.ui.scrollToEnd();
	});
});<|endoftext|>


<commit_before>var gd = require('node-gd');
var fs = require('fs');
var path = require('path');

var images = './img/';
var fonts = './font/';

var M_PI = Math.PI;
var H_PI = M_PI * 0.5;

Date.prototype.stdTimezoneOffset = function() {
    var jan = new Date(this.getFullYear(), 0, 1);
    var jul = new Date(this.getFullYear(), 6, 1);
    return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
}

Date.prototype.dst = function() {
    return this.getTimezoneOffset() < this.stdTimezoneOffset();
}

exports.clock = function(req, res, next) {

	var font = path.join(fonts, 'CASTELAR.TTF');

    var gear1 =    gd.createfrompng("gear1.png"),
	   gear2 =     gd.createfrompng("gear2.png"),
	   gear3 =     gd.createfrompng("gear3.png"),
	   clock =     gd.createfrompng("clock5.png"),
	   img =       gd.createfrompng("clock5.png");

    var width = img.width;

	img.alphaBlending(1);
	img.setAntiAliased(1);

	almostblack =  img.colorAllocate(1, 1, 1);
	black =        img.colorAllocate(0, 0, 0);
	white =        img.colorAllocate(255, 255, 255);
	clear =        img.colorAllocateAlpha(255, 255, 255, 0);
	dark =         img.colorAllocate(113, 101, 79);

	img.colorTransparent(white);
	gear1.colorTransparent(white);
	gear2.colorTransparent(white);
	gear3.colorTransparent(white);
	clock.colorTransparent(white);

    var date =      new Date(),
	    minute =    date.getMinutes(),
	    second =    date.getSeconds(),
        hour =      date.getHours();
    minute += second / 60;

	//Gears
    var gear1_diag = 2 * Math.sqrt(Math.pow(0.5 * gear1.width, 2) + Math.pow(0.5 * gear1.height, 2)),
        gear1_ang = ((minute + hour * 60) * 30),
        gear1_rot = gd.createTrueColor(Math.floor(gear1_diag), Math.floor(gear1_diag)),
        gear2_diag = 2 * Math.sqrt(Math.pow(0.5 * gear2.width, 2) + Math.pow(0.5 * gear2.height, 2)),
        gear2_ang = -(minute * 60),
        gear2_rot = gd.createTrueColor(Math.floor(gear2_diag), Math.floor(gear2_diag)),
        gear3_diag = 2 * Math.sqrt(Math.pow(0.5 * gear3.width, 2) + Math.pow(0.5 * gear3.height, 2)),
        gear3_ang = (minute * 120),
        gear3_rot = gd.createTrueColor(Math.floor(gear3_diag), Math.floor(gear3_diag));

    //img.copyRotated(dest, dstX, dstY, srcX, srcY, srcW, srcH, angle);
	gear1.copyRotated(gear1_rot,
        (gear1_diag - gear1.width) / 2,
        (gear1_diag - gear1.height) / 2,
        0, 0,
        gear1.width,
        gear1.height,
        Math.floor(gear1_ang));
	gear2.copyRotated(gear2_rot,
        (gear2_diag - gear2.width) / 2,
        (gear2_diag - gear2.height) / 2,
        0, 0,
        gear2.width,
        gear2.height,
        Math.floor(gear2_ang));
    gear3.copyRotated(gear3_rot,
        (gear3_diag - gear3.width) / 2,
        (gear3_diag - gear3.height) / 2,
        0, 0,
        gear3.width,
        gear3.height,
        Math.floor(gear3_ang));

	var offset1 = Math.floor((gear1_rot.width - gear1.width) / 2),
	    offset2 = Math.floor((gear2_rot.width - gear2.width) / 2),
	    offset3 = Math.floor((gear3_rot.width - gear3.width) / 2);

    //img.copyMerge(dest, dstX, dstY, srcX, srcY, width, height, pct);
	gear1.copyMerge(img, 403 - offset1, 32 - offset1, 0, 0, gear1.width, gear1.height, 100);
	gear1.copyMerge(img, 278 - offset1, 5 - offset1, 0, 0, gear1.width, gear1.height, 100);
	gear2.copyMerge(img, 317 - offset2, 15 - offset2, 0, 0, gear2.width, gear2.height, 100);
	gear2.copyMerge(img, 388 - offset2, 27 - offset2, 0, 0, gear2.width, gear2.height, 100);
	gear3.copyMerge(img, 105 - offset3, 7 - offset3, 0, 0, gear3.width, gear3.height, 100);

	clock.copymerge(img, 0, 0, 0, 0, width, 100, 100);

	//Clock faces
	makeClockFace(img, 224, 49, 33, 3, 5, dark, 50, 10, 1);
	makeClockFace(img, 122, 68, 22, 2, 3, dark, 40, 20, 1);
	makeClockFace(img, 122, 68, 22, 2, 6, dark, 0, 4, 1);
	makeClockFace(img, 329, 66, 22, 2, 3, dark, 20, 10, 1);

	makeClockHand(img, 224, 49, ((minute / 60) * 2 * M_PI) + M_PI / 2, 30, 3);
	makeClockHand(img, 122, 68, ((minute / 240 + ((hour + 2) % 4) / 4) * 2 * M_PI) + M_PI / 2 + M_PI / 4, 20, 3);
	makeClockHand(img, 329, 66, (((minute % 30) / 30) * 2 * M_PI) + M_PI / 2, 20, 3);

	var newpix = 0,
        then = new Date(2013, 3, 30, 0, 0, 0, 0),
	    interval = DateDiff(date, then);
	newpix = Math.floor(interval / 86400000 + 238);
	if (date.dst) { newpix -= 1;}

	fixedWidthNumber(img, 371, 86, 13.33, 15, newpix, black, font);

    //Save to a file and then read it back because pngPtr() doesn't work for some reason
    img.savePng('./temp5');
    var dat = fs.readFileheightnc('./temp5');

    res.set('Content-Type', 'image/png');
    res.end(dat, 'binary');
    img.destroy();
}

function makeClockFace(img, offsetx, offsety, radius, length1, length2, color, num1, num2, thick2) {

    var black = img.colorAllocate(36, 20, 12);

    for (var i = 0; i < num1; i++) {
        x1 = offsetx + (radius - length1) * Math.cos(((i / num1) * 2 * M_PI + H_PI));
        y1 = offsety + (radius - length1) * Math.sin(((i / num1) * 2 * M_PI + H_PI));
        x2 = offsetx + radius * Math.cos(((i / num1) * 2 * M_PI + H_PI));
        y2 = offsety + radius * Math.sin(((i / num1) * 2 * M_PI + H_PI));

        img.line(Math.Floor(x1), Math.Floor(y1), Math.Floor(x2), Math.Floor(y2), color);
    }

    for (var i = 0; i < num2; i++) {
        x1 = offsetx + (radius - length2) * Math.cos(((i / num2) * 2 * M_PI + (num2 == 10 ? H_PI : 0)));
        y1 = offsety + (radius - length2) * Math.sin(((i / num2) * 2 * M_PI + (num2 == 10 ? H_PI : 0)));
        x2 = offsetx + radius * Math.cos(((i / num2) * 2 * M_PI + (num2 == 10 ? H_PI : 0)));
        y2 = offsety + radius * Math.sin(((i / num2) * 2 * M_PI + (num2 == 10 ? H_PI : 0)));

        img.setThickness(thick2);
        img.line(Math.Floor(x1), Math.Floor(y1), Math.Floor(x2), Math.Floor(y2), black);
    }
    if (length2 <= 5) {
        img.setThickness(thick2*2);
        img.line(img, offsetx, offsety - radius, offsetx, offsety - (radius - length2 * 3), black);
    }
    else {
        img.setThickness(thick2*2);
        img.line(img, offsetx, offsety - radius, offsetx, offsety - (radius - length2 * 1.6), black);
    }
}

function makeClockHand(img, offsetx, offsety, angle, length, thick) {
    var black = img.colorallocate(0, 0, 0),
        x = offsetx + -length * Math.cos(angle),
        y = offsety + -length * Math.sin(angle),

        x2 = offsetx + -length * 0.64 * Math.cos(angle),
        y2 = offsety + -length * 0.64 * Math.sin(angle),

        x3 = offsetx + -length * 0.36 * Math.cos(angle),
        y3 = offsety + -length * 0.36 * Math.sin(angle);

    img.setThickness(Math.floor(thick * 0.333));
    img.line(img, offsetx, offsety, x, y, black);
    img.setThickness(Math.floor(thick * 0.667));
    img.line(img, offsetx, offsety, x2, y2, black);
    //img.linethick(img, offsetx, offsety, x3, y3, black, thick);
}

function fixedWidthNumber(img, offsetx, offsety, width, height, number, color, font) {
    while (number.toString().length < 5) {
        number = "0" + number;
    }
    for (var i = 0; i < 5; i++) {
        str = number.toString().substr(i, 1);
        extraoffset = width * 0.2;
        if (str == '1') { extraoffset = width * 0.5; }
        if (str == '0') { extraoffset = 0; }
        //img.stringFT      (color, font, size, angle, x, y, str);
        img.stringFT(color, font, height, 0, offsetx + (width + 2) * i + extraoffset, offsety, str);
    }
}

function DateDiff(var /*Date*/ date1, var /*Date*/ date2) {
    return date1.getTime() - date2.getTime();
}<commit_msg>Fix malformed datediff function signature<commit_after>var gd = require('node-gd');
var fs = require('fs');
var path = require('path');

var images = './img/';
var fonts = './font/';

var M_PI = Math.PI;
var H_PI = M_PI * 0.5;

Date.prototype.stdTimezoneOffset = function() {
    var jan = new Date(this.getFullYear(), 0, 1);
    var jul = new Date(this.getFullYear(), 6, 1);
    return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
}

Date.prototype.dst = function() {
    return this.getTimezoneOffset() < this.stdTimezoneOffset();
}

exports.clock = function(req, res, next) {

	var font = path.join(fonts, 'CASTELAR.TTF');

    var gear1 =    gd.createfrompng("gear1.png"),
	   gear2 =     gd.createfrompng("gear2.png"),
	   gear3 =     gd.createfrompng("gear3.png"),
	   clock =     gd.createfrompng("clock5.png"),
	   img =       gd.createfrompng("clock5.png");

    var width = img.width;

	img.alphaBlending(1);
	img.setAntiAliased(1);

	almostblack =  img.colorAllocate(1, 1, 1);
	black =        img.colorAllocate(0, 0, 0);
	white =        img.colorAllocate(255, 255, 255);
	clear =        img.colorAllocateAlpha(255, 255, 255, 0);
	dark =         img.colorAllocate(113, 101, 79);

	img.colorTransparent(white);
	gear1.colorTransparent(white);
	gear2.colorTransparent(white);
	gear3.colorTransparent(white);
	clock.colorTransparent(white);

    var date =      new Date(),
	    minute =    date.getMinutes(),
	    second =    date.getSeconds(),
        hour =      date.getHours();
    minute += second / 60;

	//Gears
    var gear1_diag = 2 * Math.sqrt(Math.pow(0.5 * gear1.width, 2) + Math.pow(0.5 * gear1.height, 2)),
        gear1_ang = ((minute + hour * 60) * 30),
        gear1_rot = gd.createTrueColor(Math.floor(gear1_diag), Math.floor(gear1_diag)),
        gear2_diag = 2 * Math.sqrt(Math.pow(0.5 * gear2.width, 2) + Math.pow(0.5 * gear2.height, 2)),
        gear2_ang = -(minute * 60),
        gear2_rot = gd.createTrueColor(Math.floor(gear2_diag), Math.floor(gear2_diag)),
        gear3_diag = 2 * Math.sqrt(Math.pow(0.5 * gear3.width, 2) + Math.pow(0.5 * gear3.height, 2)),
        gear3_ang = (minute * 120),
        gear3_rot = gd.createTrueColor(Math.floor(gear3_diag), Math.floor(gear3_diag));

    //img.copyRotated(dest, dstX, dstY, srcX, srcY, srcW, srcH, angle);
	gear1.copyRotated(gear1_rot,
        (gear1_diag - gear1.width) / 2,
        (gear1_diag - gear1.height) / 2,
        0, 0,
        gear1.width,
        gear1.height,
        Math.floor(gear1_ang));
	gear2.copyRotated(gear2_rot,
        (gear2_diag - gear2.width) / 2,
        (gear2_diag - gear2.height) / 2,
        0, 0,
        gear2.width,
        gear2.height,
        Math.floor(gear2_ang));
    gear3.copyRotated(gear3_rot,
        (gear3_diag - gear3.width) / 2,
        (gear3_diag - gear3.height) / 2,
        0, 0,
        gear3.width,
        gear3.height,
        Math.floor(gear3_ang));

	var offset1 = Math.floor((gear1_rot.width - gear1.width) / 2),
	    offset2 = Math.floor((gear2_rot.width - gear2.width) / 2),
	    offset3 = Math.floor((gear3_rot.width - gear3.width) / 2);

    //img.copyMerge(dest, dstX, dstY, srcX, srcY, width, height, pct);
	gear1.copyMerge(img, 403 - offset1, 32 - offset1, 0, 0, gear1.width, gear1.height, 100);
	gear1.copyMerge(img, 278 - offset1, 5 - offset1, 0, 0, gear1.width, gear1.height, 100);
	gear2.copyMerge(img, 317 - offset2, 15 - offset2, 0, 0, gear2.width, gear2.height, 100);
	gear2.copyMerge(img, 388 - offset2, 27 - offset2, 0, 0, gear2.width, gear2.height, 100);
	gear3.copyMerge(img, 105 - offset3, 7 - offset3, 0, 0, gear3.width, gear3.height, 100);

	clock.copymerge(img, 0, 0, 0, 0, width, 100, 100);

	//Clock faces
	makeClockFace(img, 224, 49, 33, 3, 5, dark, 50, 10, 1);
	makeClockFace(img, 122, 68, 22, 2, 3, dark, 40, 20, 1);
	makeClockFace(img, 122, 68, 22, 2, 6, dark, 0, 4, 1);
	makeClockFace(img, 329, 66, 22, 2, 3, dark, 20, 10, 1);

	makeClockHand(img, 224, 49, ((minute / 60) * 2 * M_PI) + M_PI / 2, 30, 3);
	makeClockHand(img, 122, 68, ((minute / 240 + ((hour + 2) % 4) / 4) * 2 * M_PI) + M_PI / 2 + M_PI / 4, 20, 3);
	makeClockHand(img, 329, 66, (((minute % 30) / 30) * 2 * M_PI) + M_PI / 2, 20, 3);

	var newpix = 0,
        then = new Date(2013, 3, 30, 0, 0, 0, 0),
	    interval = DateDiff(date, then);
	newpix = Math.floor(interval / 86400000 + 238);
	if (date.dst) { newpix -= 1;}

	fixedWidthNumber(img, 371, 86, 13.33, 15, newpix, black, font);

    //Save to a file and then read it back because pngPtr() doesn't work for some reason
    img.savePng('./temp5');
    var dat = fs.readFileheightnc('./temp5');

    res.set('Content-Type', 'image/png');
    res.end(dat, 'binary');
    img.destroy();
}

function makeClockFace(img, offsetx, offsety, radius, length1, length2, color, num1, num2, thick2) {

    var black = img.colorAllocate(36, 20, 12);

    for (var i = 0; i < num1; i++) {
        x1 = offsetx + (radius - length1) * Math.cos(((i / num1) * 2 * M_PI + H_PI));
        y1 = offsety + (radius - length1) * Math.sin(((i / num1) * 2 * M_PI + H_PI));
        x2 = offsetx + radius * Math.cos(((i / num1) * 2 * M_PI + H_PI));
        y2 = offsety + radius * Math.sin(((i / num1) * 2 * M_PI + H_PI));

        img.line(Math.Floor(x1), Math.Floor(y1), Math.Floor(x2), Math.Floor(y2), color);
    }

    for (var i = 0; i < num2; i++) {
        x1 = offsetx + (radius - length2) * Math.cos(((i / num2) * 2 * M_PI + (num2 == 10 ? H_PI : 0)));
        y1 = offsety + (radius - length2) * Math.sin(((i / num2) * 2 * M_PI + (num2 == 10 ? H_PI : 0)));
        x2 = offsetx + radius * Math.cos(((i / num2) * 2 * M_PI + (num2 == 10 ? H_PI : 0)));
        y2 = offsety + radius * Math.sin(((i / num2) * 2 * M_PI + (num2 == 10 ? H_PI : 0)));

        img.setThickness(thick2);
        img.line(Math.Floor(x1), Math.Floor(y1), Math.Floor(x2), Math.Floor(y2), black);
    }
    if (length2 <= 5) {
        img.setThickness(thick2*2);
        img.line(img, offsetx, offsety - radius, offsetx, offsety - (radius - length2 * 3), black);
    }
    else {
        img.setThickness(thick2*2);
        img.line(img, offsetx, offsety - radius, offsetx, offsety - (radius - length2 * 1.6), black);
    }
}

function makeClockHand(img, offsetx, offsety, angle, length, thick) {
    var black = img.colorallocate(0, 0, 0),
        x = offsetx + -length * Math.cos(angle),
        y = offsety + -length * Math.sin(angle),

        x2 = offsetx + -length * 0.64 * Math.cos(angle),
        y2 = offsety + -length * 0.64 * Math.sin(angle),

        x3 = offsetx + -length * 0.36 * Math.cos(angle),
        y3 = offsety + -length * 0.36 * Math.sin(angle);

    img.setThickness(Math.floor(thick * 0.333));
    img.line(img, offsetx, offsety, x, y, black);
    img.setThickness(Math.floor(thick * 0.667));
    img.line(img, offsetx, offsety, x2, y2, black);
    //img.linethick(img, offsetx, offsety, x3, y3, black, thick);
}

function fixedWidthNumber(img, offsetx, offsety, width, height, number, color, font) {
    while (number.toString().length < 5) {
        number = "0" + number;
    }
    for (var i = 0; i < 5; i++) {
        str = number.toString().substr(i, 1);
        extraoffset = width * 0.2;
        if (str == '1') { extraoffset = width * 0.5; }
        if (str == '0') { extraoffset = 0; }
        //img.stringFT      (color, font, size, angle, x, y, str);
        img.stringFT(color, font, height, 0, offsetx + (width + 2) * i + extraoffset, offsety, str);
    }
}

function DateDiff(date1, date2) {
    return date1.getTime() - date2.getTime();
}<|endoftext|>


<commit_before>#!/usr/bin/env node
"use strict";
require("console-dope");
var connect = require("connect"),
    http = require("http"),
    util = require("util"),
    Thing = require("nature").Thing,
    w = require("wodge");

var usage = "usage: ws [--directory|-d <directory>] [--port|-p <port>] [--log-format|-f dev|default|short|tiny]";

function halt(message){
    console.red.log("Error: %s",  message);
    console.log(usage);
    process.exit(1);
}

/**
parse command-line args
*/
var argv = new Thing()
    .define({ name: "port", alias: "p", type: "number", defaultOption: true, value: 8000 })
    .define({ name: "log-format", alias: "f", type: "string" })
    .define({ name: "help", alias: "h", type: "boolean" })
    .define({ name: "directory", alias: "d", type: "string", value: process.cwd() })
    .define({ name: "compress", alias: "c", type: "boolean" })
    .on("error", function(err){
        halt(err.message);
    })
    .set(process.argv);

function handleServerError(err){
    if (err.code === "EADDRINUSE"){
        halt("port " + argv.port + " is already is use");
    } else {
        halt(err.message);
    }
}

/**
Die here if invalid args received
*/
if (!argv.valid) halt(argv.validationMessages);

/**
$ ws --help
*/
if (argv.help){
    console.log(usage);

} else {
    var total = {
        req: 0,
        bytes: 0,
        connections: 0
    };

    process.on("SIGINT", function(){
        console.showCursor();
        console.log();
        process.exit(0);
    });

    /**
    customised connect.logger :date token, purely to satisfy Logstalgia.
    */
    connect.logger.token("date", function(){
        var a = new Date();
        return (a.getDate() + "/" + a.getUTCMonth() + "/" + a.getFullYear() + ":" + a.toTimeString())
                .replace("GMT", "").replace(" (BST)", "");
    });

    var app = connect();

    /*
    log using --log-format (if supplied), else output statics
    */
    if(argv["log-format"]){
        app.use(connect.logger(argv["log-format"]));
    } else {
        app.use(function(req, res, next){
            console.column(1).write(++total.req);
            next();
        });
    }

    /**
    --compress enables compression
    */
    if (argv.compress) app.use(connect.compress());

    /**
    static file server including directory browsing support
    */
    app.use(connect.static(argv.directory))
        .use(connect.directory(argv.directory, { icons: true }));

    /**
    launch server
    */
    var server = http.createServer(app)
        .on("error", handleServerError)
        .listen(argv.port);

    /*
    write status to stderr so stdout can be piped to disk ($ ws > log.txt)
    */
    if (argv.directory === process.cwd()){
        console.error("serving at %u{%s}", "http://localhost:" + argv.port);
    } else {
        console.error("serving %u{%s} at %u{%s}", argv.directory, "http://localhost:" + argv.port);
    }

    /**
    in stats mode, monitor connections and bytes transferred
    */
    if (!argv["log-format"]){
        console.hideCursor();
        console.log("%u{Requests}   %u{Data}        %u{Connections}");
        server.on("connection", function(socket){
            var oldWrite = socket.write;
            socket.write = function(data) {
                if (!Buffer.isBuffer(data)) {
                    data = new Buffer(data);
                }
                oldWrite.call(this, data);
                total.bytes += data.length;
                console.column(12).write((w.bytesToSize(total.bytes, 2) + "            ").slice(0,12));
            };
            console.column(24).write(++total.connections);
            socket.on("close", function(){
                console.column(24).write((--total.connections + "            ").slice(0,12));
            });
        });
    }
}
<commit_msg>store config in package.json or .local-web-server.json<commit_after>#!/usr/bin/env node
"use strict";
require("console-dope");
var connect = require("connect"),
    http = require("http"),
    util = require("util"),
    fs = require("fs"),
    Thing = require("nature").Thing,
    w = require("wodge"),
    path = require("path");

var usage = "usage: ws [--directory|-d <directory>] [--port|-p <port>] [--log-format|-f dev|default|short|tiny]";

function halt(message){
    console.red.log("Error: %s",  message);
    console.log(usage);
    process.exit(1);
}

function handleServerError(err){
    if (err.code === "EADDRINUSE"){
        halt("port " + argv.port + " is already is use");
    } else {
        halt(err.message);
    }
}

/**
parse command-line args
*/
var argv = new Thing()
    .define({ name: "port", alias: "p", type: "number", defaultOption: true, value: 8000 })
    .define({ name: "log-format", alias: "f", type: "string" })
    .define({ name: "help", alias: "h", type: "boolean" })
    .define({ name: "directory", alias: "d", type: "string", value: process.cwd() })
    .define({ name: "compress", alias: "c", type: "boolean" })
    .on("error", function(err){
        halt(err.message);
    })
    .set(process.argv);

/*
Include any options from "package.json", ".local-web-server.json" or "~/.local-web-server.json", in that order
*/
var pkgPath = path.join(process.cwd(), "package.json"),
    lwsPath = path.join(process.cwd(), ".local-web-server.json"),
    homePath = path.join(w.getHomeDir(), ".local-web-server.json");
if (fs.existsSync(pkgPath)){
    argv.set(require(pkgPath)["local-web-server"]);
}
if (fs.existsSync(lwsPath)){
    argv.set(require(lwsPath));
}
if (fs.existsSync(homePath)){
    argv.set(require(homePath));
}

/**
Die here if invalid args received
*/
if (!argv.valid) halt(argv.validationMessages);

/**
$ ws --help
*/
if (argv.help){
    console.log(usage);

} else {
    var total = {
        req: 0,
        bytes: 0,
        connections: 0
    };

    process.on("SIGINT", function(){
        console.showCursor();
        console.log();
        process.exit(0);
    });

    /**
    customised connect.logger :date token, purely to satisfy Logstalgia.
    */
    connect.logger.token("date", function(){
        var a = new Date();
        return (a.getDate() + "/" + a.getUTCMonth() + "/" + a.getFullYear() + ":" + a.toTimeString())
                .replace("GMT", "").replace(" (BST)", "");
    });

    var app = connect();

    /*
    log using --log-format (if supplied), else output statics
    */
    if(argv["log-format"]){
        app.use(connect.logger(argv["log-format"]));
    } else {
        app.use(function(req, res, next){
            console.column(1).write(++total.req);
            next();
        });
    }

    /**
    --compress enables compression
    */
    if (argv.compress) app.use(connect.compress());

    /**
    static file server including directory browsing support
    */
    app.use(connect.static(argv.directory))
        .use(connect.directory(argv.directory, { icons: true }));

    /**
    launch server
    */
    var server = http.createServer(app)
        .on("error", handleServerError)
        .listen(argv.port);

    /*
    write status to stderr so stdout can be piped to disk ($ ws > log.txt)
    */
    if (argv.directory === process.cwd()){
        console.error("serving at %u{%s}", "http://localhost:" + argv.port);
    } else {
        console.error("serving %u{%s} at %u{%s}", argv.directory, "http://localhost:" + argv.port);
    }

    /**
    in stats mode, monitor connections and bytes transferred
    */
    if (!argv["log-format"]){
        console.hideCursor();
        console.log("%u{Requests}   %u{Data}        %u{Connections}");
        server.on("connection", function(socket){
            var oldWrite = socket.write;
            socket.write = function(data) {
                if (!Buffer.isBuffer(data)) {
                    data = new Buffer(data);
                }
                oldWrite.call(this, data);
                total.bytes += data.length;
                console.column(12).write((w.bytesToSize(total.bytes, 2) + "            ").slice(0,12));
            };
            console.column(24).write(++total.connections);
            socket.on("close", function(){
                console.column(24).write((--total.connections + "            ").slice(0,12));
            });
        });
    }
}
<|endoftext|>


<commit_before>// m15_003 #479, 482, 491
//
//
casper.test.begin('m15_003 #479, 482, 491', 5, function suite(test) {
casper.echo("Test environment: "+SERVER);
var USECASE='/item/7869426'
var ENTITY=SERVER+USECASE;
	casper.start(ENTITY, function() {
	test.assertTextExists('American Journal of Food' , 'page title American Journal... found');
	test.assertTextExists('George Washington' , 'Verified GW holding');
	test.assertTextExists('Georgetown' , 'Verified GT holding');
	test.assertTextExists('UDC' , 'Verified DC holding');
	test.assertTextExists('Full ' , 'Verified Full text online ');
    }).run(function() {
        test.done();
    });
});
<commit_msg>remove test for deleted bib<commit_after>// m15_003 #479, 482, 491
//
// UPDATE July 2016, udc no longer holds. removed one test.
casper.test.begin('m15_003 #479, 482, 491', 4, function suite(test) {
casper.echo("Test environment: "+SERVER);
var USECASE='/item/7869426'
var ENTITY=SERVER+USECASE;
	casper.start(ENTITY, function() {
	test.assertTextExists('American Journal of Food' , 'page title American Journal... found');
	test.assertTextExists('George Washington' , 'Verified GW holding');
	test.assertTextExists('Georgetown' , 'Verified GT holding');
	test.assertTextExists('Full ' , 'Verified Full text online ');
    }).run(function() {
        test.done();
    });
});
<|endoftext|>


<commit_before>import { curryN, reverse } from 'ramda';

/**
 * Returns a curried equivalent of the provided function, with the specified arity.
 * This function is like curryN, except that the provided arguments order is reversed.
 *
 * @func curryRightN
 * @memberOf RA
 * @since {@link https://char0n.github.io/ramda-adjunct/1.11.0|v1.11.0}
 * @category List
 * @sig Number => (* -> a) -> (* -> a)
 *
 * @param {Number} length The arity for the returned function
 * @param {Function} fn The function to curry
 * @return {Function}  A new, curried function
 * @see {@link http://ramdajs.com/docs/#curryN|curryN}, {@link RA.curryRight|curryRight}
 * @example
 *
 * const concatStrings = (a, b, c) => a + b + c;
 * const concatStringsCurried = RA.curryRightN(3, concatStrings);
 *
 * concatStringCurried('a')('b')('c'); // => 'cba'
 */
const curryRightN = curryN(2, (arity, fn) =>
  curryN(
    arity,
    function wrapper(...args) {
      return fn.apply(this, reverse(args));
    }
  )
);

export default curryRightN;
<commit_msg>docs(curryRightN): fix @since version tag<commit_after>import { curryN, reverse } from 'ramda';

/**
 * Returns a curried equivalent of the provided function, with the specified arity.
 * This function is like curryN, except that the provided arguments order is reversed.
 *
 * @func curryRightN
 * @memberOf RA
 * @since {@link https://char0n.github.io/ramda-adjunct/1.12.0|v1.12.0}
 * @category List
 * @sig Number => (* -> a) -> (* -> a)
 *
 * @param {Number} length The arity for the returned function
 * @param {Function} fn The function to curry
 * @return {Function}  A new, curried function
 * @see {@link http://ramdajs.com/docs/#curryN|curryN}, {@link RA.curryRight|curryRight}
 * @example
 *
 * const concatStrings = (a, b, c) => a + b + c;
 * const concatStringsCurried = RA.curryRightN(3, concatStrings);
 *
 * concatStringCurried('a')('b')('c'); // => 'cba'
 */
const curryRightN = curryN(2, (arity, fn) =>
  curryN(
    arity,
    function wrapper(...args) {
      return fn.apply(this, reverse(args));
    }
  )
);

export default curryRightN;
<|endoftext|>


<commit_before>var view = require('../../lib/view');
var Data = require('../../lib/data');
var utils = require('../../lib/utils');
var throttle = require('lodash.throttle');
var Sortable = require('sortable');
var publish = require('../../lib/publish');
var i18n = require('../../lib/i18n');

var sort;
var app;
var iconColors = utils.baseColors;

var iconImages = [
    'activist.png',
    'blogger.png',
    'howto.png',
    'journalist.png',
    'puppy.png',
    'safety.png',
    'scientist.png',
    'music.png',
    'teacher.png',
    'vendor.png',
    'family.png'
].map(function (icon) {
    return 'images/' + icon;
});

module.exports = view.extend({
    id: 'make',
    template: require('./index.html'),
    partials: {
        navigation: require('./navigation.html'),
        settings: require('./settings.html')
    },
    computed: {
        noBlock: function () {
            return this.$data.app.blocks ? this.$data.app.blocks.length : 0;
        }
    },
    methods: {
        showMenu: function () {
            this.$parent.$broadcast('openSideMenu');
            this.$parent.$broadcast('openShim');
        },
        goBack: function (e) {
            e.preventDefault();
            if (this.$data.mode === 'settings') {
                app.update({
                    iconImage: this.$data.originalIconImage,
                    iconColor: this.$data.originalIconColor
                });
                this.$data.changeMode('edit');
            } else {
                this.page('/profile');
            }
        },
        goPreviousView: function (e) {
            global.history.back();
        },
        enableSave: function () {
            this.$data.saveDisabled = false;
        },
        hideSpeech: function () {
            this.$data.app.faded = true;
        },
        onSave: function (e) {
            this.goBack(e);
        },
        updateName: throttle(function (newVal) {
            this.enableSave();
            app.update({
                name: newVal
            });
        }, 3000),
        previousIconImage: function () {
            this.selectIconImage('previous');
        },
        nextIconImage: function () {
            this.selectIconImage('next');
        },
        selectIconImage: function (direction) {

            var data = this.$data;
            var index = data.iconImages.indexOf(data.app.iconImage) || 0;
            var maxIndex = data.iconImages.length - 1;

            direction === 'next' ? index++ : index--;
            if (index < 0) {
                index = maxIndex;
            }
            if (index > maxIndex) {
                index = 0;
            }
            this.enableSave();
            app.update({
                iconImage: data.iconImages[index]
            });

            this.$data.currentIconIndex = index;
        },
        onSelectIconColor: function (color) {
            this.enableSave();
            app.update({
                iconColor: color
            });
        },
        saveAppSettings: function () {
            if (this.$data.mode === 'settings') {
                this.$data.changeMode('edit');
            }
        },
        removeApp: function () {
            app.removeApp();
            this.page('/profile');
        },
        publish: function () {
            var self = this;
            var id = self.$root.$data.params.id;
            var user = this.model.data.session.user;
            var root = self.$root;

            // Publish
            root.$broadcast('publishingStarted');
            publish(id, user, function (err, data) {

                if (err) {
                    root.$broadcast('publishingError', err);
                    return;
                }

                root.$broadcast('publishingDone');
                console.log('[Publish]', data.url);

                // Native Sharing (Android / iOS) or dispatch SMS (FirefoxOS)
                var msg = i18n.get('share_message');
                var url = data.url;
                if (typeof window.plugins === 'undefined') return;
                if (typeof window.plugins.socialsharing !== 'undefined') {
                    window.plugins.socialsharing.share(msg, null, null, url);
                } else {
                    window.location.href = 'sms:?body=' + msg + ' ' + url;
                }
            });
        },
        fadeOut: function (element) {
            this.hideSpeech();

            var op = 1;  // initial opacity
            var timer = setInterval(function () {
                if (op <= 0.1) {
                    clearInterval(timer);
                    element.style.display = 'none';
                }
                element.style.opacity = op;
                element.style.filter = 'alpha(opacity=' + op * 100 + ")";
                op -= op * 0.1;
            }, 50);
        }
    },
    ready: function () {
        var self = this;
        var element = self.$el.querySelector(".fadeAway");

        if (element) {
            setTimeout(function () {
                self.fadeOut(element);
            }, 3000);
        }

        self.$on('sideMenuDeleteClick', function (event) {
            self.$dispatch('openModalPrompt', {type: 'delete'});
        });

        self.$on('sideMenuShareClick', function (event) {
            self.publish();
        });

        self.$on('sideMenuDataClick', function (event) {
            this.mode = 'data';
        });

        self.$on('onConfirmClick', function (event) {
            console.warn('Deleting app!');
            self.removeApp();
        });

        // Broadcast individual editor starts to all inline editors
        // This is so that they know to hide if another one opens
        self.$on('inlineEditorStarted', function (event) {
            self.$broadcast('inlineEditorStarted', event);
        });
    },
    created: function () {
        var self = this;
        var id = self.$root.$data.params.id;
        var storage = self.$root.storage;
        var isDragging = false;

        app = storage.getApp(id);

        self.$data.saveDisabled = true;
        self.$data.iconColors = iconColors;
        self.$data.iconImages = iconImages;

        var list = self.$el.querySelector('.blocks');

        function getIndex(nodeList, el) {
            for (var i = 0; i < nodeList.length; i++) {
                if (nodeList[i] === el) {
                    return i;
                }
            }
        }

        function onValue(val) {
            self.$root.isReady = true;

            if (isDragging) return;

            if (!val) return;
            self.$data.app = val;

            var blocks = val.blocks;

            try {
                if (sort) sort.destroy();
            } catch (e) {
                console.log('sort error', e);
            }

            sort = new Sortable(list, {
                handle: '.draggable-handle',
                scroll: self.$root.$el,
                onStart: function () {
                    isDragging = true;
                },
                onEnd: function (e) {
                    isDragging = false;

                    var el = e.target;
                    var lis = list.querySelectorAll('li');
                    var start = el.getAttribute('index');
                    var end = getIndex(lis, el);

                    isDragging = false;

                    blocks.splice(end, 0, blocks.splice(start, 1)[0]);
                    // update
                    app.update({
                        blocks: blocks
                    });
                }
            });
        }

        if (app.data) {
            onValue(app.data);
            self.$data.originalIconImage = self.$data.app.iconImage;
            self.$data.originalIconColor = self.$data.app.iconColor;
        }

        self.$on(id, onValue);

        // Modes
        // ---------------------------------------------------------------------
        self.$data.changeMode = function (mode) {
            var modes = ['edit', 'settings'];
            if (modes.indexOf(mode) === -1) {
                console.log('warning: ' + mode + ' is not a valid mode');
                mode = 'edit';
            }
            if (mode === 'settings' && self.$data.mode === 'settings') {
                mode = 'edit';
            }
            self.$data.saveDisabled = true;
            self.$data.mode = mode;
            self.$root.isEditing = self.$data.mode === 'edit';
        };

        var regex = new RegExp('[\\?&]mode=([^&#]*)');
        var results = regex.exec(window.location.search);

        var mode = results ? results[1] : 'edit';
        self.$data.changeMode(mode);

        self.$data.goTo = function (href, $event) {
            if (self.$data.mode !== 'edit') return;
            self.page(href);
        };

        // Handle save events
        // ---------------------------------------------------------------------
        var data = new Data(id);
        self.$on('dataSave', function () {
            data.collect(this.$el, function onDataSave(err) {
                if (err) return console.log('[Firebase] ' + err);
                self.$broadcast('dataSaveSuccess');
            });
        });
    }
});
<commit_msg>Resolve lint issue<commit_after>var view = require('../../lib/view');
var Data = require('../../lib/data');
var utils = require('../../lib/utils');
var throttle = require('lodash.throttle');
var Sortable = require('sortable');
var publish = require('../../lib/publish');
var i18n = require('../../lib/i18n');

var sort;
var app;
var iconColors = utils.baseColors;

var iconImages = [
    'activist.png',
    'blogger.png',
    'howto.png',
    'journalist.png',
    'puppy.png',
    'safety.png',
    'scientist.png',
    'music.png',
    'teacher.png',
    'vendor.png',
    'family.png'
].map(function (icon) {
    return 'images/' + icon;
});

module.exports = view.extend({
    id: 'make',
    template: require('./index.html'),
    partials: {
        navigation: require('./navigation.html'),
        settings: require('./settings.html')
    },
    computed: {
        noBlock: function () {
            return this.$data.app.blocks ? this.$data.app.blocks.length : 0;
        }
    },
    methods: {
        showMenu: function () {
            this.$parent.$broadcast('openSideMenu');
            this.$parent.$broadcast('openShim');
        },
        goBack: function (e) {
            e.preventDefault();
            if (this.$data.mode === 'settings') {
                app.update({
                    iconImage: this.$data.originalIconImage,
                    iconColor: this.$data.originalIconColor
                });
                this.$data.changeMode('edit');
            } else {
                this.page('/profile');
            }
        },
        goPreviousView: function (e) {
            global.history.back();
        },
        enableSave: function () {
            this.$data.saveDisabled = false;
        },
        hideSpeech: function () {
            this.$data.app.faded = true;
        },
        onSave: function (e) {
            this.goBack(e);
        },
        updateName: throttle(function (newVal) {
            this.enableSave();
            app.update({
                name: newVal
            });
        }, 3000),
        previousIconImage: function () {
            this.selectIconImage('previous');
        },
        nextIconImage: function () {
            this.selectIconImage('next');
        },
        selectIconImage: function (direction) {

            var data = this.$data;
            var index = data.iconImages.indexOf(data.app.iconImage) || 0;
            var maxIndex = data.iconImages.length - 1;

            direction === 'next' ? index++ : index--;
            if (index < 0) {
                index = maxIndex;
            }
            if (index > maxIndex) {
                index = 0;
            }
            this.enableSave();
            app.update({
                iconImage: data.iconImages[index]
            });

            this.$data.currentIconIndex = index;
        },
        onSelectIconColor: function (color) {
            this.enableSave();
            app.update({
                iconColor: color
            });
        },
        saveAppSettings: function () {
            if (this.$data.mode === 'settings') {
                this.$data.changeMode('edit');
            }
        },
        removeApp: function () {
            app.removeApp();
            this.page('/profile');
        },
        publish: function () {
            var self = this;
            var id = self.$root.$data.params.id;
            var user = this.model.data.session.user;
            var root = self.$root;

            // Publish
            root.$broadcast('publishingStarted');
            publish(id, user, function (err, data) {

                if (err) {
                    root.$broadcast('publishingError', err);
                    return;
                }

                root.$broadcast('publishingDone');
                console.log('[Publish]', data.url);

                // Native Sharing (Android / iOS) or dispatch SMS (FirefoxOS)
                var msg = i18n.get('share_message');
                var url = data.url;
                if (typeof window.plugins === 'undefined') return;
                if (typeof window.plugins.socialsharing !== 'undefined') {
                    window.plugins.socialsharing.share(msg, null, null, url);
                } else {
                    window.location.href = 'sms:?body=' + msg + ' ' + url;
                }
            });
        },
        fadeOut: function (element) {
            this.hideSpeech();

            var op = 1;  // initial opacity
            var timer = setInterval(function () {
                if (op <= 0.1) {
                    clearInterval(timer);
                    element.style.display = 'none';
                }
                element.style.opacity = op;
                element.style.filter = 'alpha(opacity=' + op * 100 + ')';
                op -= op * 0.1;
            }, 50);
        }
    },
    ready: function () {
        var self = this;
        var element = self.$el.querySelector('.fadeAway');

        if (element) {
            setTimeout(function () {
                self.fadeOut(element);
            }, 3000);
        }

        self.$on('sideMenuDeleteClick', function (event) {
            self.$dispatch('openModalPrompt', {type: 'delete'});
        });

        self.$on('sideMenuShareClick', function (event) {
            self.publish();
        });

        self.$on('sideMenuDataClick', function (event) {
            this.mode = 'data';
        });

        self.$on('onConfirmClick', function (event) {
            console.warn('Deleting app!');
            self.removeApp();
        });

        // Broadcast individual editor starts to all inline editors
        // This is so that they know to hide if another one opens
        self.$on('inlineEditorStarted', function (event) {
            self.$broadcast('inlineEditorStarted', event);
        });
    },
    created: function () {
        var self = this;
        var id = self.$root.$data.params.id;
        var storage = self.$root.storage;
        var isDragging = false;

        app = storage.getApp(id);

        self.$data.saveDisabled = true;
        self.$data.iconColors = iconColors;
        self.$data.iconImages = iconImages;

        var list = self.$el.querySelector('.blocks');

        function getIndex(nodeList, el) {
            for (var i = 0; i < nodeList.length; i++) {
                if (nodeList[i] === el) {
                    return i;
                }
            }
        }

        function onValue(val) {
            self.$root.isReady = true;

            if (isDragging) return;

            if (!val) return;
            self.$data.app = val;

            var blocks = val.blocks;

            try {
                if (sort) sort.destroy();
            } catch (e) {
                console.log('sort error', e);
            }

            sort = new Sortable(list, {
                handle: '.draggable-handle',
                scroll: self.$root.$el,
                onStart: function () {
                    isDragging = true;
                },
                onEnd: function (e) {
                    isDragging = false;

                    var el = e.target;
                    var lis = list.querySelectorAll('li');
                    var start = el.getAttribute('index');
                    var end = getIndex(lis, el);

                    isDragging = false;

                    blocks.splice(end, 0, blocks.splice(start, 1)[0]);
                    // update
                    app.update({
                        blocks: blocks
                    });
                }
            });
        }

        if (app.data) {
            onValue(app.data);
            self.$data.originalIconImage = self.$data.app.iconImage;
            self.$data.originalIconColor = self.$data.app.iconColor;
        }

        self.$on(id, onValue);

        // Modes
        // ---------------------------------------------------------------------
        self.$data.changeMode = function (mode) {
            var modes = ['edit', 'settings'];
            if (modes.indexOf(mode) === -1) {
                console.log('warning: ' + mode + ' is not a valid mode');
                mode = 'edit';
            }
            if (mode === 'settings' && self.$data.mode === 'settings') {
                mode = 'edit';
            }
            self.$data.saveDisabled = true;
            self.$data.mode = mode;
            self.$root.isEditing = self.$data.mode === 'edit';
        };

        var regex = new RegExp('[\\?&]mode=([^&#]*)');
        var results = regex.exec(window.location.search);

        var mode = results ? results[1] : 'edit';
        self.$data.changeMode(mode);

        self.$data.goTo = function (href, $event) {
            if (self.$data.mode !== 'edit') return;
            self.page(href);
        };

        // Handle save events
        // ---------------------------------------------------------------------
        var data = new Data(id);
        self.$on('dataSave', function () {
            data.collect(this.$el, function onDataSave(err) {
                if (err) return console.log('[Firebase] ' + err);
                self.$broadcast('dataSaveSuccess');
            });
        });
    }
});
<|endoftext|>


<commit_before>Ext.define('CustomApp', {
    extend: 'Rally.app.App',
    componentCls: 'app',

    launch: function() {

        console.log(this.getContext().getDataContext());

        // Create a query to grab specific build definitions
        var query = this._createQuery();

        // get the build store
        this._getBuildStore(query);

        Rally.data.ModelFactory.getModel({
            type:'Build Definition',
            scope:this,
            success: function(model){

                var myGrid = Ext.create('Rally.ui.grid.Grid',{
                    model: model,
                    columnCfgs: [
                        'Name',
                        'Description',
                        'LastStatus'
                        ]
                });
                this.add(myGrid);

            },
            failure: function(){
                console.log("failed");
            },
            context: {
                workspace: "/workspace/4365660833"
            }

        });

        var msgBox = Ext.MessageBox;
        var myButton = Ext.create('Rally.ui.Button',{
            text:'click me!',
            handler:function(button,e){
                msgBox.alert("clicked!");
            }

        });

        this.add(myButton);

    },

    // Creates a query for specific build definitions
    _createQuery: function(){

        var q = Ext.create('Rally.data.QueryFilter', {
            property:'BuildDefinition',
            operator:'=',
            value: '/slm/webservice/1.37/builddefinition/6035424766' //PacSystems Mainline Build Definition
        });

        return q;

    },

    _getBuildStore: function(query){

        var builds = Ext.create('Rally.data.WsapiDataStore', {
            model: 'Build',
            fetch: true,
            listeners: {
                load: function(store,data,success) {
                    console.log("returned with data");
                    console.log(store,data);
                }
            },
            sorters: [{
                property: 'CreationDate',
                direction: 'DESC'
            }],
            filters: query,
            autoLoad: true,
            pageSize:20
        });
    }

});
<commit_msg>Adds struct with fail count<commit_after>Ext.define('CustomApp', {
    extend: 'Rally.app.App',
    componentCls: 'app',

    launch: function() {

        this._loadBuildDefs();

        Rally.data.ModelFactory.getModel({
            type:'Build Definition',
            scope:this,
            success: function(model){

                var myGrid = Ext.create('Rally.ui.grid.Grid',{
                    model: model,
                    columnCfgs: [
                        'Name',
                        'Description',
                        'LastStatus'
                        ]
                });
                this.add(myGrid);

            },
            context: {
                workspace: "/workspace/4365660833"
            }

        });

    },

    // Creates a query for specific build definitions
    _createQuery: function(buildDefRecords){

        // get first entry
        var q = Ext.create('Rally.data.QueryFilter', {
            property:'BuildDefinition',
            operator:'=',
            value: buildDefRecords[0].get('_ref')
//            value: '/slm/webservice/1.37/builddefinition/6035424766' //PacSystems Mainline Build Definition
        });

        // remove teh first entry
        Ext.Array.remove(buildDefRecords,buildDefRecords[0]);

        // cycle through the remaineder in the array
        Ext.Array.forEach(buildDefRecords,function(item, index, allItems){
            q = q.or(Ext.create('Rally.data.QueryFilter', {
                property:'BuildDefinition',
                operator:'=',
                value: item.get('_ref')
            }));
        });

        console.log("query = ", q.toString());

        return q;

    },

    _getBuilds: function(buildDefRecords){
        var query = this._createQuery(buildDefRecords);

        Ext.create('Rally.data.WsapiDataStore', {
            model: 'Build',
            fetch: true,
            listeners: {
                load: function(store,records,success) {
                    console.log("Fetched %d builds", records.length);
                    Ext.Array.forEach(records, function(item) {
//                        console.log("Name: %s, Def: %s, Status %s", item.get("Number"), item.get("BuildDefinition")._ref, item.get("Status"));
                    });
                    this._siftBuilds(records);
                },
                scope:this
            },
            sorters: [{
                property: 'CreationDate',
                direction: 'DESC'
            }],
            filters: query,
            autoLoad: true,
            pageSize:100
        });
    },

    _loadBuildDefs: function(){

        Ext.create('Rally.data.WsapiDataStore', {
            model: 'Build Definition',
            fetch: true,
            listeners: {
                load: function(store,records,success) {
                    console.log("Loaded %d Build Definitions.", records.length);

                    this.buildDefinitions = [];
                    Ext.Array.forEach(records,function(item){
                        Ext.Array.push(this.buildDefinitions,item.get("_ref"));

                    },this);
                    console.log("Build definitions array ",this.buildDefinitions);

                    this._getBuilds(records);
                },
                scope:this
            },
            autoLoad: true
        });

    },

    // creates the build def/ build record data struct
    _siftBuilds: function(buildDefBuildRecords){

        var buildStructure = {};

        // Create a build structure
        Ext.Array.forEach(buildDefBuildRecords, function(item){
            build = item;
            buildDef = item.get("BuildDefinition")._ref;

            if (!buildStructure.hasOwnProperty(buildDef)){
                buildStructure[buildDef] = {
                    builds:[build],
                    lastBuild:null,
                    failCount:0
                };
//                console.log("Added new build def %s",buildDef);

            } else {
                Ext.Array.push(buildStructure[buildDef].builds,build);
//                console.log("Pushed build  %s",item.get("Number"));
            }

        });

        //Now update the lastGoodBuild and failCount fields

        // for each build ref
        //    for each build
        //      if build failed
        //          increment failCount
        //      else
        //          set lastGoodBuild
        //          break;
        Ext.Array.forEach(this.buildDefinitions, function(item){

            var buildDef = item;
            buildStructure[buildDef].failCount = 0;

//            console.log("Working on %s",buildDef);

            Ext.Array.forEach(buildStructure[item].builds, function(item){

                var build = item;

                if (build.get("Status") === "FAILURE" )
                {
                    if (buildStructure[buildDef].lastGoodBuild == undefined)
                    {
                        buildStructure[buildDef].failCount = buildStructure[buildDef].failCount + 1;
//                        console.log("%s failed, failCount %d",build.get("Number"), buildStructure[buildDef].failCount);
                    } else {
                        return;
                    }
                } else {
//                    console.log("%s succeeded, failCount %d",build.get("Number"), buildStructure[buildDef].failCount);
                    buildStructure[buildDef].lastGoodBuild = build;
                    return;
                }

            });

            console.log("Build %s Fails %d",buildDef,buildStructure[buildDef].failCount);

           //

        });

        console.log(buildStructure);
    }

});
<|endoftext|>


<commit_before><commit_msg>Testing<commit_after>// Load the http module to create an http server.
var http = require('http');

// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.end("Hello World\n");
});

// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);<|endoftext|>


<commit_before><commit_msg>fix preload bug. etc.<commit_after><|endoftext|>


<commit_before>var DLV = Backbone.View.extend({
    constructor: function(options) {
        options || (options = {});
        if (options.listeners) {
            this.listeners = options.listeners;
        }
        Backbone.View.apply(this, arguments);
        this.delegateListeners();
    },
    delegateListeners: function(listeners) {
        if (!(listeners || (listeners = _.result(this, 'listeners')))) {
            return this;
        }
        this.undelegateListeners();
        for (var key in listeners) {
            var method = listeners[key];
            if (!_.isFunction(method)) {
                method = this[listeners[key]];
            }
            if (!method) {
                continue;
            }
            var match = key.match(/\S+/g);
            var other = match.pop();
            other = (other === 'this') ? this : this[other];
            if (!other) {
                continue;
            }
            this.listenTo(other, match.join(' '), method);
        }
    },
    undelegateListeners: function() {
        for (var key in this.listeners) {
            var match = key.match(/\S+/g);
            var other = match.pop();
            other = (other === 'this') ? this : this[other];
            if (!other) {
                continue;
            }
            this.stopListening(other);
        }
    }
});
<commit_msg>dry up rex for delegate listener splitter.<commit_after>var delegateListenerSplitter = /\S+/g;
var DLV = Backbone.View.extend({
    constructor: function(options) {
        options || (options = {});
        if (options.listeners) {
            this.listeners = options.listeners;
        }
        Backbone.View.apply(this, arguments);
        this.delegateListeners();
    },
    delegateListeners: function(listeners) {
        if (!(listeners || (listeners = _.result(this, 'listeners')))) {
            return this;
        }
        this.undelegateListeners();
        for (var key in listeners) {
            var method = listeners[key];
            if (!_.isFunction(method)) {
                method = this[listeners[key]];
            }
            if (!method) {
                continue;
            }
            var match = key.match(delegateListenerSplitter);
            var other = match.pop();
            other = (other === 'this') ? this : this[other];
            if (!other) {
                continue;
            }
            this.listenTo(other, match.join(' '), method);
        }
    },
    undelegateListeners: function() {
        for (var key in this.listeners) {
            var match = key.match(delegateListenerSplitter);
            var other = match.pop();
            other = (other === 'this') ? this : this[other];
            if (!other) {
                continue;
            }
            this.stopListening(other);
        }
    }
});
<|endoftext|>


<commit_before>define(function(require, exports, module) {
    main.consumes = [
        "Editor", "editors", "ui", "save", "vfs", "layout"
    ];
    main.provides = ["imgeditor"];
    return main;

    function main(options, imports, register) {
        var ui       = imports.ui;
        var vfs      = imports.vfs;
        var save     = imports.save;
        var layout   = imports.layout;
        var Editor   = imports.Editor;
        var editors  = imports.editors;

        var event    = require("ace/lib/event");
        var Pixastic = require("./lib_pixastic");

        var counter     = 0;
        var loadedFiles = {};

        /***** Initialization *****/

        var extensions = ["bmp", "djv", "djvu", "jpg", "jpeg",
                          "pbm", "pgm", "png", "pnm", "ppm", "psd", "tiff",
                          "xbm", "xpm"];

        var handle = editors.register("imgeditor", "Image Editor", ImageEditor, extensions);

        var drawn;
        handle.draw = function(){
            if (drawn) return;
            drawn = true;

            // Insert CSS
            ui.insertCss(require("text!./style.css"),
                options.staticPrefix, handle);
        };

        // @todo revert to saved doesnt work (same for file watcher reload)
        // @todo getState/setState
        // @todo keep canvas reference on session and remove loadedFiles
        // @Todo for later - add undo stack
        function UndoItem(original, changed, apply){
            this.getState = function(){ }
            this.undo = function(){
                apply(original);
            }
            this.redo = function(){
                apply(changed);
            }
        }
        // undoManager.on("itemFind", function(e){
        //     return new Item(e.state[0], e.state[1]);
        // });

        function ImageEditor(){
            var plugin = new Editor("Ajax.org", main.consumes, extensions);

            var BGCOLOR = "#3D3D3D";
            var img, canvas, activeDocument, rect, crop, zoom, info, rectinfo;
            var editor;

            plugin.on("draw", function(e){
                handle.draw();

                ui.insertMarkup(e.tab, require("text!./imgeditor.xml"), plugin);

                var parent = plugin.getElement("parent");
                var btn3   = plugin.getElement("btn3");
                var btn4   = plugin.getElement("btn4");
                var btn5   = plugin.getElement("btn5");
                var btn6   = plugin.getElement("btn6");

                editor   = plugin.getElement("imgEditor");
                crop     = plugin.getElement("btn2");
                zoom     = plugin.getElement("zoom");
                info     = plugin.getElement("info");
                rectinfo = plugin.getElement("rectinfo");

                // Background color
                parent.$ext.style.backgroundColor = BGCOLOR;

                // Rectangle
                rect = document.createElement("div");
                editor.$ext.appendChild(rect);
                rect.className = "imgeditorrect";

                img    = editor.$ext.querySelector("img");
                canvas = function(){
                    return editor.$ext.querySelector("canvas");
                }

                // Zoom
                zoom.on("afterchange", function(){
                    ui.setStyleRule(".imgeditor canvas",
                        apf.CSSPREFIX2 + "-transform",
                        "scale(" + (zoom.value / 100) + ")");

                    var session = activeDocument.getSession();
                    session.zoom = zoom.value;

                    clearRect();
                });

                // resize width/height
                crop.on("click", function(){ exec("crop") });
                btn3.on("click", function(){ exec("rotate", { angle: -90 }); });
                btn4.on("click", function(){ exec("rotate", { angle: 90 }); });
                btn5.on("click", function(){ exec("fliph"); });
                btn6.on("click", function(){ exec("flipv"); });

                editor.$ext.onmousemove = function(e){
                    if (rect.style.display != "none")
                        return;

                    var cnvs  = canvas();
                    var pos   = cnvs.getBoundingClientRect();
                    var left  = e.clientX - pos.left;
                    var top   = e.clientY - pos.top;

                    var zoomLevel = zoom.value / 100;
                    if (left < 0 || top < 0
                      || left > pos.width || top > pos.height)
                        left = top = 0;

                    rectinfo.setAttribute("caption",
                        "L: " + (left / zoomLevel) + "px, "
                        + "T: " + (top / zoomLevel) + "px");
                }

                editor.$ext.onmousedown = function(e){
                    var cnvs  = canvas();
                    var pos   = cnvs.getBoundingClientRect();
                    var left  = e.clientX - pos.left;
                    var top   = e.clientY - pos.top;
                    if (left < 0 || top < 0
                      || left > pos.width || top > pos.height)
                        return;

                    startRect(e);
                };

                function saveCanvas(path, value, callback){
                    var dataURL = loadedFiles[path];
                    var binary  = atob(dataURL.split(',')[1]);

                    vfs.rest(path, {
                        method : "PUT",
                        body   : binary
                    }, function(err, data, res) {
                        callback(err, data);
                    });
                }

                save.on("beforeSave", function(e) {
                    if (e.document.editor.type == "imgeditor"){
                        var path = e.document.tab.path;

                        if (e.document == activeDocument)
                            loadedFiles[path] = canvas().toDataURL();

                        return saveCanvas;
                    }
                });

                // Not sure what this is supposed to do
                // save.on("afterSave", function(e) {
                //     console.log("afterfilesave");
                //     var path = e.document.tab.path;
                //     if (!path)
                //         return;

                //     var newPath = e.doc && e.doc.getNode && e.doc.getNode().getAttribute("path");
                //     if (editor.value == e.oldpath && newPath !== e.oldpath){
                //         var dataURL = _canvas.toDataURL();
                //         saveCanvas(newPath,dataURL);
                //         return false;
                //     }
                // });

                if (!editor.focus)
                    editor.focus = function(){ return false;};

                editor.show();
            });

            /***** Method *****/

            function setPath(path, doc){
                if (!path) return;

                // Caption is the filename
                doc.title = path.substr(path.lastIndexOf("/") + 1);

                // Tooltip is the full path
                doc.tooltip = path;

                var fullpath = path.match(/^\w+:\/\//)
                    ? path
                    : vfs.url(path);

                // editor.setProperty("value", apf.escapeXML(fullpath));
                loadCanvas(doc.tab, fullpath);
            }

            function loadCanvas(tab, path){
                var idx  = tab.path;
                var cnvs = canvas();
                var ctx  = cnvs.getContext("2d");

                if (path && !loadedFiles[idx]){
                    tab.className.add("connecting");

                    img.onload = function(){
                        cnvs.width         = img.width;
                        cnvs.height        = img.height;
                        cnvs.style.display = "inline-block";
                        img.style.display  = "none";

                        ctx.drawImage(img, 0, 0);
                        loadedFiles[idx] = cnvs.toDataURL();

                        info.setAttribute("caption",
                            "W:" + img.width + "px, H:" + img.height + "px");

                        tab.className.remove("connecting");
                    };
                    img.onerror = function(){
                        tab.className.remove("connecting");
                        tab.className.add("error");

                        img.src = options.staticPrefix + "/sorry.jpg";

                        layout.showError("Invalid or Unsupported Image Format");
                    }

                    img.src = path;
                }
                else {
                    img.onload = function(){
                        cnvs.width         = img.width;
                        cnvs.height        = img.height;
                        cnvs.style.display = "inline-block";
                        img.style.display  = "none";

                        info.setAttribute("caption",
                            "W:" + img.width + "px, H:" + img.height + "px");

                        ctx.drawImage(img, 0, 0);
                    };

                    img.src = loadedFiles[idx];
                }
            }

            function startRect(e){
                var container = rect.parentNode;
                var pos       = container.getBoundingClientRect();
                var cnvs      = canvas();
                var htmlNode  = editor.$ext;

                var startX  = e.clientX + htmlNode.scrollLeft;
                var startY  = e.clientY + htmlNode.scrollTop;
                var moved;

                event.capture(container, function(e) {
                    if (!moved) {
                        if (Math.abs(startX - e.clientX) + Math.abs(startY - e.clientY) > 5) {
                            moved = true;
                            rect.style.display = "block";
                        }
                        else return;
                    }

                    var clientX = e.clientX + htmlNode.scrollLeft;
                    var clientY = e.clientY + htmlNode.scrollTop;

                    if (startX > clientX) {
                        rect.style.left = (clientX - pos.left) + "px";
                        rect.style.width  = (startX - clientX) + "px";
                    }
                    else {
                        rect.style.left = (startX - pos.left) + "px";
                        rect.style.width  = (clientX - startX) + "px";
                    }

                    if (startY > clientY) {
                        rect.style.top  = (clientY - pos.top) + "px";
                        rect.style.height = (startY - clientY) + "px";
                    }
                    else {
                        rect.style.top  = (startY - pos.top) + "px";
                        rect.style.height = (clientY - startY) + "px";
                    }

                    var zoomLevel = zoom.value / 100;
                    rectinfo.setAttribute("caption",
                        "L: " + ((rect.offsetLeft - cnvs.offsetLeft) / zoomLevel) + "px, "
                        + "T: " + ((rect.offsetTop - cnvs.offsetTop) / zoomLevel) + "px, "
                        + "W: " + (rect.offsetWidth / zoomLevel) + "px, "
                        + "H: " + (rect.offsetHeight / zoomLevel) + "px");

                }, function() {
                    if (moved) {
                        activeDocument.getSession().rect = {
                            left   : rect.style.left,
                            top    : rect.style.top,
                            width  : rect.style.width,
                            height : rect.style.height,
                        }
                        crop.enable();
                    }
                    else {
                        clearRect();
                    }
                });

                event.stopEvent(e);
            }

            function exec(action, options){
                var cnvs = canvas();
                var url  = cnvs.toDataURL();

                if (action == "crop") {
                    var zoomLevel = zoom.value / 100;

                    options = {
                        left   : (rect.offsetLeft - cnvs.offsetLeft) / zoomLevel,
                        top    : (rect.offsetTop - cnvs.offsetTop) / zoomLevel,
                        width  : (rect.offsetWidth) / zoomLevel,
                        height : (rect.offsetHeight) / zoomLevel
                    }
                }

                Pixastic.process(cnvs, action, options);
                clearRect();

                //@todo
                var doc = activeDocument;
                doc.undoManager.add(new UndoItem(url, canvas().toDataURL(), function(url){
                    loadedFiles[doc.tab.path] = url;
                    loadCanvas(doc.tab);
                }));
            }

            function clearRect(){
                rect.style.display = "none";
                delete activeDocument.getSession().rect;
                crop.disable();
            }

            plugin.on("documentLoad", function(e){
                var doc     = e.doc;
                var session = doc.getSession();

                doc.tab.on("setPath", function(e){
                    setPath(e.path, doc);
                }, session);

                // Changed marker
                function setChanged(e){
                    if (e.changed || doc.meta.newfile)
                        doc.tab.className.add("changed");
                    else
                        doc.tab.className.remove("changed");
                }
                doc.on("changed", setChanged, session);
                setChanged({ changed: doc.changed });

                doc.tab.backgroundColor = BGCOLOR;
                doc.tab.className.add("dark");

                canvas().style.display = "none";
            });

            plugin.on("documentActivate", function(e){
                var doc     = e.doc;
                var session = doc.getSession();
                var path    = doc.tab.path || doc.value;

                activeDocument = doc;

                // Set Image
                setPath(path, doc);

                // Set Toolbar
                zoom.setValue(session.zoom || 100);
                zoom.dispatchEvent("afterchange");

                // Set Rect
                if (session.rect) {
                    rect.style.display = "block";
                    rect.style.left   = session.rect.left;
                    rect.style.top    = session.rect.top;
                    rect.style.width  = session.rect.width;
                    rect.style.height = session.rect.height;
                }
                else {
                    rect.style.display = "none";
                }
            });

            plugin.on("documentUnload", function(e){
                delete loadedFiles[e.doc.tab.path || e.doc.value];
            });

            /***** Register and define API *****/

            /**
             * The imgeditor handle, responsible for events that involve all
             * ImageEditor instances. This is the object you get when you request
             * the imgeditor service in your plugin.
             *
             * Example:
             *
             *     define(function(require, exports, module) {
             *         main.consumes = ["imgeditor"];
             *         main.provides = ["myplugin"];
             *         return main;
             *
             *         function main(options, imports, register) {
             *             var imgeditorHandle = imports.imgeditor;
             *         });
             *     });
             *
             *
             * @class imgeditor
             * @extends Plugin
             * @singleton
             */
            /**
             * Read Only Image Viewer for Cloud9 IDE
             *
             * Example of instantiating a new terminal:
             *
             *     tabManager.openFile("/test.png", true, function(err, tab){
             *         if (err) throw err;
             *
             *         var imgeditor = tab.editor;
             *     });
             *
             * @class imgeditor.ImageEditor
             * @extends Editor
             **/
            /**
             * The type of editor. Use this to create the terminal using
             * {@link tabManager#openEditor} or {@link editors#createEditor}.
             * @property {"imgeditor"} type
             * @readonly
             */
            plugin.freezePublicAPI({});

            plugin.load("imgeditor" + counter++);

            return plugin;
        }
        ImageEditor.autoload = false;

        register(null, {
            imgeditor: handle
        });
    }
});<commit_msg>Fixes several issues<commit_after>define(function(require, exports, module) {
    main.consumes = [
        "Editor", "editors", "ui", "save", "vfs", "layout"
    ];
    main.provides = ["imgeditor"];
    return main;

    function main(options, imports, register) {
        var ui       = imports.ui;
        var vfs      = imports.vfs;
        var save     = imports.save;
        var layout   = imports.layout;
        var Editor   = imports.Editor;
        var editors  = imports.editors;

        var event    = require("ace/lib/event");
        var Pixastic = require("./lib_pixastic");

        var counter     = 0;
        var loadedFiles = {};

        /***** Initialization *****/

        var extensions = ["bmp", "djv", "djvu", "jpg", "jpeg",
                          "pbm", "pgm", "png", "pnm", "ppm", "psd", "tiff",
                          "xbm", "xpm"];

        var handle = editors.register("imgeditor", "Image Editor", ImageEditor, extensions);

        var drawn;
        handle.draw = function(){
            if (drawn) return;
            drawn = true;

            // Insert CSS
            ui.insertCss(require("text!./style.css"),
                options.staticPrefix, handle);
        };

        // @todo revert to saved doesnt work (same for file watcher reload)
        // @todo getState/setState
        // @todo keep canvas reference on session and remove loadedFiles
        // @Todo for later - add undo stack
        function UndoItem(original, changed, apply){
            this.getState = function(){ }
            this.undo = function(){
                apply(original);
            }
            this.redo = function(){
                apply(changed);
            }
        }
        // undoManager.on("itemFind", function(e){
        //     return new Item(e.state[0], e.state[1]);
        // });

        function ImageEditor(){
            var plugin = new Editor("Ajax.org", main.consumes, extensions);

            var BGCOLOR = "#3D3D3D";
            var img, canvas, activeDocument, rect, crop, zoom, info, rectinfo;
            var editor;

            plugin.on("draw", function(e){
                handle.draw();

                ui.insertMarkup(e.tab, require("text!./imgeditor.xml"), plugin);

                var parent = plugin.getElement("parent");
                var btn3   = plugin.getElement("btn3");
                var btn4   = plugin.getElement("btn4");
                var btn5   = plugin.getElement("btn5");
                var btn6   = plugin.getElement("btn6");

                editor   = plugin.getElement("imgEditor");
                crop     = plugin.getElement("btn2");
                zoom     = plugin.getElement("zoom");
                info     = plugin.getElement("info");
                rectinfo = plugin.getElement("rectinfo");

                // Background color
                parent.$ext.style.backgroundColor = BGCOLOR;

                // Rectangle
                rect = document.createElement("div");
                editor.$ext.appendChild(rect);
                rect.className = "imgeditorrect";

                img    = editor.$ext.querySelector("img");
                canvas = function(){
                    return editor.$ext.querySelector("canvas");
                }

                // Zoom
                zoom.on("afterchange", function(){
                    ui.setStyleRule(".imgeditor canvas",
                        apf.CSSPREFIX2 + "-transform",
                        "scale(" + (zoom.value / 100) + ")");

                    var session = activeDocument.getSession();
                    session.zoom = zoom.value;

                    clearRect();
                });

                // resize width/height
                crop.on("click", function(){ exec("crop") });
                btn3.on("click", function(){ exec("rotate", { angle: -90 }); });
                btn4.on("click", function(){ exec("rotate", { angle: 90 }); });
                btn5.on("click", function(){ exec("fliph"); });
                btn6.on("click", function(){ exec("flipv"); });

                editor.$ext.onmousemove = function(e){
                    if (rect.style.display != "none")
                        return;

                    var cnvs  = canvas();
                    var pos   = cnvs.getBoundingClientRect();
                    var left  = e.clientX - pos.left;
                    var top   = e.clientY - pos.top;

                    var zoomLevel = zoom.value / 100;
                    if (left < 0 || top < 0
                      || left > pos.width || top > pos.height)
                        left = top = 0;

                    rectinfo.setAttribute("caption",
                        "L: " + (left / zoomLevel) + "px, "
                        + "T: " + (top / zoomLevel) + "px");
                }

                editor.$ext.onmousedown = function(e){
                    var cnvs  = canvas();
                    var pos   = cnvs.getBoundingClientRect();
                    var left  = e.clientX - pos.left;
                    var top   = e.clientY - pos.top;
                    if (left < 0 || top < 0
                      || left > pos.width || top > pos.height)
                        return;

                    startRect(e);
                };

                function saveCanvas(path, value, callback){
                    var dataURL = loadedFiles[path];
                    var binary  = atob(dataURL.split(',')[1]);

                    vfs.rest(path, {
                        method : "PUT",
                        body   : binary
                    }, function(err, data, res) {
                        callback(err, data);
                    });
                }

                save.on("beforeSave", function(e) {
                    if (e.document.editor.type == "imgeditor"){
                        var path = e.document.tab.path;

                        if (e.document == activeDocument)
                            loadedFiles[path] = canvas().toDataURL();

                        return saveCanvas;
                    }
                });

                // Not sure what this is supposed to do
                // save.on("afterSave", function(e) {
                //     console.log("afterfilesave");
                //     var path = e.document.tab.path;
                //     if (!path)
                //         return;

                //     var newPath = e.doc && e.doc.getNode && e.doc.getNode().getAttribute("path");
                //     if (editor.value == e.oldpath && newPath !== e.oldpath){
                //         var dataURL = _canvas.toDataURL();
                //         saveCanvas(newPath,dataURL);
                //         return false;
                //     }
                // });

                if (!editor.focus)
                    editor.focus = function(){ return false;};

                editor.show();
            });

            /***** Method *****/

            function setPath(path, doc, callback){
                if (!path) return;

                // Caption is the filename
                doc.title = path.substr(path.lastIndexOf("/") + 1);

                // Tooltip is the full path
                doc.tooltip = path;

                var fullpath = path.match(/^\w+:\/\//)
                    ? path
                    : vfs.url(path);

                // editor.setProperty("value", apf.escapeXML(fullpath));
                loadCanvas(doc.tab, fullpath, callback);
            }

            function loadCanvas(tab, path, callback){
                var idx  = tab.path;
                var cnvs = canvas();
                var ctx  = cnvs.getContext("2d");

                if (path && !loadedFiles[idx]){
                    tab.className.add("connecting");

                    img.onload = function(){
                        cnvs.width         = img.width;
                        cnvs.height        = img.height;
                        cnvs.style.display = "inline-block";
                        img.style.display  = "none";

                        ctx.drawImage(img, 0, 0);
                        loadedFiles[idx] = cnvs.toDataURL();

                        info.setAttribute("caption",
                            "W:" + img.width + "px, H:" + img.height + "px");

                        tab.className.remove("connecting");

                        callback && callback(loadedFiles[idx]);
                    };
                    img.onerror = function(){
                        tab.className.remove("connecting");
                        tab.className.add("error");

                        img.src = options.staticPrefix + "/sorry.jpg";

                        layout.showError("Invalid or Unsupported Image Format");
                    }

                    img.src = path;
                }
                else {
                    img.onload = function(){
                        cnvs.width         = img.width;
                        cnvs.height        = img.height;
                        cnvs.style.display = "inline-block";
                        img.style.display  = "none";

                        info.setAttribute("caption",
                            "W:" + img.width + "px, H:" + img.height + "px");

                        ctx.drawImage(img, 0, 0);
                    };

                    img.src = loadedFiles[idx];

                    callback && callback(loadedFiles[idx]);
                }
            }

            function startRect(e){
                var container = rect.parentNode;
                var pos       = container.getBoundingClientRect();
                var cnvs      = canvas();
                var htmlNode  = editor.$ext;

                var startX  = e.clientX + htmlNode.scrollLeft;
                var startY  = e.clientY + htmlNode.scrollTop;
                var moved;

                event.capture(container, function(e) {
                    if (!moved) {
                        if (Math.abs(startX - e.clientX) + Math.abs(startY - e.clientY) > 5) {
                            moved = true;
                            rect.style.display = "block";
                        }
                        else return;
                    }

                    var clientX = e.clientX + htmlNode.scrollLeft;
                    var clientY = e.clientY + htmlNode.scrollTop;

                    if (startX > clientX) {
                        rect.style.left = (clientX - pos.left) + "px";
                        rect.style.width  = (startX - clientX) + "px";
                    }
                    else {
                        rect.style.left = (startX - pos.left) + "px";
                        rect.style.width  = (clientX - startX) + "px";
                    }

                    if (startY > clientY) {
                        rect.style.top  = (clientY - pos.top) + "px";
                        rect.style.height = (startY - clientY) + "px";
                    }
                    else {
                        rect.style.top  = (startY - pos.top) + "px";
                        rect.style.height = (clientY - startY) + "px";
                    }

                    var zoomLevel = zoom.value / 100;
                    rectinfo.setAttribute("caption",
                        "L: " + ((rect.offsetLeft - cnvs.offsetLeft) / zoomLevel) + "px, "
                        + "T: " + ((rect.offsetTop - cnvs.offsetTop) / zoomLevel) + "px, "
                        + "W: " + (rect.offsetWidth / zoomLevel) + "px, "
                        + "H: " + (rect.offsetHeight / zoomLevel) + "px");

                }, function() {
                    if (moved) {
                        activeDocument.getSession().rect = {
                            left   : rect.style.left,
                            top    : rect.style.top,
                            width  : rect.style.width,
                            height : rect.style.height,
                        }
                        crop.enable();
                    }
                    else {
                        clearRect();
                    }
                });

                event.stopEvent(e);
            }

            function exec(action, options){
                var cnvs = canvas();
                var url  = cnvs.toDataURL();

                if (action == "crop") {
                    var zoomLevel = zoom.value / 100;

                    options = {
                        left   : (rect.offsetLeft - cnvs.offsetLeft) / zoomLevel,
                        top    : (rect.offsetTop - cnvs.offsetTop) / zoomLevel,
                        width  : (rect.offsetWidth) / zoomLevel,
                        height : (rect.offsetHeight) / zoomLevel
                    }
                }

                Pixastic.process(cnvs, action, options);
                clearRect();

                //@todo
                var doc = activeDocument;
                doc.undoManager.add(new UndoItem(url, canvas().toDataURL(), function(url){
                    loadedFiles[doc.tab.path] = url;
                    loadCanvas(doc.tab);
                }));
            }

            function clearRect(){
                rect.style.display = "none";
                delete activeDocument.getSession().rect;
                crop.disable();
            }

            plugin.on("documentLoad", function(e){
                var doc     = e.doc;
                var session = doc.getSession();

                doc.tab.on("setPath", function(e){
                    setPath(e.path, doc);
                }, session);

                // Value Retrieval
                // doc.on("getValue", function get(e){
                //     return session.session
                //         ? session.session.getValue()
                //         : e.value;
                // }, session);

                // Value setting
                doc.on("setValue", function set(e){
                    var path = doc.tab.path;

                    // The first value that is set should clear the undo stack
                    // additional times setting the value should keep it.
                    if (doc.hasValue()) {
                        var lastValue = loadedFiles[path];
                        delete loadedFiles[path];

                        // @todo this will go wrong and will be fixed when keeping canvas per session
                        setPath(path, doc, function(newValue){
                            doc.undoManager.add(new UndoItem(lastValue, canvas().toDataURL(), function(url){
                                loadedFiles[path] = url;
                                loadCanvas(doc.tab);
                            }));
                        });
                    }
                    else {
                        setPath(path, doc);
                    }

                    // doc.tab.className.remove("loading");
                }, session);

                // Changed marker
                function setChanged(e){
                    if (e.changed || doc.meta.newfile)
                        doc.tab.className.add("changed");
                    else
                        doc.tab.className.remove("changed");
                }
                doc.on("changed", setChanged, session);
                setChanged({ changed: doc.changed });

                doc.tab.backgroundColor = BGCOLOR;
                doc.tab.className.add("dark");

                canvas().style.display = "none";
            });

            plugin.on("documentActivate", function(e){
                var doc     = e.doc;
                var session = doc.getSession();
                var path    = doc.tab.path;

                activeDocument = doc;

                // Set Image
                setPath(path, doc);

                // Set Toolbar
                zoom.setValue(session.zoom || 100);
                zoom.dispatchEvent("afterchange");

                // Set Rect
                if (session.rect) {
                    rect.style.display = "block";
                    rect.style.left   = session.rect.left;
                    rect.style.top    = session.rect.top;
                    rect.style.width  = session.rect.width;
                    rect.style.height = session.rect.height;
                }
                else {
                    rect.style.display = "none";
                }
            });

            plugin.on("documentUnload", function(e){
                delete loadedFiles[e.doc.tab.path];
            });

            /***** Register and define API *****/

            /**
             * The imgeditor handle, responsible for events that involve all
             * ImageEditor instances. This is the object you get when you request
             * the imgeditor service in your plugin.
             *
             * Example:
             *
             *     define(function(require, exports, module) {
             *         main.consumes = ["imgeditor"];
             *         main.provides = ["myplugin"];
             *         return main;
             *
             *         function main(options, imports, register) {
             *             var imgeditorHandle = imports.imgeditor;
             *         });
             *     });
             *
             *
             * @class imgeditor
             * @extends Plugin
             * @singleton
             */
            /**
             * Read Only Image Viewer for Cloud9 IDE
             *
             * Example of instantiating a new terminal:
             *
             *     tabManager.openFile("/test.png", true, function(err, tab){
             *         if (err) throw err;
             *
             *         var imgeditor = tab.editor;
             *     });
             *
             * @class imgeditor.ImageEditor
             * @extends Editor
             **/
            /**
             * The type of editor. Use this to create the terminal using
             * {@link tabManager#openEditor} or {@link editors#createEditor}.
             * @property {"imgeditor"} type
             * @readonly
             */
            plugin.freezePublicAPI({
                autoload: false
            });

            plugin.load("imgeditor" + counter++);

            return plugin;
        }
        ImageEditor.autoload = false;

        register(null, {
            imgeditor: handle
        });
    }
});<|endoftext|>