<commit_before>/*jslint node: true, vars: true, indent: 4 */
'use strict';

var util = require('util'),
    Imap = require('imap'),
    MailParser = require('mailparser').MailParser,
    EventEmitter = require('events').EventEmitter;

function Notifier(opts) {
    EventEmitter.call(this);
    var self = this;
    self.options = opts;
    if (self.options.username) { //backward compat
        self.options.user = self.options.username;
    }
    self.hideLogs = (self.options.hideLogs) ? true : false;
    self.connected = false;
    self.imap = new Imap(opts);
    self.imap.on('end', function () {
        self.connected = false;
        self.emit('end');
    });
    self.imap.on('error', function (err) {
        self.emit('error', err);
    });
}
util.inherits(Notifier, EventEmitter);

module.exports = function (opts) {
    return new Notifier(opts);
};

Notifier.prototype.start = function () {
    var self = this;
    self.imap.once('ready', function () {
        self.connected = true;
        self.imap.openBox(self.options.box || 'INBOX', false, function () {
            self.scan();
            self.imap.on('mail', function (id) {
                self.scan();
            });
        });
    });
    self.imap.connect();
    return this;
};

Notifier.prototype.scan = function () {
    var self = this;
    self.imap.search(self.options.search || ['UNSEEN'], function (err, seachResults) {
        if (err) {
            self.emit('error', err);
        }
        if (!seachResults || seachResults.length === 0) {
            if(!self.options.hideLogs) {
                util.log('no new mail in INBOX');
            }
            return;
        }
        var fetch = self.imap.fetch(seachResults, {
            markSeen: self.options.markSeen !== false,
            bodies: ''
        });
        fetch.on('message', function (msg) {
            var mp = new MailParser();
            mp.once('end', function (mail) {
                self.emit('mail', mail);
            });
            msg.once('body', function (stream, info) {
                stream.pipe(mp);
            });
        });
        fetch.once('end', function () {
            if(!self.options.hideLogs) {
                util.log('Done fetching all messages!');
            }
        });
        fetch.on('error', function () {
            self.emit('error', err);
        });
    });
    return this;
};

Notifier.prototype.stop = function () {
    if (this.connected) {
        this.imap.end();
    }
    return this;
};
<commit_msg>Print correct inbox name<commit_after>/*jslint node: true, vars: true, indent: 4 */
'use strict';

var util = require('util'),
    Imap = require('imap'),
    MailParser = require('mailparser').MailParser,
    EventEmitter = require('events').EventEmitter;

function Notifier(opts) {
    EventEmitter.call(this);
    var self = this;
    self.options = opts;
    if (self.options.username) { //backward compat
        self.options.user = self.options.username;
    }
    self.hideLogs = (self.options.hideLogs) ? true : false;
    self.connected = false;
    self.imap = new Imap(opts);
    self.imap.on('end', function () {
        self.connected = false;
        self.emit('end');
    });
    self.imap.on('error', function (err) {
        self.emit('error', err);
    });
}
util.inherits(Notifier, EventEmitter);

module.exports = function (opts) {
    return new Notifier(opts);
};

Notifier.prototype.start = function () {
    var self = this;
    self.imap.once('ready', function () {
        self.connected = true;
        self.options.box = self.options.box || 'INBOX'
        self.imap.openBox(self.options.box, false, function () {
            self.scan();
            self.imap.on('mail', function (id) {
                self.scan();
            });
        });
    });
    self.imap.connect();
    return this;
};

Notifier.prototype.scan = function () {
    var self = this;
    self.imap.search(self.options.search || ['UNSEEN'], function (err, seachResults) {
        if (err) {
            self.emit('error', err);
        }
        if (!seachResults || seachResults.length === 0) {
            if(!self.options.hideLogs) {
                util.log('no new mail in ' + self.options.box);
            }
            return;
        }
        var fetch = self.imap.fetch(seachResults, {
            markSeen: self.options.markSeen !== false,
            bodies: ''
        });
        fetch.on('message', function (msg) {
            var mp = new MailParser();
            mp.once('end', function (mail) {
                self.emit('mail', mail);
            });
            msg.once('body', function (stream, info) {
                stream.pipe(mp);
            });
        });
        fetch.once('end', function () {
            if(!self.options.hideLogs) {
                util.log('Done fetching all messages!');
            }
        });
        fetch.on('error', function () {
            self.emit('error', err);
        });
    });
    return this;
};

Notifier.prototype.stop = function () {
    if (this.connected) {
        this.imap.end();
    }
    return this;
};
<|endoftext|>


<commit_before>/**
 *
 */

(function(){

	//Simple webserver

	var fs=require('fs');
	var http=require('http');
	var async=require('async');
	var port=80;
	var documentRoot='./html/';

	var server=http.createServer(function(req, res) {

		var file=req.url.split('/').pop();
		if(file===''){
			file='index.html';
		}
		if(file.indexOf('.')>=0){

			fs.exists(documentRoot+file, function(exists){

				if(exists){
					var contentTypes={
						js:'text/javascript',
						css:'text/css',
						html:'text/html'
					};

					var type=file.split('.').pop();
					res.writeHead(200, {
						'Content-Type': contentTypes[type]
					});

					fs.readFile(documentRoot+file, function (err, data) {
						res.write(data);
						res.end();
					});

				}else{

					res.writeHead(404);
					res.end('File not found: '+file);

				}

			});
		}else{

			res.writeHead(500);
			res.end('resuest: '+file);

		}

	});

	server.listen(port);
	console.log('webserver listening on: '+port);

})();

var devices=[{
		name:'GPI Pin 7',
		pin:7,
		direction:'out',
		type:'bool',
		state:false
}];

var gpio = require('rpi-gpio');
devices.forEach(function(dconf){

	var direction=dconf.direction==='in'?gpio.DIR_IN:gpio.DIR_OUT;

	gpio.setup(dconf.pin, direction, function(err){

		 gpio.read(dconf.pin, function(err, value) {
		        console.log('The value is ' + value);
		        dconf.state=value?true:false;
		 });

	});

});

(function(){

	// Simple websocket server

	var port = 8080;
	var clients = [];

	(new (require('ws').Server)({
		port: port
	})).on('connection', function(wsclient){

		clients.push(wsclient);

		wsclient.on('message',function(data){

			var request=JSON.parse(data);
			console.log([data, request]);
			var id=request.id;
			var tast=request.task;
			var arguments=request.json;

			if(task=='list_devices'){
				wsclient.send(id+':'+JSON.stringify(devices));
			}

		}).on('close',function(code, message){
			var i = clients.indexOf(wsclient);
			console.log('ws:'+i+' client closed: '+code+' '+message);
			clients.splice(i, 1);
		});

	}).on('error', function(error){

		console.log('error: '+error);

	});

	console.log('websocket listening on: '+port);

})();

<commit_msg>!task!<commit_after>/**
 *
 */

(function(){

	//Simple webserver

	var fs=require('fs');
	var http=require('http');
	var async=require('async');
	var port=80;
	var documentRoot='./html/';

	var server=http.createServer(function(req, res) {

		var file=req.url.split('/').pop();
		if(file===''){
			file='index.html';
		}
		if(file.indexOf('.')>=0){

			fs.exists(documentRoot+file, function(exists){

				if(exists){
					var contentTypes={
						js:'text/javascript',
						css:'text/css',
						html:'text/html'
					};

					var type=file.split('.').pop();
					res.writeHead(200, {
						'Content-Type': contentTypes[type]
					});

					fs.readFile(documentRoot+file, function (err, data) {
						res.write(data);
						res.end();
					});

				}else{

					res.writeHead(404);
					res.end('File not found: '+file);

				}

			});
		}else{

			res.writeHead(500);
			res.end('resuest: '+file);

		}

	});

	server.listen(port);
	console.log('webserver listening on: '+port);

})();

var devices=[{
		name:'GPI Pin 7',
		pin:7,
		direction:'out',
		type:'bool',
		state:false
}];

var gpio = require('rpi-gpio');
devices.forEach(function(dconf){

	var direction=dconf.direction==='in'?gpio.DIR_IN:gpio.DIR_OUT;

	gpio.setup(dconf.pin, direction, function(err){

		 gpio.read(dconf.pin, function(err, value) {
		        console.log('The value is ' + value);
		        dconf.state=value?true:false;
		 });

	});

});

(function(){

	// Simple websocket server

	var port = 8080;
	var clients = [];

	(new (require('ws').Server)({
		port: port
	})).on('connection', function(wsclient){

		clients.push(wsclient);

		wsclient.on('message',function(data){

			var request=JSON.parse(data);
			console.log([data, request]);
			var id=request.id;
			var task=request.task;
			var arguments=request.json;

			if(task=='list_devices'){
				wsclient.send(id+':'+JSON.stringify(devices));
			}

		}).on('close',function(code, message){
			var i = clients.indexOf(wsclient);
			console.log('ws:'+i+' client closed: '+code+' '+message);
			clients.splice(i, 1);
		});

	}).on('error', function(error){

		console.log('error: '+error);

	});

	console.log('websocket listening on: '+port);

})();

<|endoftext|>


<commit_before>var findZeroRange = require('find-zero-range');

function walrasianCEPriceRange(pLow,pHigh,pTol,qDemand,qSupply){
    'use strict';
    var excessSupply = function(p){ return (qSupply(p)-qDemand(p)); };
    var priceRange = findZeroRange(pLow, pHigh, pTol, excessSupply);
    // correction for integer prices and quantities when a supply order is needed for CE
    if ((priceRange.length===1) &&
	(pTol===1) &&
	(excessSupply(priceRange[0])<0) &&
	(qSupply(priceRange[0])<qSupply(priceRange[0]+1)))
	return [priceRange[0]+1];
    return priceRange;
}

module.exports.walrasianCEPriceRange = walrasianCEPriceRange;

function demandFromQueue(buyQueue,bpCol,qCol){
    return function(p){
	'use strict';
	var i=0,l=buyQueue.length,totalQ=0;
	while ((i<l) && (p<=buyQueue[i][bpCol])){
	    totalQ += buyQueue[i][qCol];
	    ++i;
	}
	return totalQ;
    };
}

module.exports.demandFromQueue = demandFromQueue;

function supplyFromQueue(sellQueue,spCol,qCol){
    return function(p){
	'use strict';
	var i=0,l=sellQueue.length,totalQ=0;
	while ((i<l) && (p>=sellQueue[i][spCol])){
	    totalQ += sellQueue[i][qCol];
	    ++i;
	}
	return totalQ;
    };
}

module.exports.supplyFromQueue = supplyFromQueue;

function marshallianCEPriceRange(inframarginalBuyPrice,
				 inframarginalSellPrice,
				 extramarginalBuyPrice,
				 extramarginalSellPrice){
    'use strict';
    if (extramarginalBuyPrice > inframarginalBuyPrice) throw   "marketPricing.marshallianCEPriceRange: invalid buy prices, extramarginal price must not be greater than inframarginal price";
    if (extramarginalSellPrice < inframarginalSellPrice) throw "marketPricing.marshallianCEPriceRange: invalid sell prices, extramarginal price must not be less than inframarginal price";
    if (extramarginalBuyPrice >= extramarginalSellPrice) throw "marketPricing.marshallianCEPriceRange: invalid extramarginal prices, extramarginal buy price should not equal or exceed extramarginal sell price";
    var cePriceRange = [
	(Math.max(extramarginalBuyPrice, inframarginalSellPrice) || inframarginalSellPrice),
	(Math.min(extramarginalSellPrice, inframarginalBuyPrice) || inframarginalBuyPrice)
    ];
    return cePriceRange;
}

module.exports.marshallianCEPriceRange = marshallianCEPriceRange;

function cross(buyQueue,sellQueue,bpCol,bqCol,spCol,sqCol){
    'use strict';
    if ((bpCol===undefined) ||
	(bqCol===undefined) ||
	(spCol===undefined) ||
	(sqCol===undefined))
	throw "marketPricing.cross: missing 1 or more col parameters: "+([bpCol,bqCol,spCol,sqCol].join(","));
    var bidx=0,sidx=0,bl=buyQueue.length,sl=sellQueue.length;
    if ((!bl) || (!sl)) return undefined;
    var buyQ=[],sellQ=[],deltaQ=0,totalQ=0;
    var ibp,isp,ebp=buyQueue[0][bpCol],esp=sellQueue[0][spCol];
    if (ebp>=esp){
	buyQ[0]=0;
	sellQ[0]=0;
    }
    while ((ebp >= esp) &&
	   (bidx < bl) &&
	   (sidx < sl)){
	deltaQ = Math.min(buyQueue[bidx][bqCol]-buyQ[bidx],sellQueue[sidx][sqCol]-sellQ[sidx]);
	totalQ += deltaQ;
	// increment or initialize quantity bought/sold by deltaQ
	buyQ[bidx] += deltaQ;
	sellQ[sidx] += deltaQ;
	ibp = ebp;
	isp = esp;
	if (buyQueue[bidx][bqCol]===buyQ[bidx]){
	    bidx++;
	    buyQ[bidx]=0;
	    ebp = (bidx<bl)? (buyQueue[bidx][bpCol]) : undefined;
	}
	if (sellQueue[sidx][sqCol]===sellQ[sidx]){
	    sidx++;
	    sellQ[sidx]=0;
	    esp = (sidx<sl)? (sellQueue[sidx][spCol]) : undefined;
	}
    }
    if (totalQ===0) return undefined;
    var priceRange = marshallianCEPriceRange(ibp,isp,ebp,esp);
    var price = (priceRange[0]+priceRange[1])/2;
    if (buyQ[bidx]===0) buyQ.pop();
    if (sellQ[sidx]===0) sellQ.pop();
    return [price,totalQ,buyQ,sellQ];
}

module.exports.cross = cross;

function sequential(buyQueue,sellQueue,tCol,bpCol,bqCol,spCol,sqCol){
    'use strict';
    if ((tCol===undefined) ||
	(bpCol===undefined) ||
	(bqCol===undefined) ||
	(spCol===undefined) ||
	(sqCol===undefined))
	throw "marketPricing.cross: missing 1 or more col parameters: "+([tCol,bpCol,bqCol,spCol,sqCol].join(","));
    var totalQ,prices,buyQ,sellQ,i,l,op;
    if ((!buyQueue.length) ||
	(!sellQueue.length) ||
        (buyQueue[0][bpCol]<sellQueue[0][spCol])) return undefined;
    var crossResult = cross(buyQueue,sellQueue,bpCol,bqCol,spCol,sqCol);
    if (crossResult===undefined) return undefined;
    totalQ = crossResult[1];
    buyQ   = crossResult[2];
    sellQ  = crossResult[3];
    prices = [];
    if (buyQueue[0][tCol]<sellQueue[0][tCol]){
	op = 's';
	if (sellQ[1]) throw "marketPricing.sequential: non-sequential trades on sell side";
	for(i=0,l=buyQ.length;i<l;++i)
	    prices[i] = buyQueue[i][bpCol];
    } else {
	op = 'b';
	if (buyQ[1]) throw "marketPricing.sequential: non-sequential trades on buy side";
	for(i=0,l=sellQ.length;i<l;++i)
	    prices[i] = sellQueue[i][spCol];
    }
    return [op, prices, totalQ, buyQ, sellQ];
}

module.exports.sequential = sequential;
<commit_msg>convert throw "some string" to throw new Error("some string");<commit_after>var findZeroRange = require('find-zero-range');

function walrasianCEPriceRange(pLow,pHigh,pTol,qDemand,qSupply){
    'use strict';
    var excessSupply = function(p){ return (qSupply(p)-qDemand(p)); };
    var priceRange = findZeroRange(pLow, pHigh, pTol, excessSupply);
    // correction for integer prices and quantities when a supply order is needed for CE
    if ((priceRange.length===1) &&
	(pTol===1) &&
	(excessSupply(priceRange[0])<0) &&
	(qSupply(priceRange[0])<qSupply(priceRange[0]+1)))
	return [priceRange[0]+1];
    return priceRange;
}

module.exports.walrasianCEPriceRange = walrasianCEPriceRange;

function demandFromQueue(buyQueue,bpCol,qCol){
    return function(p){
	'use strict';
	var i=0,l=buyQueue.length,totalQ=0;
	while ((i<l) && (p<=buyQueue[i][bpCol])){
	    totalQ += buyQueue[i][qCol];
	    ++i;
	}
	return totalQ;
    };
}

module.exports.demandFromQueue = demandFromQueue;

function supplyFromQueue(sellQueue,spCol,qCol){
    return function(p){
	'use strict';
	var i=0,l=sellQueue.length,totalQ=0;
	while ((i<l) && (p>=sellQueue[i][spCol])){
	    totalQ += sellQueue[i][qCol];
	    ++i;
	}
	return totalQ;
    };
}

module.exports.supplyFromQueue = supplyFromQueue;

function marshallianCEPriceRange(inframarginalBuyPrice,
				 inframarginalSellPrice,
				 extramarginalBuyPrice,
				 extramarginalSellPrice){
    'use strict';
    if (extramarginalBuyPrice > inframarginalBuyPrice)
	throw new Error("marketPricing.marshallianCEPriceRange: invalid buy prices, extramarginal price must not be greater than inframarginal price");
    if (extramarginalSellPrice < inframarginalSellPrice)
	throw new Error("marketPricing.marshallianCEPriceRange: invalid sell prices, extramarginal price must not be less than inframarginal price");
    if (extramarginalBuyPrice >= extramarginalSellPrice)
	throw new Error("marketPricing.marshallianCEPriceRange: invalid extramarginal prices, extramarginal buy price should not equal or exceed extramarginal sell price");
    var cePriceRange = [
	(Math.max(extramarginalBuyPrice, inframarginalSellPrice) || inframarginalSellPrice),
	(Math.min(extramarginalSellPrice, inframarginalBuyPrice) || inframarginalBuyPrice)
    ];
    return cePriceRange;
}

module.exports.marshallianCEPriceRange = marshallianCEPriceRange;

function cross(buyQueue,sellQueue,bpCol,bqCol,spCol,sqCol){
    'use strict';
    if ((bpCol===undefined) ||
	(bqCol===undefined) ||
	(spCol===undefined) ||
	(sqCol===undefined))
	throw new Error("marketPricing.cross: missing 1 or more col parameters: "+([bpCol,bqCol,spCol,sqCol].join(",")));
    var bidx=0,sidx=0,bl=buyQueue.length,sl=sellQueue.length;
    if ((!bl) || (!sl)) return undefined;
    var buyQ=[],sellQ=[],deltaQ=0,totalQ=0;
    var ibp,isp,ebp=buyQueue[0][bpCol],esp=sellQueue[0][spCol];
    if (ebp>=esp){
	buyQ[0]=0;
	sellQ[0]=0;
    }
    while ((ebp >= esp) &&
	   (bidx < bl) &&
	   (sidx < sl)){
	deltaQ = Math.min(buyQueue[bidx][bqCol]-buyQ[bidx],sellQueue[sidx][sqCol]-sellQ[sidx]);
	totalQ += deltaQ;
	// increment or initialize quantity bought/sold by deltaQ
	buyQ[bidx] += deltaQ;
	sellQ[sidx] += deltaQ;
	ibp = ebp;
	isp = esp;
	if (buyQueue[bidx][bqCol]===buyQ[bidx]){
	    bidx++;
	    buyQ[bidx]=0;
	    ebp = (bidx<bl)? (buyQueue[bidx][bpCol]) : undefined;
	}
	if (sellQueue[sidx][sqCol]===sellQ[sidx]){
	    sidx++;
	    sellQ[sidx]=0;
	    esp = (sidx<sl)? (sellQueue[sidx][spCol]) : undefined;
	}
    }
    if (totalQ===0) return undefined;
    var priceRange = marshallianCEPriceRange(ibp,isp,ebp,esp);
    var price = (priceRange[0]+priceRange[1])/2;
    if (buyQ[bidx]===0) buyQ.pop();
    if (sellQ[sidx]===0) sellQ.pop();
    return [price,totalQ,buyQ,sellQ];
}

module.exports.cross = cross;

function sequential(buyQueue,sellQueue,tCol,bpCol,bqCol,spCol,sqCol){
    'use strict';
    if ((tCol===undefined) ||
	(bpCol===undefined) ||
	(bqCol===undefined) ||
	(spCol===undefined) ||
	(sqCol===undefined))
	throw new Error("marketPricing.cross: missing 1 or more col parameters: "+([tCol,bpCol,bqCol,spCol,sqCol].join(",")));
    var totalQ,prices,buyQ,sellQ,i,l,op;
    if ((!buyQueue.length) ||
	(!sellQueue.length) ||
        (buyQueue[0][bpCol]<sellQueue[0][spCol])) return undefined;
    var crossResult = cross(buyQueue,sellQueue,bpCol,bqCol,spCol,sqCol);
    if (crossResult===undefined) return undefined;
    totalQ = crossResult[1];
    buyQ   = crossResult[2];
    sellQ  = crossResult[3];
    prices = [];
    if (buyQueue[0][tCol]<sellQueue[0][tCol]){
	op = 's';
	if (sellQ[1]) throw new Error("marketPricing.sequential: non-sequential trades on sell side");
	for(i=0,l=buyQ.length;i<l;++i)
	    prices[i] = buyQueue[i][bpCol];
    } else {
	op = 'b';
	if (buyQ[1]) throw new Error("marketPricing.sequential: non-sequential trades on buy side");
	for(i=0,l=sellQ.length;i<l;++i)
	    prices[i] = sellQueue[i][spCol];
    }
    return [op, prices, totalQ, buyQ, sellQ];
}

module.exports.sequential = sequential;
<|endoftext|>


<commit_before>'use strict';

var facebook = require("./lib/services/facebook.service.js");
var facebook = require("./lib/services/github.service.js");

module.exports = {
    facebook: facebook,
    github: github
};

// facebook(function(res) {
//         console.log(res);
// });
<commit_msg>iAmAnIdiot<commit_after>'use strict';

var facebook = require("./lib/services/facebook.service.js");
var github = require("./lib/services/github.service.js");

module.exports = {
    facebook: facebook,
    github: github
};
<|endoftext|>


<commit_before>var atan2 = Math.atan2
var cos = Math.cos
var sin = Math.sin
var sqrt = Math.sqrt
var PI = Math.PI

 // (mean) radius of Earth (meters)
var R = 6378137

function squared (x) { return x * x }
function toRad (x) { return x * PI / 180.0 }

// https://stackoverflow.com/questions/1502590/calculate-distance-between-two-points-in-google-maps-v3
module.exports = function haversineDistance (a, b) {
  var aLat = a.latitude || a.lat
  var bLat = b.latitude || b.lat
  var aLng = a.longitude || a.lng || a.lon
  var bLng = b.longitude || b.lng || b.lon

  var dLat = toRad(bLat - aLat)
  var dLon = toRad(bLng - aLng)

  var f = squared(sin(dLat / 2.0)) + cos(toRad(aLat)) * cos(toRad(bLat)) * squared(sin(dLon / 2.0))
  var c = 2 * atan2(sqrt(f), sqrt(1 - f))

  return R * c
}
<commit_msg>add missing references<commit_after>// Reference material(s)
// - https://en.wikipedia.org/wiki/Haversine_formula
// - https://stackoverflow.com/questions/27928/calculate-distance-between-two-latitude-longitude-points-haversine-formula
// - https://stackoverflow.com/questions/1502590/calculate-distance-between-two-points-in-google-maps-v3

var atan2 = Math.atan2
var cos = Math.cos
var sin = Math.sin
var sqrt = Math.sqrt
var PI = Math.PI

 // (mean) radius of Earth (meters)
var R = 6378137

function squared (x) { return x * x }
function toRad (x) { return x * PI / 180.0 }

module.exports = function haversineDistance (a, b) {
  var aLat = a.latitude || a.lat
  var bLat = b.latitude || b.lat
  var aLng = a.longitude || a.lng || a.lon
  var bLng = b.longitude || b.lng || b.lon

  var dLat = toRad(bLat - aLat)
  var dLon = toRad(bLng - aLng)

  var f = squared(sin(dLat / 2.0)) + cos(toRad(aLat)) * cos(toRad(bLat)) * squared(sin(dLon / 2.0))
  var c = 2 * atan2(sqrt(f), sqrt(1 - f))

  return R * c
}
<|endoftext|>


<commit_before>'use strict';

function injectDefaultOptions(options) {
  options = options || {};
  options.prefix = options.prefix || '#{';
  options.suffix = options.suffix || '}';
  options.configFile = options.configFile || process.cwd() + '/config.json';
  options.preserveUnknownTokens = options.preserveUnknownTokens || false;
  options.delimiter = options.delimiter || '.';

  if (options.configFile) {
    try {
      options.tokens = require(options.configFile);
    } catch (e) { }
  }
  options.tokens = options.tokens || options.global || {};

  return options;
}

function escapeRegExp(text) {
  return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
}

function getTokenValue(tokens, tokenName, delimiter) {
  var tmpTokens = tokens;
  if (tokens.hasOwnProperty(tokenName)) {
    return tokens[tokenName];
  }

  var tokenNameParts = tokenName.split(delimiter);
  for (var i = 0; i < tokenNameParts.length; i++) {
    if (tmpTokens.hasOwnProperty(tokenNameParts[i])) {
      tmpTokens = tmpTokens[tokenNameParts[i]];
    } else {
      return null;
    }
  }
  return tmpTokens;
}

function replace(target, options) {
  options = injectDefaultOptions(options);

  var includeRegExp = new RegExp(escapeRegExp(options.prefix) + '(.+?)' + escapeRegExp(options.suffix), 'g');
  var text, isObject = false;
  if (typeof target === 'object') {
    text = JSON.stringify(target);
    isObject = true;
  } else if ( typeof target === 'string') {
     text = target;
  } else {
    text = target.toString();
  }

  var retVal = text;
  var regExpResult;
  while (regExpResult = includeRegExp.exec(text)) {
    var fullMatch = regExpResult[0];
    var tokenName = regExpResult[1];
    var tokenValue = getTokenValue(options.tokens, tokenName, options.delimiter);
    if (tokenValue === null && !options.preserveUnknownTokens) {
      tokenValue = '';
    }
    if (tokenValue !== null) {
      if (typeof tokenValue == 'object') {
        tokenValue = JSON.stringify(tokenValue);
      }
      retVal = retVal.replace(fullMatch, tokenValue);
    }
  }
  return isObject ? JSON.parse(retVal) : retVal;
};

module.exports = replace;
<commit_msg>Fixed no-extra-semi error<commit_after>'use strict';

function injectDefaultOptions(options) {
  options = options || {};
  options.prefix = options.prefix || '#{';
  options.suffix = options.suffix || '}';
  options.configFile = options.configFile || process.cwd() + '/config.json';
  options.preserveUnknownTokens = options.preserveUnknownTokens || false;
  options.delimiter = options.delimiter || '.';

  if (options.configFile) {
    try {
      options.tokens = require(options.configFile);
    } catch (e) { }
  }
  options.tokens = options.tokens || options.global || {};

  return options;
}

function escapeRegExp(text) {
  return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
}

function getTokenValue(tokens, tokenName, delimiter) {
  var tmpTokens = tokens;
  if (tokens.hasOwnProperty(tokenName)) {
    return tokens[tokenName];
  }

  var tokenNameParts = tokenName.split(delimiter);
  for (var i = 0; i < tokenNameParts.length; i++) {
    if (tmpTokens.hasOwnProperty(tokenNameParts[i])) {
      tmpTokens = tmpTokens[tokenNameParts[i]];
    } else {
      return null;
    }
  }
  return tmpTokens;
}

function replace(target, options) {
  options = injectDefaultOptions(options);

  var includeRegExp = new RegExp(escapeRegExp(options.prefix) + '(.+?)' + escapeRegExp(options.suffix), 'g');
  var text, isObject = false;
  if (typeof target === 'object') {
    text = JSON.stringify(target);
    isObject = true;
  } else if ( typeof target === 'string') {
     text = target;
  } else {
    text = target.toString();
  }

  var retVal = text;
  var regExpResult;
  while (regExpResult = includeRegExp.exec(text)) {
    var fullMatch = regExpResult[0];
    var tokenName = regExpResult[1];
    var tokenValue = getTokenValue(options.tokens, tokenName, options.delimiter);
    if (tokenValue === null && !options.preserveUnknownTokens) {
      tokenValue = '';
    }
    if (tokenValue !== null) {
      if (typeof tokenValue == 'object') {
        tokenValue = JSON.stringify(tokenValue);
      }
      retVal = retVal.replace(fullMatch, tokenValue);
    }
  }
  return isObject ? JSON.parse(retVal) : retVal;
}

module.exports = replace;
<|endoftext|>


<commit_before>#!/usr/bin/env node

"use strict";

var fs      = require('fs'),
    path    = require('path'),
    util    = require('util'),
    exec    = require('child_process').exec,

    dates   = require('./lib/dates'),
    parser  = require('./lib/parser'),

    isGitRepo = fs.existsSync(process.cwd() + '/.git');

console.log(isGitRepo, dates);

if (isGitRepo) {
    // git log this repo
    exec('git log --after=' + dates.after + ' --before=' + dates.before, parser.format);
} else {
    // start to recursively go through all sub dirrectories looking for .git
    console.log('yolo');
}
<commit_msg>Changed some more stuff - testing config<commit_after>#!/usr/bin/env node

"use strict";

var fs      = require('fs'),
    path    = require('path'),
    util    = require('util'),
    exec    = require('child_process').exec,

    dates   = require('./lib/dates'),
    parser  = require('./lib/parser'),

    isGitRepo = fs.existsSync(process.cwd() + '/.git');

console.log(isGitRepo, dates);

if (isGitRepo) {
    // git log this repo
    exec('git log --after=' + dates.after + ' --before=' + dates.before, parser.format);
} else {
    // start to recursively go through all sub dirrectories looking for .git
    console.log('yolo');

}
<|endoftext|>


<commit_before>'use strict';

const colorJS = require('color');

exports.decorateConfig = config => {
  const materialBox = Object.assign(
      {
        scheme: 'solarized dark',
        backgroundOpacity: 1,
        backgroundVibrancy: false,
        closeOnTheLeft: false,
      },
      config.materialBox);

  materialBox.user = Object.assign(
      {
        colors: config.colors,
        backgroundColor: config.backgroundColor,
        foregroundColor: config.foregroundColor,
        borderColor: config.borderColor,
        cursorColor: config.cursorColor,
        accentColor: config.colors.blue,
        inactiveTabTitleColor: config.inactiveTabTitleColor ||
            colorJS(config.foregroundColor).alpha(0.3).string(),
        activeTabTitleColor:
            config.activeTabTitleColor || config.foregroundColor,
      },
      (config.materialBox ? config.materialBox.user : {}));

  // Get scheme
  const schemeIndex = {
    'user': materialBox.user,
    'solarized dark': require('./scheme/solarized_dark.js'),
    'solarized light': require('./scheme/solarized_light.js'),
  };
  const scheme = Object.assign(
      schemeIndex[materialBox.scheme] || schemeIndex['solarized dark'],
      config.materialBox.user);

  // Background opacity
  scheme.backgroundColor = colorJS(scheme.backgroundColor)
                               .alpha(materialBox.backgroundOpacity)
                               .string();
  // Background vibrancy
  if (materialBox.backgroundVibrancy === true) {
    if (colorJS(scheme.backgroundColor).light() === true) {
      exports.onWindow = browserWindow => browserWindow.setVibrancy('light');
    } else {
      exports.onWindow = browserWindow => browserWindow.setVibrancy('dark');
    }
  }

  return Object.assign({}, config, {
    colors: scheme.colors,
    backgroundColor: scheme.backgroundColor,
    foregroundColor: scheme.foregroundColor,
    borderColor: scheme.borderColor,
    cursorColor: scheme.cursorColor,
    css: `
    .tab_tab {
      border: none;
      color: ${scheme.inactiveTabTitleColor};
    }
    .tab_tab.tab_active {
      color: ${scheme.activeTabTitleColor};
    }
    .tabs_title {
      color: ${scheme.activeTabTitleColor};
    }
    .hyper_main {
      border: none;
    }
    .tabs_borderShim {
      display: none;
    }
    .tab_tab.tab_active::before {
      transform: scaleX(1);
      transition: all 300ms cubic-bezier(0.0, 0.0, 0.2, 1)
    }
    .tab_textInner {
      text-overflow: ellipsis;
      overflow: hidden;
      max-width: 100%;
      padding: 0px 24px 0 8px;
    }
    .tabs_nav .tab_tab .tab_icon {
      left: 5px;
      right: auto;
      top: 4px;
      border-radius: 2px;
    }
    ${
      materialBox.closeOnTheLeft === true ?
          '.tab_tab .tab_icon { left: 7px; right: initial; }' :
          ''
    }
    ${config.css || ''}
    `,
    termCSS: `
    .cursor-node[focus=true]:not([moving]) {
      mix-blend-mode: difference;
    }
    ::-webkit-scrollbar {
      width: 2px;
    }
    ::-webkit-scrollbar-thumb {
      border-radius: 0px;
      background-color: ${scheme.accentColor};
    }
    x-screen x-row { font-variant-ligatures: contextual; }
    ${config.termCSS || ''}
    `,
  });
};
<commit_msg>:bug: Fix a property 'user' undefined bug<commit_after>'use strict';

const colorJS = require('color');

exports.decorateConfig = config => {
  const materialBox = Object.assign(
      {
        scheme: 'solarized dark',
        backgroundOpacity: 1,
        backgroundVibrancy: false,
        closeOnTheLeft: false,
      },
      config.materialBox);

  materialBox.user = Object.assign(
      {
        colors: config.colors,
        backgroundColor: config.backgroundColor,
        foregroundColor: config.foregroundColor,
        borderColor: config.borderColor,
        cursorColor: config.cursorColor,
        accentColor: config.colors.blue,
        inactiveTabTitleColor: config.inactiveTabTitleColor ||
            colorJS(config.foregroundColor).alpha(0.3).string(),
        activeTabTitleColor:
            config.activeTabTitleColor || config.foregroundColor,
      },
      (config.materialBox ? config.materialBox.user : {}));

  // Get scheme
  const schemeIndex = {
    'user': materialBox.user,
    'solarized dark': require('./scheme/solarized_dark.js'),
    'solarized light': require('./scheme/solarized_light.js'),
  };
  const scheme = Object.assign(
      schemeIndex[materialBox.scheme] || schemeIndex['solarized dark'],
      (config.materialBox ? config.materialBox.user : {}));

  // Background opacity
  scheme.backgroundColor = colorJS(scheme.backgroundColor)
                               .alpha(materialBox.backgroundOpacity)
                               .string();
  // Background vibrancy
  if (materialBox.backgroundVibrancy === true) {
    if (colorJS(scheme.backgroundColor).light() === true) {
      exports.onWindow = browserWindow => browserWindow.setVibrancy('light');
    } else {
      exports.onWindow = browserWindow => browserWindow.setVibrancy('dark');
    }
  }

  return Object.assign({}, config, {
    colors: scheme.colors,
    backgroundColor: scheme.backgroundColor,
    foregroundColor: scheme.foregroundColor,
    borderColor: scheme.borderColor,
    cursorColor: scheme.cursorColor,
    css: `
    .tab_tab {
      border: none;
      color: ${scheme.inactiveTabTitleColor};
    }
    .tab_tab.tab_active {
      color: ${scheme.activeTabTitleColor};
    }
    .tabs_title {
      color: ${scheme.activeTabTitleColor};
    }
    .hyper_main {
      border: none;
    }
    .tabs_borderShim {
      display: none;
    }
    .tab_tab.tab_active::before {
      transform: scaleX(1);
      transition: all 300ms cubic-bezier(0.0, 0.0, 0.2, 1)
    }
    .tab_textInner {
      text-overflow: ellipsis;
      overflow: hidden;
      max-width: 100%;
      padding: 0px 24px 0 8px;
    }
    .tabs_nav .tab_tab .tab_icon {
      left: 5px;
      right: auto;
      top: 4px;
      border-radius: 2px;
    }
    ${
      materialBox.closeOnTheLeft === true ?
          '.tab_tab .tab_icon { left: 7px; right: initial; }' :
          ''
    }
    ${config.css || ''}
    `,
    termCSS: `
    .cursor-node[focus=true]:not([moving]) {
      mix-blend-mode: difference;
    }
    ::-webkit-scrollbar {
      width: 2px;
    }
    ::-webkit-scrollbar-thumb {
      border-radius: 0px;
      background-color: ${scheme.accentColor};
    }
    x-screen x-row { font-variant-ligatures: contextual; }
    ${config.termCSS || ''}
    `,
  });
};
<|endoftext|>


<commit_before>/*
 * Copyright 2015 Hippo B.V. (http://www.onehippo.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var autoprefixer = require('gulp-autoprefixer');
var browserSync = require('browser-sync');
var buildConfig = require('./build.conf.js');
var Builder = require('systemjs-builder');
var concat = require('gulp-concat');
var debounce = require('debounce');
var debug = require('gulp-debug');
var del = require('del');
var esLint = require('gulp-eslint');
var gulpif = require('gulp-if');
var imagemin = require('gulp-imagemin');
var insert = require('gulp-insert');
var karma = require('karma');
var minifyCss = require('gulp-minify-css');
var minifyHtml = require('gulp-minify-html');
var ngAnnotate = require('gulp-ng-annotate');
var path = require('path');
var plumber = require('gulp-plumber');
var rev = require('gulp-rev');
var sass = require('gulp-sass');
var sassLint = require('gulp-sass-lint');
var sourceMaps = require('gulp-sourcemaps');
var templateCache = require('gulp-angular-templatecache');
var uglify = require('gulp-uglify');
var usemin = require('gulp-usemin');

function buildTasks(customConfig, localGulp) {
  var cfg = buildConfig(customConfig);
  var gulp = localGulp || require('gulp');
  var bsServer = browserSync.create();

  function clean() {
    return del([cfg.distDir]);
  }

  function styles() {
    return gulp
      .src(cfg.src.indexStyles)
      .pipe(plumber())
      .pipe(sassLint({
        rules: cfg.sassLintRules
      }))
      .pipe(sassLint.format())
      .pipe(sassLint.failOnError())
      .pipe(sourceMaps.init())
      .pipe(sass({
        outputStyle: 'expanded'
      }))
      .pipe(autoprefixer({
        browsers: cfg.supportedBrowsers
      }))
      .pipe(sourceMaps.write('./'))
      .pipe(gulp.dest(cfg.dist.styles))
      .pipe(bsServer.stream());
  }

  function images() {
    return gulp
      .src(cfg.src.images)
      .pipe(plumber())
      .pipe(imagemin())
      .pipe(gulp.dest(cfg.dist.images))
      .pipe(bsServer.stream());
  }

  function fonts() {
    return gulp
      .src(cfg.src.fonts)
      .pipe(plumber())
      .pipe(gulp.dest(cfg.dist.fonts))
      .pipe(bsServer.stream());
  }

  function bowerAssets() {
    return gulp
      .src(cfg.bowerAssets)
      .pipe(plumber())
      .pipe(gulp.dest(cfg.distDir))
      .pipe(bsServer.stream());
  }

  function symlinkDependencies() {
    return gulp.src([
        path.basename(cfg.bowerDir),
        path.basename(cfg.npmDir)
      ])
      .pipe(gulp.symlink(cfg.distDir));
  }

  function unlinkDependencies() {
    return del([
      cfg.targetBowerDir,
      cfg.targetNpmDir
    ]);
  }

  function scripts(done) {
    gulp.series(
      function lint() {
        return gulp
          .src(cfg.src.scripts)
          .pipe(plumber())
          .pipe(esLint(cfg.esLintConfig))
          .pipe(esLint.format())
          .pipe(esLint.failOnError());
      },
      function transpile() {
        var systemjs = new Builder();
        systemjs.config(cfg.systemjsOptions);
        return systemjs.bundle(cfg.src.indexScript, cfg.dist.indexScript, {
          sourceMaps: true
        });
      },
      function annotate() {
        return gulp
          .src(cfg.dist.indexScript)
          .pipe(plumber())
          .pipe(sourceMaps.init({
            loadMaps: true
          }))
          .pipe(ngAnnotate())
          .pipe(sourceMaps.write('./'))
          .pipe(gulp.dest(cfg.dist.scripts));
      },
      function html2js() {
        return gulp
          .src([
            cfg.src.templates,
            cfg.dist.indexScript
          ])
          .pipe(plumber())
          .pipe(gulpif('*.html', templateCache({
            transformUrl: function(url) {
              return url.replace(/.*angularjs(?:\\|\/)/gi, '');
            },
            module: cfg.projectName + '-templates',
            standalone: true
          })))
          .pipe(concat(cfg.projectName + '.js'))
          .pipe(gulp.dest(cfg.dist.scripts));
      },
      function systemImport() {
        return gulp
          .src(cfg.dist.indexScript)
          .pipe(insert.append('System.import("' + cfg.src.indexScript + '");'))
          .pipe(gulp.dest(cfg.dist.scripts))
          .pipe(bsServer.stream());
      }
    )(done);
  }

  function unitTests(done) {
    gulp.series(
      function lint() {
        return gulp
          .src(cfg.src.unitTests)
          .pipe(plumber())
          .pipe(esLint(cfg.esLintConfig))
          .pipe(esLint.format())
          .pipe(esLint.failOnError());
      },
      function runKarma(karmaDone) {
        var server = new karma.Server({
          configFile: cfg.karmaConfig
        }, karmaDone);

        server.start();
      }
    )(done);
  }

  function unitTestsDebug(done) {
    gulp.series(
      function lint() {
        return gulp
          .src(cfg.src.unitTests)
          .pipe(plumber())
          .pipe(esLint(cfg.esLintConfig))
          .pipe(esLint.format())
          .pipe(esLint.failOnError());
      },
      function runKarma(karmaDone) {
        var server = new karma.Server({
          configFile: cfg.karmaConfig,
          browsers: ['Chrome'],
          singleRun: false,
          autoWatch: true
        }, karmaDone);

        server.start();
      }
    )(done);
  }

  function i18n() {
    return gulp
      .src(cfg.src.i18n)
      .pipe(plumber())
      .pipe(gulp.dest(cfg.dist.i18n));
  }

  function dev() {
    return gulp
      .src(cfg.src.indexHtml)
      .pipe(plumber())
      .pipe(gulp.dest(cfg.distDir))
      .pipe(bsServer.stream());
  }

  function dist() {
    return gulp
      .src(cfg.dist.indexHtml)
      .pipe(usemin({
        html: [
          minifyHtml()
        ],
        css: [
          sourceMaps.init(),
          minifyCss(),
          rev(),
          sourceMaps.write('./')
        ],
        js: [
          sourceMaps.init(),
          uglify(),
          rev(),
          sourceMaps.write('./')
        ]
      }))
      .pipe(gulp.dest(cfg.distDir))
      .pipe(bsServer.stream());
  }

  function bsServerSync() {
    if (cfg.env.maven) {
      bsServer.init();
    } else {
      bsServer.init({
        ui: {
          port: (cfg.serverPort + 1)
        },
        server: {
          baseDir: [cfg.distDir, './'],
          middleware: cfg.serverMiddlewares
        },
        port: cfg.serverPort
      });
    }
  }

  function serve(done) {
    gulp.series('build', gulp.parallel('bsServerSync', 'watch'))(done);
  }

  function serveDist(done) {
    gulp.series('buildDist', gulp.parallel('bsServerSync', 'watch'))(done);
  }

  function build(done) {
    if (cfg.env.maven) {
      gulp.series('clean', gulp.parallel('scripts', 'styles', 'images', 'bowerAssets', 'i18n', 'dev', 'symlinkDependencies'))(done);
    } else {
      gulp.series('clean', gulp.parallel('scripts', 'styles', 'images', 'bowerAssets', 'i18n', 'dev'))(done);
    }
  }

  function buildDist(done) {
    if (cfg.env.maven) {
      gulp.series('build', 'dist', 'unlinkDependencies')(done);
    } else {
      gulp.series('build', 'dist')(done);
    }
  }

  function watch() {
    gulp.watch(cfg.src.styles, gulp.parallel('styles'));
    gulp.watch(cfg.src.images, gulp.parallel('images'));
    gulp.watch(cfg.src.fonts, gulp.parallel('fonts'));
    gulp.watch(cfg.src.bowerLinks, gulp.parallel('build'));
    gulp.watch(cfg.src.indexHtml, gulp.parallel('dev'));
    gulp.watch([
      cfg.src.scripts,
      cfg.src.templates,
      cfg.src.unitTests
    ], debounce(gulp.series('scripts', 'unitTests'), 200));
    gulp.watch(cfg.src.i18n, gulp.parallel('i18n'));
  }

  gulp.task(bowerAssets);
  gulp.task(build);
  gulp.task(buildDist);
  gulp.task(clean);
  gulp.task(dev);
  gulp.task(dist);
  gulp.task(fonts);
  gulp.task(i18n);
  gulp.task(images);
  gulp.task(bsServerSync);
  gulp.task(scripts);
  gulp.task(serve);
  gulp.task(serveDist);
  gulp.task(styles);
  gulp.task(symlinkDependencies);
  gulp.task(unitTests);
  gulp.task(unitTestsDebug);
  gulp.task(unlinkDependencies);
  gulp.task(watch);
}

module.exports.buildTasks = buildTasks;
module.exports.buildConfig = buildConfig;
<commit_msg>Make serveDist only serve dist folder and not watch<commit_after>/*
 * Copyright 2015 Hippo B.V. (http://www.onehippo.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var autoprefixer = require('gulp-autoprefixer');
var browserSync = require('browser-sync');
var buildConfig = require('./build.conf.js');
var Builder = require('systemjs-builder');
var concat = require('gulp-concat');
var debounce = require('debounce');
var debug = require('gulp-debug');
var del = require('del');
var esLint = require('gulp-eslint');
var gulpif = require('gulp-if');
var imagemin = require('gulp-imagemin');
var insert = require('gulp-insert');
var karma = require('karma');
var minifyCss = require('gulp-minify-css');
var minifyHtml = require('gulp-minify-html');
var ngAnnotate = require('gulp-ng-annotate');
var path = require('path');
var plumber = require('gulp-plumber');
var rev = require('gulp-rev');
var sass = require('gulp-sass');
var sassLint = require('gulp-sass-lint');
var sourceMaps = require('gulp-sourcemaps');
var templateCache = require('gulp-angular-templatecache');
var uglify = require('gulp-uglify');
var usemin = require('gulp-usemin');

function buildTasks(customConfig, localGulp) {
  var cfg = buildConfig(customConfig);
  var gulp = localGulp || require('gulp');
  var bsServer = browserSync.create();

  function clean() {
    return del([cfg.distDir]);
  }

  function styles() {
    return gulp
      .src(cfg.src.indexStyles)
      .pipe(plumber())
      .pipe(sassLint({
        rules: cfg.sassLintRules
      }))
      .pipe(sassLint.format())
      .pipe(sassLint.failOnError())
      .pipe(sourceMaps.init())
      .pipe(sass({
        outputStyle: 'expanded'
      }))
      .pipe(autoprefixer({
        browsers: cfg.supportedBrowsers
      }))
      .pipe(sourceMaps.write('./'))
      .pipe(gulp.dest(cfg.dist.styles))
      .pipe(bsServer.stream());
  }

  function images() {
    return gulp
      .src(cfg.src.images)
      .pipe(plumber())
      .pipe(imagemin())
      .pipe(gulp.dest(cfg.dist.images))
      .pipe(bsServer.stream());
  }

  function fonts() {
    return gulp
      .src(cfg.src.fonts)
      .pipe(plumber())
      .pipe(gulp.dest(cfg.dist.fonts))
      .pipe(bsServer.stream());
  }

  function bowerAssets() {
    return gulp
      .src(cfg.bowerAssets)
      .pipe(plumber())
      .pipe(gulp.dest(cfg.distDir))
      .pipe(bsServer.stream());
  }

  function symlinkDependencies() {
    return gulp.src([
        path.basename(cfg.bowerDir),
        path.basename(cfg.npmDir)
      ])
      .pipe(gulp.symlink(cfg.distDir));
  }

  function unlinkDependencies() {
    return del([
      cfg.targetBowerDir,
      cfg.targetNpmDir
    ]);
  }

  function scripts(done) {
    gulp.series(
      function lint() {
        return gulp
          .src(cfg.src.scripts)
          .pipe(plumber())
          .pipe(esLint(cfg.esLintConfig))
          .pipe(esLint.format())
          .pipe(esLint.failOnError());
      },
      function transpile() {
        var systemjs = new Builder();
        systemjs.config(cfg.systemjsOptions);
        return systemjs.bundle(cfg.src.indexScript, cfg.dist.indexScript, {
          sourceMaps: true
        });
      },
      function annotate() {
        return gulp
          .src(cfg.dist.indexScript)
          .pipe(plumber())
          .pipe(sourceMaps.init({
            loadMaps: true
          }))
          .pipe(ngAnnotate())
          .pipe(sourceMaps.write('./'))
          .pipe(gulp.dest(cfg.dist.scripts));
      },
      function html2js() {
        return gulp
          .src([
            cfg.src.templates,
            cfg.dist.indexScript
          ])
          .pipe(plumber())
          .pipe(gulpif('*.html', templateCache({
            transformUrl: function(url) {
              return url.replace(/.*angularjs(?:\\|\/)/gi, '');
            },
            module: cfg.projectName + '-templates',
            standalone: true
          })))
          .pipe(concat(cfg.projectName + '.js'))
          .pipe(gulp.dest(cfg.dist.scripts));
      },
      function systemImport() {
        return gulp
          .src(cfg.dist.indexScript)
          .pipe(insert.append('System.import("' + cfg.src.indexScript + '");'))
          .pipe(gulp.dest(cfg.dist.scripts))
          .pipe(bsServer.stream());
      }
    )(done);
  }

  function unitTests(done) {
    gulp.series(
      function lint() {
        return gulp
          .src(cfg.src.unitTests)
          .pipe(plumber())
          .pipe(esLint(cfg.esLintConfig))
          .pipe(esLint.format())
          .pipe(esLint.failOnError());
      },
      function runKarma(karmaDone) {
        var server = new karma.Server({
          configFile: cfg.karmaConfig
        }, karmaDone);

        server.start();
      }
    )(done);
  }

  function unitTestsDebug(done) {
    gulp.series(
      function lint() {
        return gulp
          .src(cfg.src.unitTests)
          .pipe(plumber())
          .pipe(esLint(cfg.esLintConfig))
          .pipe(esLint.format())
          .pipe(esLint.failOnError());
      },
      function runKarma(karmaDone) {
        var server = new karma.Server({
          configFile: cfg.karmaConfig,
          browsers: ['Chrome'],
          singleRun: false,
          autoWatch: true
        }, karmaDone);

        server.start();
      }
    )(done);
  }

  function i18n() {
    return gulp
      .src(cfg.src.i18n)
      .pipe(plumber())
      .pipe(gulp.dest(cfg.dist.i18n));
  }

  function dev() {
    return gulp
      .src(cfg.src.indexHtml)
      .pipe(plumber())
      .pipe(gulp.dest(cfg.distDir))
      .pipe(bsServer.stream());
  }

  function dist() {
    return gulp
      .src(cfg.dist.indexHtml)
      .pipe(usemin({
        html: [
          minifyHtml()
        ],
        css: [
          sourceMaps.init(),
          minifyCss(),
          rev(),
          sourceMaps.write('./')
        ],
        js: [
          sourceMaps.init(),
          uglify(),
          rev(),
          sourceMaps.write('./')
        ]
      }))
      .pipe(gulp.dest(cfg.distDir))
      .pipe(bsServer.stream());
  }

  function bsServerSync() {
    if (cfg.env.maven) {
      bsServer.init();
    } else {
      bsServer.init({
        ui: {
          port: (cfg.serverPort + 1)
        },
        server: {
          baseDir: [cfg.distDir, './'],
          middleware: cfg.serverMiddlewares
        },
        port: cfg.serverPort
      });
    }
  }

  function bsServerSyncDist() {
    if (cfg.env.maven) {
      bsServer.init();
    } else {
      bsServer.init({
        ui: {
          port: (cfg.serverPort + 1)
        },
        server: {
          baseDir: [cfg.distDir],
          middleware: cfg.serverMiddlewares
        },
        port: cfg.serverPort
      });
    }
  }

  function serve(done) {
    gulp.series('build', gulp.parallel('bsServerSync', 'watch'))(done);
  }

  function serveDist(done) {
    gulp.series('buildDist', 'bsServerSyncDist')(done);
  }

  function build(done) {
    if (cfg.env.maven) {
      gulp.series('clean', gulp.parallel('scripts', 'styles', 'images', 'bowerAssets', 'i18n', 'dev', 'symlinkDependencies'))(done);
    } else {
      gulp.series('clean', gulp.parallel('scripts', 'styles', 'images', 'bowerAssets', 'i18n', 'dev'))(done);
    }
  }

  function buildDist(done) {
    if (cfg.env.maven) {
      gulp.series('build', 'dist', 'unlinkDependencies')(done);
    } else {
      gulp.series('build', 'dist')(done);
    }
  }

  function watch() {
    gulp.watch(cfg.src.styles, gulp.parallel('styles'));
    gulp.watch(cfg.src.images, gulp.parallel('images'));
    gulp.watch(cfg.src.fonts, gulp.parallel('fonts'));
    gulp.watch(cfg.src.bowerLinks, gulp.parallel('build'));
    gulp.watch(cfg.src.indexHtml, gulp.parallel('dev'));
    gulp.watch([
      cfg.src.scripts,
      cfg.src.templates,
      cfg.src.unitTests
    ], debounce(gulp.series('scripts', 'unitTests'), 200));
    gulp.watch(cfg.src.i18n, gulp.parallel('i18n'));
  }

  gulp.task(bowerAssets);
  gulp.task(build);
  gulp.task(buildDist);
  gulp.task(clean);
  gulp.task(dev);
  gulp.task(dist);
  gulp.task(fonts);
  gulp.task(i18n);
  gulp.task(images);
  gulp.task(bsServerSync);
  gulp.task(bsServerSyncDist);
  gulp.task(scripts);
  gulp.task(serve);
  gulp.task(serveDist);
  gulp.task(styles);
  gulp.task(symlinkDependencies);
  gulp.task(unitTests);
  gulp.task(unitTestsDebug);
  gulp.task(unlinkDependencies);
  gulp.task(watch);
}

module.exports.buildTasks = buildTasks;
module.exports.buildConfig = buildConfig;
<|endoftext|>


<commit_before>/** @babel */
import path from 'path';
import postcss from 'postcss';
import autoprefixer from 'autoprefixer';
import postcssSafeParser from 'postcss-safe-parser';
import postcssScssParser from 'postcss-scss';

function init() {
	const editor = atom.workspace.getActiveTextEditor();

	if (!editor) {
		return;
	}

	const selectedText = editor.getSelectedText();
	const text = selectedText || editor.getText();
	const filePath = editor.getPath();
	let postcssParser = postcssScssParser;

	if (filePath && path.extname(filePath).toLowerCase() === '.css') {
		postcssParser = postcssSafeParser;
	}

	postcss(autoprefixer(atom.config.get('autoprefixer'))).process(text, {
		parser: postcssParser
	}).then(result => {
		result.warnings().forEach(x => {
			console.warn(x.toString());
			atom.notifications.addWarning('Autoprefixer', {
				detail: x.toString()
			});
		});

		const cursorPosition = editor.getCursorBufferPosition();

		if (selectedText) {
			editor.setTextInBufferRange(editor.getSelectedBufferRange(), result.css);
		} else {
			editor.setText(result.css);
		}

		editor.setCursorBufferPosition(cursorPosition);
	}).catch(err => {
		if (err.name === 'CssSyntaxError') {
			err.message += err.showSourceCode();
		}

		console.error(err);
		atom.notifications.addError('Autoprefixer', {
			detail: err.message
		});
	});
}

export const config = {
	browsers: {
		title: 'Supported browsers',
		description: 'Using the [following syntax](https://github.com/ai/browserslist#queries).',
		type: 'array',
		default: autoprefixer.defaults,
		items: {
			type: 'string'
		}
	},
	cascade: {
		title: 'Cascade prefixes',
		type: 'boolean',
		default: true
	},
	remove: {
		title: 'Remove unneeded prefixes',
		type: 'boolean',
		default: true
	}
};

export const activate = () => {
	atom.commands.add('atom-workspace', 'autoprefixer', init);
};
<commit_msg>minor tweaks<commit_after>/** @babel */
import postcss from 'postcss';
import autoprefixer from 'autoprefixer';
import postcssSafeParser from 'postcss-safe-parser';
import postcssScss from 'postcss-scss';

function init() {
	const editor = atom.workspace.getActiveTextEditor();

	if (!editor) {
		return;
	}

	const selectedText = editor.getSelectedText();
	const text = selectedText || editor.getText();
	const parser = editor.getGrammar().scopeName === 'source.css' ? postcssSafeParser : postcssScss;

	postcss(autoprefixer(atom.config.get('autoprefixer'))).process(text, {parser}).then(result => {
		result.warnings().forEach(x => {
			console.warn(x.toString());
			atom.notifications.addWarning('Autoprefixer', {
				detail: x.toString()
			});
		});

		const cursorPosition = editor.getCursorBufferPosition();

		if (selectedText) {
			editor.setTextInBufferRange(editor.getSelectedBufferRange(), result.css);
		} else {
			editor.setText(result.css);
		}

		editor.setCursorBufferPosition(cursorPosition);
	}).catch(err => {
		if (err.name === 'CssSyntaxError') {
			err.message += err.showSourceCode();
		}

		console.error(err);
		atom.notifications.addError('Autoprefixer', {
			detail: err.message
		});
	});
}

export const config = {
	browsers: {
		title: 'Supported browsers',
		description: 'Using the [following syntax](https://github.com/ai/browserslist#queries).',
		type: 'array',
		default: autoprefixer.defaults,
		items: {
			type: 'string'
		}
	},
	cascade: {
		title: 'Cascade prefixes',
		type: 'boolean',
		default: true
	},
	remove: {
		title: 'Remove unneeded prefixes',
		type: 'boolean',
		default: true
	}
};

export const activate = () => {
	atom.commands.add('atom-workspace', 'autoprefixer', init);
};
<|endoftext|>


<commit_before>'use strict';

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

/**
 * Get an accurate type check for the given Object.
 *
 * @param {Mixed} obj The object that needs to be detected.
 * @returns {String} The object type.
 * @api public
 */
function is(obj) {
  return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
}

/**
 * Create a HTTP server.
 *
 * @param {Mixed} server Different ways of constructing a server.
 * @param {Object} fn Callback or callbacks.
 * @returns {Server} The created server.
 */
function create(server, fn) {
  fn = create.fn(fn);

  var options;

  switch (is(server)) {
    case 'object':
      options = server;
    break;

    case 'number':
      options = { port: server };
    break;
  }

  var port = options.port || 443                // Force HTTPS by default.
    , certs = options.key && options.cert       // Check HTTPS certs.
    , secure = certs || 443 === port            // Check for true HTTPS
    , spdy = 'spdy' in options                  // Or are we spdy
    , type;

  //
  // Determine which type of server we need to create.
  //
  if (spdy) type = 'spdy';
  else if (secure) type = 'https';
  else type = 'http';

  //
  // We need to have SSL certs for SPDY and secure servers.
  //
  if ((secure || spdy) && !certs) {
    throw new Error('Missing the SSL key or certificate files in the options.');
  }

  //
  // When given a `options.root` assume that our SSL certs and keys are path
  // references that still needs to be read. This allows a much more human
  // readable interface for SSL.
  //
  if (secure && options.root) {
    ['cert', 'key', 'ca', 'pfx', 'crl'].filter(function filter(key) {
      return key in options;
    }).forEach(function parse(key) {
      var data = options[key];

      if (Array.isArray(data)) {
        options[key] = data.map(function read(file) {
          return fs.readFileSync(path.join(options.root, file));
        });
      } else {
        options[key] = fs.readFileSync(path.join(options.root, data));
      }
    });
  }

  switch (type) {
    case 'http':
      server = require('http').createServer();
    break;

    case 'https':
      server = require('https').createServer(options);
    break;

    case 'spdy':
      server = require('spdy').createServer(options);
    break;
  }

  //
  // Setup an addition redirect server which redirects people to the correct
  // HTTP or HTTPS server.
  //
  if (+options.redirect) require('http').createServer(function handle(req, res) {
    res.statusCode = 404;

    if (req.headers.host) {
      res.statusCode = 301;
      res.setHeader(
        'Location',
        'http'+ (secure ? 's' : '') +'://'+ req.headers.host + req.url
      );
    }

    if (secure) res.setHeader(
      'Strict-Transport-Security',
      'max-age=8640000; includeSubDomains'
    );

    res.end('');
  }).listen(+options.redirect);

  //
  // Assign the last callbacks.
  //
  if (fn.request) server.on('request', fn.request);
  if (fn.close) server.once('close', fn.close);

  //
  // Things are completed, call callback.
  //
  if (fn[type]) fn[type]();

  if (options.listen === false || !fn.listening) return server;
  return listen(server, port, fn.listening);
}

/**
 * Create callbacks.
 *
 * @param {Object} fn Callback hooks.
 * @returns {Object} The callbacks
 * @api private
 */
create.fns = function fns(fn) {
  var callbacks = {};

  if ('function' === typeof fn) {
    callbacks.listening = fn;
    return callbacks;
  }

  [
    'close', 'request', 'listening',
    'http', 'https', 'spdy'
  ].forEach(function each(name) {
    if ('function' !== typeof fn[name]) return;

    callbacks[name] = fn[name];
  });

  return callbacks;
};

//
// Expose the create server method.
//
module.exports = create;
<commit_msg>[fix] Added default to switch [fix] Allow options to also specify the callbacks<commit_after>'use strict';

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

/**
 * Get an accurate type check for the given Object.
 *
 * @param {Mixed} obj The object that needs to be detected.
 * @returns {String} The object type.
 * @api public
 */
function is(obj) {
  return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
}

/**
 * Create a HTTP server.
 *
 * @param {Mixed} server Different ways of constructing a server.
 * @param {Object} fn Callback or callbacks.
 * @returns {Server} The created server.
 */
function create(server, fn) {
  var options;

  switch (is(server)) {
    case 'object':
      options = server;
    break;

    case 'number':
      options = { port: server };
    break;

    default:
      options = {};
    break;
  }

  fn = create.fns(fn || options);

  var port = options.port || 443                // Force HTTPS by default.
    , certs = options.key && options.cert       // Check HTTPS certs.
    , secure = certs || 443 === port            // Check for true HTTPS
    , spdy = 'spdy' in options                  // Or are we spdy
    , type;

  //
  // Determine which type of server we need to create.
  //
  if (spdy) type = 'spdy';
  else if (secure) type = 'https';
  else type = 'http';

  //
  // We need to have SSL certs for SPDY and secure servers.
  //
  if ((secure || spdy) && !certs) {
    throw new Error('Missing the SSL key or certificate files in the options.');
  }

  //
  // When given a `options.root` assume that our SSL certs and keys are path
  // references that still needs to be read. This allows a much more human
  // readable interface for SSL.
  //
  if (secure && options.root) {
    ['cert', 'key', 'ca', 'pfx', 'crl'].filter(function filter(key) {
      return key in options;
    }).forEach(function parse(key) {
      var data = options[key];

      if (Array.isArray(data)) {
        options[key] = data.map(function read(file) {
          return fs.readFileSync(path.join(options.root, file));
        });
      } else {
        options[key] = fs.readFileSync(path.join(options.root, data));
      }
    });
  }

  switch (type) {
    case 'http':
      server = require('http').createServer();
    break;

    case 'https':
      server = require('https').createServer(options);
    break;

    case 'spdy':
      server = require('spdy').createServer(options);
    break;
  }

  //
  // Setup an addition redirect server which redirects people to the correct
  // HTTP or HTTPS server.
  //
  if (+options.redirect) require('http').createServer(function handle(req, res) {
    res.statusCode = 404;

    if (req.headers.host) {
      res.statusCode = 301;
      res.setHeader(
        'Location',
        'http'+ (secure ? 's' : '') +'://'+ req.headers.host + req.url
      );
    }

    if (secure) res.setHeader(
      'Strict-Transport-Security',
      'max-age=8640000; includeSubDomains'
    );

    res.end('');
  }).listen(+options.redirect);

  //
  // Assign the last callbacks.
  //
  if (fn.request) server.on('request', fn.request);
  if (fn.close) server.once('close', fn.close);

  //
  // Things are completed, call callback.
  //
  if (fn[type]) fn[type]();

  if (options.listen === false || !fn.listening) return server;
  return listen(server, port, fn.listening);
}

/**
 * Create callbacks.
 *
 * @param {Object} fn Callback hooks.
 * @returns {Object} The callbacks
 * @api private
 */
create.fns = function fns(fn) {
  var callbacks = {};

  if ('function' === typeof fn) {
    callbacks.listening = fn;
    return callbacks;
  }

  [
    'close', 'request', 'listening',
    'http', 'https', 'spdy'
  ].forEach(function each(name) {
    if ('function' !== typeof fn[name]) return;

    callbacks[name] = fn[name];
  });

  return callbacks;
};

//
// Expose the create server method.
//
module.exports = create;
<|endoftext|>


<commit_before>var path = require('path');
var fs = require('fs');
var builder = require('xmlbuilder');

var TRXReporter = function (baseReporterDecorator, config, emitter, logger, helper, formatError) {
    var outputFile = config.outputFile;
    var shortTestName = !!config.shortTestName;
    var log = logger.create('reporter.trx');
    var hostName = require('os').hostname();
    var testRun;
    var resultSummary;
    var counters;
    var testDefinitions;
    var testListIdNotInAList;
    var testEntries;
    var results;
    var times;

    var getTimestamp = function () {
        // todo: use local time ?
        return (new Date()).toISOString().substr(0, 19);
    };

    var s4 = function () {
        return Math.floor((1 + Math.random()) * 0x10000)
            .toString(16)
            .substring(1);
    };

    var newGuid = function () {
        return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
    };

    var formatDuration = function (duration) {
        duration = duration | 0;
        var ms = duration % 1000;
        duration -= ms;
        var s = (duration / 1000) % 60;
        duration -= s * 1000;
        var m = (duration / 60000) % 60;
        duration -= m * 60000;
        var h = (duration / 3600000) % 24;
        duration -= h * 3600000;
        var d = duration / 86400000;

        return (d > 0 ? d + '.' : '') +
            (h < 10 ? '0' + h : h) + ':' +
            (m < 10 ? '0' + m : m) + ':' +
            (s < 10 ? '0' + s : s) + '.' +
            (ms < 10 ? '00' + ms : ms < 100 ? '0' + ms : ms);
    };

    baseReporterDecorator(this);

    this.onRunStart = function () {
        var userName = process.env.USERNAME || process.env.USER;
        var runStartTimestamp = getTimestamp();
        testRun = builder.create("TestRun", {version: '1.0', encoding: 'UTF-8'})
            .att('id', newGuid())
            .att('name', userName + '@' + hostName + ' ' + runStartTimestamp)
            .att('runUser', userName)
            .att('xmlns', 'http://microsoft.com/schemas/VisualStudio/TeamTest/2010');

        testRun.ele('TestSettings')
            .att('name', 'Karma Test Run')
            .att('id', newGuid());

        times = testRun.ele('Times');
        times.att('creation', runStartTimestamp);
        times.att('queuing', runStartTimestamp);
        times.att('start', runStartTimestamp);

        resultSummary = testRun.ele('ResultSummary');
        counters = resultSummary.ele('Counters');
        testDefinitions = testRun.ele('TestDefinitions');

        testListIdNotInAList = "8c84fa94-04c1-424b-9868-57a2d4851a1d";
        var testLists = testRun.ele('TestLists');

        testLists.ele('TestList')
            .att('name', 'Results Not in a List')
            .att('id', testListIdNotInAList);

        // seems to be VS is expecting that exact id
        testLists.ele('TestList')
            .att('name', 'All Loaded Results')
            .att('id', "19431567-8539-422a-85d7-44ee4e166bda");

        testEntries = testRun.ele('TestEntries');
        results = testRun.ele('Results');
    };

    this.onBrowserStart = function(browser) {
    };

    this.onBrowserComplete = function (browser) {
        var result = browser.lastResult;

        var passed = result.failed <= 0 && !result.error;
        resultSummary.att('outcome', passed ? 'Passed' : 'Failed');

        // todo: checkout if all theses numbers map well
        counters.att('total', result.total)
            .att('executed', result.total - result.skipped)
            .att('passed', result.success)
            .att('error', result.error ? 1 : 0)
            .att('failed', result.failed);

        // possible useful info:
        // todo: result.disconnected => this seems to happen occasionally? => Possibly handle it!
        // (result.netTime || 0) / 1000)
    };

    this.onRunComplete = function () {
        times.att('finish', getTimestamp());
        var xmlToOutput = testRun;

        helper.mkdirIfNotExists(path.dirname(outputFile), function () {
            fs.writeFile(outputFile, xmlToOutput.end({pretty: true}), function (err) {
                if (err) {
                    log.warn('Cannot write TRX testRun\n\t' + err.message);
                } else {
                    log.debug('TRX results written to "%s".', outputFile);
                }
            });
        });
    };

    this.specSuccess = this.specSkipped = this.specFailure = function (browser, result) {
        var unitTestId = newGuid();
        var unitTestName = shortTestName
            ? result.description
            : browser.name + '_' + result.description;
        var className = result.suite.join('.');
        var codeBase = className + '.' + unitTestName;

        var unitTest = testDefinitions.ele('UnitTest')
            .att('name', unitTestName)
            .att('id', unitTestId);
        var executionId = newGuid();
        unitTest.ele('Execution')
            .att('id', executionId);
        unitTest.ele('TestMethod')
            .att('codeBase', codeBase)
            .att('name', unitTestName)
            .att('className', className);

        testEntries.ele('TestEntry')
            .att('testId', unitTestId)
            .att('executionId', executionId)
            .att('testListId', testListIdNotInAList);

        var unitTestResult = results.ele('UnitTestResult')
            .att('executionId', executionId)
            .att('testId', unitTestId)
            .att('testName', unitTestName)
            .att('computerName', hostName)
            .att('duration', formatDuration(result.time || 0))
            .att('startTime', getTimestamp())
            .att('endTime', getTimestamp())
            // todo: are there other test types?
            .att('testType', '13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b') // that guid seems to represent 'unit test'
            .att('outcome', result.skipped ? 'NotExecuted' : (result.success ? 'Passed' : 'Failed'))
            .att('testListId', testListIdNotInAList);

        if (!result.success) {
            unitTestResult.ele('Output')
                .ele('ErrorInfo')
                .ele('Message', formatError(result.log[0]))
        }
    };
};

TRXReporter.$inject = ['baseReporterDecorator', 'config.trxReporter', 'emitter', 'logger',
    'helper', 'formatError'];

// PUBLISH DI MODULE
module.exports = {
    'reporter:trx': ['type', TRXReporter]
};
<commit_msg>Stop trimming timestamps by default<commit_after>var path = require('path');
var fs = require('fs');
var builder = require('xmlbuilder');

var TRXReporter = function (baseReporterDecorator, config, emitter, logger, helper, formatError) {
    var outputFile = config.outputFile;
    var shortTestName = !!config.shortTestName;
    var trimTimestamps = !!config.trimTimestamps;
    var log = logger.create('reporter.trx');
    var hostName = require('os').hostname();
    var testRun;
    var resultSummary;
    var counters;
    var testDefinitions;
    var testListIdNotInAList;
    var testEntries;
    var results;
    var times;

    var getTimestamp = function () {
        // todo: use local time ?
        return trimTimestamps
            ? new Date().toISOString().substr(0, 19)
            : new Date().toISOString();
    };

    var s4 = function () {
        return Math.floor((1 + Math.random()) * 0x10000)
            .toString(16)
            .substring(1);
    };

    var newGuid = function () {
        return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
    };

    var formatDuration = function (duration) {
        duration = duration | 0;
        var ms = duration % 1000;
        duration -= ms;
        var s = (duration / 1000) % 60;
        duration -= s * 1000;
        var m = (duration / 60000) % 60;
        duration -= m * 60000;
        var h = (duration / 3600000) % 24;
        duration -= h * 3600000;
        var d = duration / 86400000;

        return (d > 0 ? d + '.' : '') +
            (h < 10 ? '0' + h : h) + ':' +
            (m < 10 ? '0' + m : m) + ':' +
            (s < 10 ? '0' + s : s) + '.' +
            (ms < 10 ? '00' + ms : ms < 100 ? '0' + ms : ms);
    };

    baseReporterDecorator(this);

    this.onRunStart = function () {
        var userName = process.env.USERNAME || process.env.USER;
        var runStartTimestamp = getTimestamp();
        testRun = builder.create("TestRun", {version: '1.0', encoding: 'UTF-8'})
            .att('id', newGuid())
            .att('name', userName + '@' + hostName + ' ' + runStartTimestamp)
            .att('runUser', userName)
            .att('xmlns', 'http://microsoft.com/schemas/VisualStudio/TeamTest/2010');

        testRun.ele('TestSettings')
            .att('name', 'Karma Test Run')
            .att('id', newGuid());

        times = testRun.ele('Times');
        times.att('creation', runStartTimestamp);
        times.att('queuing', runStartTimestamp);
        times.att('start', runStartTimestamp);

        resultSummary = testRun.ele('ResultSummary');
        counters = resultSummary.ele('Counters');
        testDefinitions = testRun.ele('TestDefinitions');

        testListIdNotInAList = "8c84fa94-04c1-424b-9868-57a2d4851a1d";
        var testLists = testRun.ele('TestLists');

        testLists.ele('TestList')
            .att('name', 'Results Not in a List')
            .att('id', testListIdNotInAList);

        // seems to be VS is expecting that exact id
        testLists.ele('TestList')
            .att('name', 'All Loaded Results')
            .att('id', "19431567-8539-422a-85d7-44ee4e166bda");

        testEntries = testRun.ele('TestEntries');
        results = testRun.ele('Results');
    };

    this.onBrowserStart = function(browser) {
    };

    this.onBrowserComplete = function (browser) {
        var result = browser.lastResult;

        var passed = result.failed <= 0 && !result.error;
        resultSummary.att('outcome', passed ? 'Passed' : 'Failed');

        // todo: checkout if all theses numbers map well
        counters.att('total', result.total)
            .att('executed', result.total - result.skipped)
            .att('passed', result.success)
            .att('error', result.error ? 1 : 0)
            .att('failed', result.failed);

        // possible useful info:
        // todo: result.disconnected => this seems to happen occasionally? => Possibly handle it!
        // (result.netTime || 0) / 1000)
    };

    this.onRunComplete = function () {
        times.att('finish', getTimestamp());
        var xmlToOutput = testRun;

        helper.mkdirIfNotExists(path.dirname(outputFile), function () {
            fs.writeFile(outputFile, xmlToOutput.end({pretty: true}), function (err) {
                if (err) {
                    log.warn('Cannot write TRX testRun\n\t' + err.message);
                } else {
                    log.debug('TRX results written to "%s".', outputFile);
                }
            });
        });
    };

    this.specSuccess = this.specSkipped = this.specFailure = function (browser, result) {
        var unitTestId = newGuid();
        var unitTestName = shortTestName
            ? result.description
            : browser.name + '_' + result.description;
        var className = result.suite.join('.');
        var codeBase = className + '.' + unitTestName;

        var unitTest = testDefinitions.ele('UnitTest')
            .att('name', unitTestName)
            .att('id', unitTestId);
        var executionId = newGuid();
        unitTest.ele('Execution')
            .att('id', executionId);
        unitTest.ele('TestMethod')
            .att('codeBase', codeBase)
            .att('name', unitTestName)
            .att('className', className);

        testEntries.ele('TestEntry')
            .att('testId', unitTestId)
            .att('executionId', executionId)
            .att('testListId', testListIdNotInAList);

        var unitTestResult = results.ele('UnitTestResult')
            .att('executionId', executionId)
            .att('testId', unitTestId)
            .att('testName', unitTestName)
            .att('computerName', hostName)
            .att('duration', formatDuration(result.time || 0))
            .att('startTime', getTimestamp())
            .att('endTime', getTimestamp())
            // todo: are there other test types?
            .att('testType', '13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b') // that guid seems to represent 'unit test'
            .att('outcome', result.skipped ? 'NotExecuted' : (result.success ? 'Passed' : 'Failed'))
            .att('testListId', testListIdNotInAList);

        if (!result.success) {
            unitTestResult.ele('Output')
                .ele('ErrorInfo')
                .ele('Message', formatError(result.log[0]))
        }
    };
};

TRXReporter.$inject = ['baseReporterDecorator', 'config.trxReporter', 'emitter', 'logger',
    'helper', 'formatError'];

// PUBLISH DI MODULE
module.exports = {
    'reporter:trx': ['type', TRXReporter]
};
<|endoftext|>


<commit_before>#!/home/ubuntu/.nodebrew/current/bin/node
const fs = require("fs");
const util = require("util");
const twitter = require("twitter");
let path = require("path");
const readline = require("readline").createInterface({
	input: process.stdin,
	output: process.stdout
});

let pathdata = process.argv[1];
pathdata = path.dirname(pathdata);
let key = fs.readFileSync(__dirname + "/key.txt", "utf8");
if (key === "") {
	console.log("https://apps.twitter.com/ からapi-keyを取得し,keyset.jsを使用してキーを登録してください。");
	process.exit();
} else {
	key = key.split(",");
	key = new twitter({
		consumer_key: key[0],
		consumer_secret: key[1],
		access_token_key: key[2],
		access_token_secret: key[3]
	});
};

//文字色
const black = '\u001b[30m';
const red = '\u001b[31m';
const green = '\u001b[32m';
const yellow = '\u001b[33m';
const blue = '\u001b[34m';
const magenta = '\u001b[35m';
const cyan = '\u001b[36m';
const white = '\u001b[37m';
const reset = '\u001b[0m';
//記憶域
let twinum = -1;
let twiid = [];
let twitxt = [];
let scname = [];
let replynum = "";
let mode = undefined;

let shell = [];
shell = process.argv;
console.log(shell[2])
switch (shell[2]) {
	case "h":
		//ヘルプ
		console.log("h:ヘルプ\r\ntl:TLを流す\r\n一致しない場合:第二引数をツイート後即終了");
		break;
	case undefined :
	case "tl":
		//TLを流す
		console.log(green + " #    #  " + cyan + "######  " + yellow + "#       " + red + " ####   " + white + " ####   " + yellow + "#    #  " + blue + "######" + reset);
		console.log(green + " #    #  " + cyan + "#       " + yellow + "#       " + red + "#    #  " + white + "#    #  " + yellow + "##  ##  " + blue + "#     " + reset);
		console.log(green + " #    #  " + cyan + "#####   " + yellow + "#       " + red + "#       " + white + "#    #  " + yellow + "# ## #  " + blue + "##### " + reset);
		console.log(green + " # ## #  " + cyan + "#       " + yellow + "#       " + red + "#       " + white + "#    #  " + yellow + "#    #  " + blue + "#     " + reset);
		console.log(green + " ##  ##  " + cyan + "#       " + yellow + "#       " + red + "#    #  " + white + "#    #  " + yellow + "#    #  " + blue + "#     " + reset);
		console.log(green + " #    #  " + cyan + "######  " + yellow + "######  " + red + " ####   " + white + " ####   " + yellow + "#    #  " + blue + "######" + reset);
		console.log("\r\ntimeline mode\r\n");

		key.stream('user', function (stream) {
			stream.on("data", function (data) {

				let tmp = data.source;
				tmp = tmp.split('">');
				tmp = tmp[1].split('');

				twinum = twinum + 1;
				twiid.push(data.id_str);
				twitxt.push(data.text);
				scname.push(data.user.screen_name);

				let temp = "No." + twinum + "\r\n";
				temp += cyan + data.user.name + " @" + data.user.screen_name + "\r\n";
				temp += white + data.text + "\r\n";
				temp += green + "via " + tmp + "\r\n";
				temp += data.user.created_at + reset + "\r\n";

				console.log(temp);
			})
		});

		//↓TLモード内コマンド判定式------------------
		readline.on('line', function (line) {

			if (line === "q") {
				mode = ""
				console.log("cancel")
			} else {
				switch (mode) {
					case "replynum":
						mode = "replymsg";
						replynum = line;
						console.log("repry msg?");
						break;

					case "replymsg":
						mode = undefined;
						console.log(cyan + "send...")
						key.post('statuses/update',
							{ status: "@" + scname[replynum] + " " + line, in_reply_to_status_id: twiid[replynum] },
							function (error, tweet, response) {
								if (!error) {
									//console.log(tweet);
									console.log(green + "tweet success\r\n" + reset);
								} else {
									console.log(red + "tweet error\r\n" + reset);
								};
								replyid = "";
							}
						);
						break;
					case "rt":
						//RT
						mode = undefined;
						key.post('statuses/retweet/' + twiid[line] + '.json',
							function (error) {
								if (!error) {
									console.log(green + "\r\nRT success\r\n" + reset);
								} else {
									console.log(red + "\r\nRT error\r\n" + reset);
								};
							});
						break;
					case "fav":
						//ふぁぼ
						mode = undefined;
						key.post('favorites/create.json?id=' + twiid[line] + "&include_entities=true",
							function (error) {
								if (!error) {
									console.log(green + "\r\nFav success\r\n" + reset);
								} else {
									console.log(red + "\r\nFav error\r\n" + reset);
								};
							});
						break;
					case "copy":
						//パクツイ
						mode = "";
						console.log(cyan + "send...");
						key.post('statuses/update',
							{ status: twitxt[line] },
							function (error, tweet, response) {
								if (!error) {
									//console.log(tweet);
									console.log(green + "tweet success\r\n" + reset);
								} else {
									console.log(red + "tweet error\r\n" + reset);
								};
							}
						);
						break;
					default:
						switch (line) {
							case "h":
								if (mode === undefined) {
									console.log(" r=retweet \r\n f=Favorite \r\n c=copy \r\n m=reply(message) \r\n q=cancel");
								} else {
									console.log("Number=No,*");
								};
								break;
							case "r":
								mode = "rt";
								console.log("RT Number?");
								break;
							case "f":
								mode = "fav";
								console.log("Fav Number?");
								break;
							case "c":
								mode = "copy";
								console.log("Copy Number?");
								break;
							case "m":
								mode = "replynum";
								console.log("reply Number?");
								break;
							default:
								console.log(cyan + "send...");
								key.post('statuses/update',
									{ status: line },
									function (error, tweet, response) {
										if (!error) {
											//console.log(tweet);
											console.log(green + "tweet success\r\n" + reset);
										} else {
											console.log(red + "tweet error\r\n" + reset);
										};
									}
								);
								break;
						}//swich mode
						break;
				};//switch line
			}
		});//入力
		//↑TLモード内コマンド判定式----------------------------
		break;
	default:
		//ツイート後即終了
		console.log(cyan + 'send...' + reset);
		key.post('statuses/update',
			{ status: shell[2] },
			function (error, tweet, response) {
				if (!error) {
					//console.log(tweet);
					console.log(green + "success" + reset);
				} else {
					console.log(red + "error" + reset);
					console.log(error);
				};
				process.exit();
			});
		break;

};//switch shell

/*
licenses

mitライセンスのnode-twitterを利用させていただきました。

MIT License Copyright (c) 2016 Desmond Morris

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/<commit_msg>フォロふぁぼツイ消し通知追加<commit_after>#!/home/ubuntu/.nodebrew/current/bin/node
const fs = require("fs");
const util = require("util");
const twitter = require("twitter");
let path = require("path");
const readline = require("readline").createInterface({
	input: process.stdin,
	output: process.stdout
});

let pathdata = process.argv[1];
pathdata = path.dirname(pathdata);
let key = fs.readFileSync(__dirname + "/key.txt", "utf8");
if (key === "") {
	console.log("https://apps.twitter.com/ からapi-keyを取得し,keyset.jsを使用してキーを登録してください。");
	process.exit();
} else {
	key = key.split(",");
	key = new twitter({
		consumer_key: key[0],
		consumer_secret: key[1],
		access_token_key: key[2],
		access_token_secret: key[3]
	});
};

//文字色
const black = '\u001b[30m';
const red = '\u001b[31m';
const green = '\u001b[32m';
const yellow = '\u001b[33m';
const blue = '\u001b[34m';
const magenta = '\u001b[35m';
const cyan = '\u001b[36m';
const white = '\u001b[37m';
const reset = '\u001b[0m';
//記憶域
let twinum = -1;
let twiid = [];
let twitxt = [];
let twiname = [];
let twiscname = [];
let replynum = "";
let mode = undefined;

let shell = [];
shell = process.argv;
console.log(shell[2])
switch (shell[2]) {
	case "h":
		//ヘルプ
		console.log("h:ヘルプ\r\ntl:TLを流す\r\n一致しない場合:第二引数をツイート後即終了");
		break;
	case undefined:
	case "tl":
		//TLを流す
		console.log(green + " #    #  " + cyan + "######  " + yellow + "#       " + red + " ####   " + white + " ####   " + yellow + "#    #  " + blue + "######" + reset);
		console.log(green + " #    #  " + cyan + "#       " + yellow + "#       " + red + "#    #  " + white + "#    #  " + yellow + "##  ##  " + blue + "#     " + reset);
		console.log(green + " #    #  " + cyan + "#####   " + yellow + "#       " + red + "#       " + white + "#    #  " + yellow + "# ## #  " + blue + "##### " + reset);
		console.log(green + " # ## #  " + cyan + "#       " + yellow + "#       " + red + "#       " + white + "#    #  " + yellow + "#    #  " + blue + "#     " + reset);
		console.log(green + " ##  ##  " + cyan + "#       " + yellow + "#       " + red + "#    #  " + white + "#    #  " + yellow + "#    #  " + blue + "#     " + reset);
		console.log(green + " #    #  " + cyan + "######  " + yellow + "######  " + red + " ####   " + white + " ####   " + yellow + "#    #  " + blue + "######" + reset);
		console.log("\r\ntimeline mode\r\n");

		key.stream('user', function (stream) {

			stream.on("data", function (data) {

				let tmp = data.source;
				tmp = tmp.split('">');
				tmp = tmp[1].split('');

				twinum = twinum + 1;
				twiid.push(data.id_str);
				twitxt.push(data.text);
				twiname.push(data.user.name);
				twiscname.push(data.user.screen_name);

				let temp = "No." + twinum + "\r\n";
				temp += cyan + data.user.name + " @" + data.user.screen_name + "\r\n";
				temp += white + data.text + "\r\n";
				temp += green + "via " + tmp + "\r\n";
				temp += data.user.created_at + reset + "\r\n";

				console.log(temp);
			})

			//ツイ消し通知
			stream.on("delete", function (data) {
				for (let i = twiid.length; i > 0; i--) {
					if (twiid[i] === data.delete.status.id_str) {
						let temp = ""
						temp += red + "delete\r\n";
						temp += twiname[i] + " " + twiscname[i] + "\r\n";
						temp += twitxt[i] + reset + "\r\n";
						console.log(temp);
						break;
					}
				}
			})

			stream.on("event", function (data) {
				let temp = red
				switch (data.event) {
					case "follow":
						temp += "follow \r\n"
						temp += data.source.name + "\r\n";
						temp += "@" + data.source.screen_name + "\r\n" + reset
						console.log(temp);
						break;
					case "favorite":
						temp += "favorite" + "\r\n";
						temp += "source\r\n"
						temp += data.source.name +" @"+ data.source.screen_name + "\r\n";
						temp += "target\r\n"
						temp += data.target.name + " @" + data.target.screen_name + "\r\n";
						temp += data.target_object.text + reset + "\r\n"
						console.log(temp);
						break;
					case "unfavorite":
					  temp += "unfavorite" + "\r\n";
					  temp += "source\r\n"
					  temp += data.source.name +" @"+ data.source.screen_name + "\r\n";
					  temp += "target\r\n"
					  temp += data.target.name + " @" + data.target.screen_name + "\r\n";
					  temp += data.target_object.text + reset + "\r\n"
						console.log(temp);
						break;
					default:
						temp += "未知のイベントが検出されました。プログラムの機能拡充の為、以下のメッセージを開発者に伝えていただけると幸いです。\r\n\r\n"
						temp += data + reset
						console.log(temp);
						break;
				}
			})

		});

		//↓TLモード内コマンド判定式------------------
		readline.on('line', function (line) {

			if (line === "q") {
				mode = ""
				console.log("cancel")
			} else {
				switch (mode) {
					case "replynum":
						mode = "replymsg";
						replynum = line;
						console.log("repry msg?");
						break;

					case "replymsg":
						mode = undefined;
						console.log(cyan + "send...")
						key.post('statuses/update',
							{ status: "@" + twiscname[replynum] + " " + line, in_reply_to_status_id: twiid[replynum] },
							function (error, tweet, response) {
								if (!error) {
									//console.log(tweet);
									console.log(green + "tweet success\r\n" + reset);
								} else {
									console.log(red + "tweet error\r\n" + reset);
								};
								replyid = "";
							}
						);
						break;
					case "rt":
						//RT
						mode = undefined;
						key.post('statuses/retweet/' + twiid[line] + '.json',
							function (error) {
								if (!error) {
									console.log(green + "\r\nRT success\r\n" + reset);
								} else {
									console.log(red + "\r\nRT error\r\n" + reset);
								};
							});
						break;
					case "fav":
						//ふぁぼ
						mode = undefined;
						key.post('favorites/create.json?id=' + twiid[line] + "&include_entities=true",
							function (error) {
								if (!error) {
									console.log(green + "\r\nFav success\r\n" + reset);
								} else {
									console.log(red + "\r\nFav error\r\n" + reset);
								};
							});
						break;
					case "copy":
						//パクツイ
						mode = "";
						console.log(cyan + "send...");
						key.post('statuses/update',
							{ status: twitxt[line] },
							function (error, tweet, response) {
								if (!error) {
									//console.log(tweet);
									console.log(green + "tweet success\r\n" + reset);
								} else {
									console.log(red + "tweet error\r\n" + reset);
								};
							}
						);
						break;
					default:
						switch (line) {
							case "h":
								if (mode === undefined) {
									console.log(" r=retweet \r\n f=Favorite \r\n c=copy \r\n m=reply(message) \r\n q=cancel");
								} else {
									console.log("Number=No,*");
								};
								break;
							case "r":
								mode = "rt";
								console.log("RT Number?");
								break;
							case "f":
								mode = "fav";
								console.log("Fav Number?");
								break;
							case "c":
								mode = "copy";
								console.log("Copy Number?");
								break;
							case "m":
								mode = "replynum";
								console.log("reply Number?");
								break;
							default:
								console.log(cyan + "send...");
								key.post('statuses/update',
									{ status: line },
									function (error, tweet, response) {
										if (!error) {
											//console.log(tweet);
											console.log(green + "tweet success\r\n" + reset);
										} else {
											console.log(red + "tweet error\r\n" + reset);
										};
									}
								);
								break;
						}//swich mode
						break;
				};//switch line
			}
		});//入力
		//↑TLモード内コマンド判定式----------------------------
		break;
	default:
		//ツイート後即終了
		console.log(cyan + 'send...' + reset);
		key.post('statuses/update',
			{ status: shell[2] },
			function (error, tweet, response) {
				if (!error) {
					//console.log(tweet);
					console.log(green + "success" + reset);
				} else {
					console.log(red + "error" + reset);
					console.log(error);
				};
				process.exit();
			});
		break;

};//switch shell

/*
licenses

mitライセンスのnode-twitterを利用させていただきました。

MIT License Copyright (c) 2016 Desmond Morris

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/<|endoftext|>


<commit_before>var os = require('os');
var vm = require('vm');
var fs = require('fs');
var path = require('path');

var tsc = require.resolve("typescript").replace(/typescript\.js$/, "tsc.js");
var tscScript = vm.createScript(fs.readFileSync(tsc, "utf8"), tsc);

var options = {
  nodeLib: false,
  targetES5: true,
  moduleKind: 'commonjs'
};

module.exports = function(opts) {
  options = merge(options, opts);
};

require.extensions['.ts'] = function(module) {
  var jsname = compileTS(module);
  runJS(jsname, module);
};

/**
 * Compiles TypeScript file, returns js file path
 * @return {string} js file path
 */
function compileTS (module) {
  var exitCode = 0;
  var tmpDir = path.join(os.tmpDir(), "tsreq_" + Math.floor(Math.random() * 0xFFFFFFFF));

  var argv = [
    "node",
    "tsc.js",
    "--nolib",
    "--target",
    options.targetES5 ? "ES5" : "ES3", !! options.moduleKind ? "--module" : "", !! options.moduleKind ? options.moduleKind : "",
    "--outDir",
    tmpDir,
    path.resolve(__dirname, "typings/lib.d.ts"),
    options.nodeLib ? path.resolve(__dirname, "typings/node.d.ts") : null,
    module.filename
  ];

  var proc = merge(merge({}, process), {
    argv: compact(argv),
    exit: function(code) {
      exitCode = code;
    }
  });

  var sandbox = {
    process: proc,
    require: require,
    module: module,
    Buffer: Buffer,
    setTimeout: setTimeout,
  };

  tscScript.runInNewContext(sandbox);
  if (exitCode != 0) {
    throw new Error('Unable to compile TypeScript file.');
  }

  return path.join(tmpDir, path.basename(module.filename, ".ts") + ".js");
}

function runJS (jsname, module) {
  var content = fs.readFileSync(jsname, 'utf8');

  var sandbox = {};
  for (var k in global) {
    sandbox[k] = global[k];
  }
  sandbox.require = require;
  sandbox.exports = module.exports;
  sandbox.__filename = jsname;
  sandbox.__dirname = path.dirname(module.filename);;
  sandbox.module = module;
  sandbox.global = sandbox;
  sandbox.root = root;

  return vm.runInNewContext(content, sandbox, { filename: jsname });
}

function merge(a, b) {
  if (a && b) {
    for (var key in b) {
      a[key] = b[key];
    }
  }
  return a;
};

function compact(arr) {
  var narr = [];
  arr.forEach(function(data) {
    if (data) narr.push(data);
  });
  return narr;
}
<commit_msg>removed comma<commit_after>var os = require('os');
var vm = require('vm');
var fs = require('fs');
var path = require('path');

var tsc = require.resolve("typescript").replace(/typescript\.js$/, "tsc.js");
var tscScript = vm.createScript(fs.readFileSync(tsc, "utf8"), tsc);

var options = {
  nodeLib: false,
  targetES5: true,
  moduleKind: 'commonjs'
};

module.exports = function(opts) {
  options = merge(options, opts);
};

require.extensions['.ts'] = function(module) {
  var jsname = compileTS(module);
  runJS(jsname, module);
};

/**
 * Compiles TypeScript file, returns js file path
 * @return {string} js file path
 */
function compileTS (module) {
  var exitCode = 0;
  var tmpDir = path.join(os.tmpDir(), "tsreq_" + Math.floor(Math.random() * 0xFFFFFFFF));

  var argv = [
    "node",
    "tsc.js",
    "--nolib",
    "--target",
    options.targetES5 ? "ES5" : "ES3", !! options.moduleKind ? "--module" : "", !! options.moduleKind ? options.moduleKind : "",
    "--outDir",
    tmpDir,
    path.resolve(__dirname, "typings/lib.d.ts"),
    options.nodeLib ? path.resolve(__dirname, "typings/node.d.ts") : null,
    module.filename
  ];

  var proc = merge(merge({}, process), {
    argv: compact(argv),
    exit: function(code) {
      exitCode = code;
    }
  });

  var sandbox = {
    process: proc,
    require: require,
    module: module,
    Buffer: Buffer,
    setTimeout: setTimeout
  };

  tscScript.runInNewContext(sandbox);
  if (exitCode != 0) {
    throw new Error('Unable to compile TypeScript file.');
  }

  return path.join(tmpDir, path.basename(module.filename, ".ts") + ".js");
}

function runJS (jsname, module) {
  var content = fs.readFileSync(jsname, 'utf8');

  var sandbox = {};
  for (var k in global) {
    sandbox[k] = global[k];
  }
  sandbox.require = require;
  sandbox.exports = module.exports;
  sandbox.__filename = jsname;
  sandbox.__dirname = path.dirname(module.filename);;
  sandbox.module = module;
  sandbox.global = sandbox;
  sandbox.root = root;

  return vm.runInNewContext(content, sandbox, { filename: jsname });
}

function merge(a, b) {
  if (a && b) {
    for (var key in b) {
      a[key] = b[key];
    }
  }
  return a;
};

function compact(arr) {
  var narr = [];
  arr.forEach(function(data) {
    if (data) narr.push(data);
  });
  return narr;
}
<|endoftext|>


<commit_before>function Queue(callback_error, callback_successed, callback_thisArg) {
  var queue = [];
  var aborted = false;
  var executing = false;

  this.add = function(callback) {
    if(executing)
      throw new Error("The Queue already executed");

    queue.push(callback);
  };

  this.error = function() {
    aborted = true;
    callback_error.apply(callback_thisArg, arguments);
  };

  this.deliver = function() {
    if(queue.length < 1)
      callback_successed.apply(callback_thisArg, arguments);
    else
      queue.shift().apply(this, arguments);
  };

  this.execute = function() {
    if(executing)
      throw new Error("The Queue already executed");

    executing = true;

    if(queue.length < 1) {
      callback_successed();
      return;
    }

    queue.shift().apply(this, arguments);
  };
};

module.exports.createQueue = function(callback_error, callback_successed, callback_thisArg) {
  return new Queue(callback_error, callback_successed, callback_thisArg);
}
<commit_msg>mod: call callback_successed when queue is empty<commit_after>function Queue(callback_error, callback_successed, callback_thisArg) {
  var queue = [];
  var aborted = false;
  var executing = false;

  this.add = function(callback) {
    if(executing)
      throw new Error("The Queue already executed");

    queue.push(callback);
  };

  this.error = function() {
    aborted = true;
    callback_error.apply(callback_thisArg, arguments);
  };

  this.deliver = function() {
    if(queue.length < 1)
      callback_successed.apply(callback_thisArg, arguments);
    else
      queue.shift().apply(this, arguments);
  };

  this.execute = function() {
    if(executing)
      throw new Error("The Queue already executed");

    executing = true;

    if(queue.length < 1) {
      callback_successed.apply(callback_thisArg, arguments);
      return;
    }

    queue.shift().apply(this, arguments);
  };
};

module.exports.createQueue = function(callback_error, callback_successed, callback_thisArg) {
  return new Queue(callback_error, callback_successed, callback_thisArg);
}
<|endoftext|>