<commit_before>/**
 * language and OOP enhancement for non-ECMAScript5 standards
 */

;(function(K, undef){

/**
 * copy all properties in the supplier to the receiver
 * @param r {Object} receiver
 * @param s {Object} supplier
 * @param or {boolean=} whether override the existing property in the receiver
 * @param cl {(Array.<string>)=} copy list, an array of selected properties
 */
function mix(r, s, or, cl) {
	if (!s || !r) return r;
	var i = 0, c, len;
	or = or || or === undef;

	if (cl && (len = cl.length)) {
		for (; i < len; i++) {
			c = cl[i];
			if ( (c in s) && (or || !(c in r) ) ) {
				r[c] = s[c];
			}
		}
	} else {
		for (c in s) {
			if (or || !(c in r)) {
				r[c] = s[c];
			}
		}
	}
	return r;
};

// bind the this pointer of a function
function bind_method(fn, bind){
	return function(){
		return fn.apply(bind, arguments);
	}
};

/**
 * transform functions that have the signature fn(key, value)
 * to
 * functions that could accept object arguments
 * @adapter
 */
function overloadSetter(fn){

	// @return {undefined} setter method will always return this,
	// for the sake of potential chain-style invocations
	return function(key, value){
		var self = this;

		if (key || key === 0){
			if (K.isString(key)){
				fn.call(self, key, value);

			}else if (K.isObject(key)){
				K.each(key, function(v, k){
					fn.call(self, k, v);
				});
			}
		}

		return self;
	};
};

/**
 * memoize static result of a complicated method to save time
 */
function memoizeMethod(fn){
	var stack = {};

	return function(){
		var arg = array_join.call(arguments, '~^_^~');

		return (arg in stack) ? stack[arg] : (stack[arg] = fn.apply(null, arguments));
	}
};

/**
 * transform constructor functions to functions that could change a method of a instance or singleton
 */
/*
function overload_for_instance_method(fn){
	var self = this;

	return function(methodname, instance){
		var arg = arguments;

		return K.isFunction(methodname) ?
			fn.apply(self, arg)
		:	instance[methodname] = fn.call(instance, instance[methodname], instance);
	};
};
*/

function toQueryString(obj, splitter){
	var key, value, ret = [], encode = encodeURIComponent;

	for(key in obj){
		!K.isObject(value = obj[key]) && !K.isArray(value) && ret.push(key + '=' + encode(value));
	}

	return ret.join(splitter || '&');
};

/**
 * @param {mixed} o
 * @param {Object} stack
 */
function clone(o, marked, cached){
	var cloned = {}, m, id;

	// internal use
	cached || (cached = {});

	switch(K._type(o)){
		case 'date':
			return new Date(o);

		case 'array':
			cloned = [];

		// object, plainObject, instance
		case 'object':
			m = CLONE_MARKER;

			if(o[m]){
				return cached[o[m]];
			}

			id = _guid ++;

			// mark copied object to prevent duplicately cloning
			o[m] = id;
			marked[id] = o;
			cached[id] = cloned;

			K.each(o, function(value, key){
				if(key !== m){
					cloned[key] = clone(value, marked, cached);
				}
			});

			// free
			marked = cached = null;

			return cloned;

		// number, boolean, element(DOMElement, HTMLWindow, HTMLDocument, HTMLhtmlElement), collections
		// arguments?
		default:
			return o;
	}
};

var	NOOP = function(){},
	array_join = Array.prototype.join,
	CLONE_MARKER = '>_>~cloned',

	_guid = 1;

/**
 * language enhancement

 * for non-ECMAScript5 implementations, we'll add them into the KM namespace
 * and ECMAScript5 standard methods will be included in native.js
 * --------------------------------------------------------------------------------------------- */

K.mix = mix;

K.guid = function(){
	return _guid ++;
};

/**
 * forEach method for Object
 */
K.each = function(obj, fn){
	if(K.isFunction(fn)){

		if(K.isObject(obj)){
			var keys = Object.keys(obj), i = 0, len = keys.length, key;

			for(; i < len; i ++){
				key = keys[i];
				obj.hasOwnProperty(key) && fn.call(obj, obj[key], key);
			}

		}else if(K.isArray(obj)){
			obj.forEach(fn);

		}
	}
};

/**
 * deep clone an object, excluding properties on prototype chain
 */
K.clone = function(o) {
	var marked = {},
		m = CLONE_MARKER,
		cloned = clone(o, marked);

	// remove CLONE_MARKER
	K.each(marked, function(v){
		try{
			delete v[m];
		}catch(e){
			K.log('del CLONE_MARKER err', e);
			v[m] = undefined;
		}
	});

	marked = null;

	return cloned;
};

// random: Number.random, // Number.random

K.now = function(){
	return + new Date;
};

/**
 * bind 'this' pointer for a function
 * or bind a method for a constructor
 * @usage:
 *
   1. KM.bind(myFunction, {a:1});
   2. KM.bind('method', {a:1, method: function(){ alert(this.a) }});

 *
 *
 */
K.bind = function(fn, bind){
	return K.isFunction(fn) ?
		bind_method(fn, bind)
	:
		(bind[fn] = bind_method(bind[fn], bind));
};

/**
 * method to encapsulate the delayed function
 */
K.delay = function(fn, delay, isInterval){
	var ret = {
		start: function(){
			ret.cancel();
			return ret.id = isInterval ? setInterval(fn, delay) : setTimeout(fn, delay);
		},
		cancel: function(){
			var timer = ret.id;

			ret.id = isInterval ? clearInterval(timer) : clearTimeout(timer);
			return ret;
		}
	};

	return ret;
};

// TODO:
// improve stability
K.makeArray = function(obj){
	return K.isArray(obj) ? obj : [obj];
};

K.toQueryString = function(obj, splitter){
	return K.isObject(obj) ? toQueryString(obj, splitter) : obj;
};

/**
 * OOP Enhancement
 * --------------------------------------------------------------------------------------------- */

/**
 * overload a setter function or a setter method of a instance
 */
K._overloadSetter = overloadSetter; // overload_for_instance_method( batch_setter ),

/**
 *
 */
// _overloadInstanceMethod: overload_for_instance_method,

/**
 * run a method once and only ONCE before the real method executed
 * usefull for lazy initialization
 *
 * @example
 * if Overlay::show is the public api to show the overlay
 * but it has a initialization method, which we want to be called just before the overlay shows, not the very moment when the instance of Overlay created,
 * so,
 * we apply:
 * initialization method 	-> Overlay::_showInit
 * real show method 		-> Overlay::show
 * and then:
 *
 * @usage

	 	// before 'show', '_showInit' will be executed only once
	 	KM._onceBefore('show', '_showInit', Overlay.prototype);

 */
K._onceBefore = function(real_method_name, init_method_name, belong){
	var init = belong[init_method_name],
		real = belong[real_method_name];

	belong[real_method_name] = function(){
		init.call(this);
		real.apply(this, arguments);

		belong[real_method_name] = real;
	};

	// delete belong[init_method_name];
	//
	belong[init_method_name] = NOOP;
};

/**
 @usage

		funcion myMethod(string){....}
		var memoizedMyMethod = KM._memoize(myMethod);

 */
K._memoize = memoizeMethod; // overload_for_instance_method( memoizeMethod )

})(KM);

/**
 change log:

 2011-09-10  Kael:
 - add KM.clone to clone an object instead of Object.clone
 	fix the bug that mootools will exceede maximum call stack size when cloning a recursive object

 TODO:
 A. test memleak about cached parameter in function clone on ie

 2011-09-04  Kael:
 TODO:
 A. improve stability for KM.makeArray

 change log:
 2011-04-19  Kael:
 - add method lazyInit，fix a bug of overloadInstanceMethod
 - add method to detect the type of an object. set KM._type as semi-private method
 2011-04-15  Kael:
 - add adapter for overloadSetter,
 - add method overloadInstanceMethod
 2011-04-1   Kael Zhang: move KM.ready to web.js
 2010-12-31  Kael Zhang:
 - add KM.data and KM.delay
 - remove domready from mootools
 */<commit_msg>lang/enhance: remove KM.now method. plz use + new Date instead<commit_after>/**
 * language and OOP enhancement for non-ECMAScript5 standards
 */

;(function(K, undef){

/**
 * copy all properties in the supplier to the receiver
 * @param r {Object} receiver
 * @param s {Object} supplier
 * @param or {boolean=} whether override the existing property in the receiver
 * @param cl {(Array.<string>)=} copy list, an array of selected properties
 */
function mix(r, s, or, cl) {
	if (!s || !r) return r;
	var i = 0, c, len;
	or = or || or === undef;

	if (cl && (len = cl.length)) {
		for (; i < len; i++) {
			c = cl[i];
			if ( (c in s) && (or || !(c in r) ) ) {
				r[c] = s[c];
			}
		}
	} else {
		for (c in s) {
			if (or || !(c in r)) {
				r[c] = s[c];
			}
		}
	}
	return r;
};

// bind the this pointer of a function
function bind_method(fn, bind){
	return function(){
		return fn.apply(bind, arguments);
	}
};

/**
 * transform functions that have the signature fn(key, value)
 * to
 * functions that could accept object arguments
 * @adapter
 */
function overloadSetter(fn){

	// @return {undefined} setter method will always return this,
	// for the sake of potential chain-style invocations
	return function(key, value){
		var self = this;

		if (key || key === 0){
			if (K.isString(key)){
				fn.call(self, key, value);

			}else if (K.isObject(key)){
				K.each(key, function(v, k){
					fn.call(self, k, v);
				});
			}
		}

		return self;
	};
};

/**
 * memoize static result of a complicated method to save time
 */
function memoizeMethod(fn){
	var stack = {};

	return function(){
		var arg = array_join.call(arguments, '~^_^~');

		return (arg in stack) ? stack[arg] : (stack[arg] = fn.apply(null, arguments));
	}
};

/**
 * transform constructor functions to functions that could change a method of a instance or singleton
 */
/*
function overload_for_instance_method(fn){
	var self = this;

	return function(methodname, instance){
		var arg = arguments;

		return K.isFunction(methodname) ?
			fn.apply(self, arg)
		:	instance[methodname] = fn.call(instance, instance[methodname], instance);
	};
};
*/

function toQueryString(obj, splitter){
	var key, value, ret = [], encode = encodeURIComponent;

	for(key in obj){
		!K.isObject(value = obj[key]) && !K.isArray(value) && ret.push(key + '=' + encode(value));
	}

	return ret.join(splitter || '&');
};

/**
 * @param {mixed} o
 * @param {Object} stack
 */
function clone(o, marked, cached){
	var cloned = {}, m, id;

	// internal use
	cached || (cached = {});

	switch(K._type(o)){
		case 'date':
			return new Date(o);

		case 'array':
			cloned = [];

		// object, plainObject, instance
		case 'object':
			m = CLONE_MARKER;

			if(o[m]){
				return cached[o[m]];
			}

			id = _guid ++;

			// mark copied object to prevent duplicately cloning
			o[m] = id;
			marked[id] = o;
			cached[id] = cloned;

			K.each(o, function(value, key){
				if(key !== m){
					cloned[key] = clone(value, marked, cached);
				}
			});

			// free
			marked = cached = null;

			return cloned;

		// number, boolean, element(DOMElement, HTMLWindow, HTMLDocument, HTMLhtmlElement), collections
		// arguments?
		default:
			return o;
	}
};

var	NOOP = function(){},
	array_join = Array.prototype.join,
	CLONE_MARKER = '>_>~cloned',

	_guid = 1;

/**
 * language enhancement

 * for non-ECMAScript5 implementations, we'll add them into the KM namespace
 * and ECMAScript5 standard methods will be included in native.js
 * --------------------------------------------------------------------------------------------- */

K.mix = mix;

K.guid = function(){
	return _guid ++;
};

/**
 * forEach method for Object
 */
K.each = function(obj, fn){
	if(K.isFunction(fn)){

		if(K.isObject(obj)){
			var keys = Object.keys(obj), i = 0, len = keys.length, key;

			for(; i < len; i ++){
				key = keys[i];
				obj.hasOwnProperty(key) && fn.call(obj, obj[key], key);
			}

		}else if(K.isArray(obj)){
			obj.forEach(fn);

		}
	}
};

/**
 * deep clone an object, excluding properties on prototype chain.
 * is able to deal with recursive object, unlike the poor Object.clone of mootools
 */
K.clone = function(o) {
	var marked = {},
		m = CLONE_MARKER,
		cloned = clone(o, marked);

	// remove CLONE_MARKER
	K.each(marked, function(v){
		try{
			delete v[m];
		}catch(e){
			K.log('del CLONE_MARKER err', e);
			v[m] = undefined;
		}
	});

	marked = null;

	return cloned;
};

// random: Number.random, // Number.random

// K.now = function(){
//	return + new Date;
// };

/**
 * bind 'this' pointer for a function
 * or bind a method for a constructor
 * @usage:
 *
   1. KM.bind(myFunction, {a:1});
   2. KM.bind('method', {a:1, method: function(){ alert(this.a) }});

 *
 *
 */
K.bind = function(fn, bind){
	return K.isFunction(fn) ?
		bind_method(fn, bind)
	:
		(bind[fn] = bind_method(bind[fn], bind));
};

/**
 * method to encapsulate the delayed function
 */
K.delay = function(fn, delay, isInterval){
	var ret = {
		start: function(){
			ret.cancel();
			return ret.id = isInterval ? setInterval(fn, delay) : setTimeout(fn, delay);
		},
		cancel: function(){
			var timer = ret.id;

			ret.id = isInterval ? clearInterval(timer) : clearTimeout(timer);
			return ret;
		}
	};

	return ret;
};

// TODO:
// improve stability
K.makeArray = function(obj){
	return K.isArray(obj) ? obj : [obj];
};

K.toQueryString = function(obj, splitter){
	return K.isObject(obj) ? toQueryString(obj, splitter) : obj;
};

/**
 * OOP Enhancement
 * --------------------------------------------------------------------------------------------- */

/**
 * overload a setter function or a setter method of a instance
 */
K._overloadSetter = overloadSetter; // overload_for_instance_method( batch_setter ),

/**
 *
 */
// _overloadInstanceMethod: overload_for_instance_method,

/**
 * run a method once and only ONCE before the real method executed
 * usefull for lazy initialization
 *
 * @example
 * if Overlay::show is the public api to show the overlay
 * but it has a initialization method, which we want to be called just before the overlay shows, not the very moment when the instance of Overlay created,
 * so,
 * we apply:
 * initialization method 	-> Overlay::_showInit
 * real show method 		-> Overlay::show
 * and then:
 *
 * @usage

	 	// before 'show', '_showInit' will be executed only once
	 	KM._onceBefore('show', '_showInit', Overlay.prototype);

 */
K._onceBefore = function(real_method_name, init_method_name, belong){
	var init = belong[init_method_name],
		real = belong[real_method_name];

	belong[real_method_name] = function(){
		init.call(this);
		real.apply(this, arguments);

		belong[real_method_name] = real;
	};

	// delete belong[init_method_name];
	//
	belong[init_method_name] = NOOP;
};

/**
 @usage

		funcion myMethod(string){....}
		var memoizedMyMethod = KM._memoize(myMethod);

 */
K._memoize = memoizeMethod; // overload_for_instance_method( memoizeMethod )

})(KM);

/**
 change log:

 2011-09-10  Kael:
 - add KM.clone to clone an object instead of Object.clone
 	fix the bug that mootools will exceede maximum call stack size when cloning a recursive object

 TODO:
 A. test memleak about cached parameter in function clone on ie

 2011-09-04  Kael:
 TODO:
 A. improve stability for KM.makeArray

 change log:
 2011-04-19  Kael:
 - add method lazyInit，fix a bug of overloadInstanceMethod
 - add method to detect the type of an object. set KM._type as semi-private method
 2011-04-15  Kael:
 - add adapter for overloadSetter,
 - add method overloadInstanceMethod
 2011-04-1   Kael Zhang: move KM.ready to web.js
 2010-12-31  Kael Zhang:
 - add KM.data and KM.delay
 - remove domready from mootools
 */<|endoftext|>


<commit_before>'use strict';

var config = require('../config/config.js');
var db = require('./db.js');
var PDFDocument = require('pdfkit');

var ticket = {
  generatePdf: function(tickets) {

    var doc = new PDFDocument();
    doc.registerFont('mp-bold', 'assets/fonts/MYRIADPRO-BOLD.ttf');
    doc.registerFont('mp', 'assets/fonts/MYRIADPRO-REGULAR.ttf');

    for (var i = 0; i < tickets.length; ++i) {
      var ticket = tickets[i];
      var discount = ticket.discount_group_title;
      var showDate = ticket.show_date + ' klo ' + ticket.show_time; //'20.4.2015 klo 19:00';
      var show = ticket.show_title; //'Helsinki VI';
      var seat = ticket.section_title + ', ' + ticket.row_name + ' ' + ticket.row + ', paikka ' + ticket.seat_number; //'PERMANTO, RIVI 8, PAIKKA 154';
      var venueDescription = ticket.venue_description.split('\n');
      var venue = venueDescription[0]; //'Aleksanterin teatteri, Helsinki';
      var address = venueDescription[1]; //'Bulevardi 23-27 / Albertinkatu 32';
      if (i > 0) {
        doc.addPage();
      }
      doc.font('mp-bold')
          .fontSize(21)
          .text(config.title.toUpperCase(), 50, 80)

          .font('mp')
          .text(discount, 50, 80, {align: 'right'})

          .moveUp(0.2)
          .font('mp-bold')
          .text(show)

          .moveUp(0.2)
          .font('mp')
          .fontSize(16)
          .text(showDate)

          .moveDown(0.8)
          .font('mp-bold')
          .text(seat.toUpperCase())

          .font('mp')
          .moveDown(0.8)
          .text(venue)

          .moveUp(0.2)
          .fontSize(9)
          .text(address)
    }
    doc.end();
    return doc;
  }

};

module.exports = ticket;
<commit_msg>ticket layout<commit_after>'use strict';

var config = require('../config/config.js');
var db = require('./db.js');
var PDFDocument = require('pdfkit');

var ticket = {
  generatePdf: function(tickets) {

    var doc = new PDFDocument();
    doc.registerFont('mp-bold', 'assets/fonts/MYRIADPRO-BOLD.ttf');
    doc.registerFont('mp', 'assets/fonts/MYRIADPRO-REGULAR.ttf');

    for (var i = 0; i < tickets.length; ++i) {
      var ticket = tickets[i];
      var discount = ticket.discount_group_title;
      var showDate = ticket.show_date + ' klo ' + ticket.show_time; //'20.4.2015 klo 19:00';
      var show = ticket.show_title; //'Helsinki VI';
      var seat = ticket.section_title + ', ' + ticket.row_name + ' ' + ticket.row + ', paikka ' + ticket.seat_number; //'PERMANTO, RIVI 8, PAIKKA 154';
      var venueDescription = ticket.venue_description.split('\n');
      var venue = venueDescription[0]; //'Aleksanterin teatteri, Helsinki';
      var address = venueDescription[1]; //'Bulevardi 23-27 / Albertinkatu 32';
      if (i > 0) {
        doc.addPage();
      }
      doc.rect(30, 30, 15, 135)
          .fill([254, 240, 53]) // yellow

          .font('mp-bold')
          .fill('#000000')
          .fontSize(21)
          .text(config.title.toUpperCase(), 60, 30)

          .font('mp')
          .text(discount, 60, 30, {align: 'right'})

          .moveUp(0.2)
          .font('mp-bold')
          .text(show)

          .moveUp(0.2)
          .font('mp')
          .fontSize(16)
          .text(showDate)

          .moveDown(0.8)
          .font('mp-bold')
          .text(seat.toUpperCase())

          .moveDown(0.8)
          .font('mp')
          .text(venue)

          .moveUp(0.2)
          .fontSize(9)
          .text(address)
    }
    doc.end();
    return doc;
  }

};

module.exports = ticket;
<|endoftext|>


<commit_before>/**
 * Developer: Stepan Burguchev
 * Date: 6/26/2015
 * Copyright: 2009-2015 Comindware®
 *       All Rights Reserved
 *
 * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF Comindware
 *       The copyright notice above does not evidence any
 *       actual or intended publication of such source code.
 */

/* global define, require, Handlebars, Backbone, Marionette, $, _, Localizer */

define([
        'module/lib',
        'core/utils/utilsApi',
        './routing/ModuleProxy',
        'core/application/views/ContentLoadingView',
        'module/moduleConfigs',
        'project/module/moduleConfigs',
        'process/module/moduleConfigs'
    ],
    function (lib, utilsApi, ModuleProxy, ContentLoadingView, moduleConfigs, projectModuleConfigs, processModuleConfigs) {
        'use strict';

        // storing active url to get back to it while canceling module leave
        var previousUrl;
        var activeUrl;
        var originalCheckUrl = Backbone.history.checkUrl;
        Backbone.history.checkUrl = function (e) {
            previousUrl = activeUrl;
            activeUrl = window.location.hash;
            originalCheckUrl.apply(this, arguments);
        };

        var configs = _.flatten([ moduleConfigs, projectModuleConfigs, processModuleConfigs ]);

        var activeModule = null;
        var loadingContext = null;
        var thisOptions = null;
        var router;

        var __registerDefaultRoute = function () {
            var DefaultRouter = Marionette.AppRouter.extend({
                routes: {
                    "": "defaultRoute"
                },
                defaultRoute: function () {
                    routingService.navigateToUrl(thisOptions.defaultUrl, { replace: true });
                }
            });
            router = new DefaultRouter();
        };

        var __onModuleLoading = function (callbackName, routingArgs, config) {
            loadingContext = {
                config: config,
                leavingPromise: null,
                loaded: false
            };
            if (!activeModule) {
                window.application.contentLoadingRegion.show(new ContentLoadingView());
            } else {
                loadingContext.leavingPromise = Promise.resolve(activeModule.leave());
                loadingContext.leavingPromise.then(function (canLeave) {
                    if (!canLeave) {
                        // getting back to last url
                        routingService.navigateToUrl(previousUrl, { replace: true, trigger: false });
                        return;
                    }
                    if (!loadingContext.loaded) {
                        activeModule.view.setModuleLoading(true);
                    }
                }.bind(this));
            }
        };

        var __onModuleLoaded = function (callbackName, routingArgs, config, Module) {
            // reject race condition
            if (loadingContext === null || loadingContext.config.module !== config.module) {
                return;
            }

            loadingContext.loaded = true;
            Promise.resolve(loadingContext.leavingPromise ? loadingContext.leavingPromise : true).then(function (canLeave) {
                if (!canLeave) {
                    return;
                }

                // reset loading region
                window.application.contentLoadingRegion.reset();
                if (activeModule) {
                    activeModule.view.setModuleLoading(false);
                }
                var movingOut = activeModule && activeModule.options.config.module !== config.module;

                // destroy active module
                if (activeModule && movingOut) {
                    activeModule.destroy();
                }

                // construct new module
                if (!activeModule || movingOut) {
                    activeModule = new Module({
                        config: config,
                        region: window.application.contentRegion
                    });
                }

                // navigate to new module
                loadingContext = null;
                if (activeModule.onRoute) {
                    activeModule.onRoute.apply(activeModule, routingArgs);
                }
                var routingCallback = activeModule[callbackName];
                if (!routingCallback) {
                    var moduleId = config.id || config.module;
                    utilsApi.helpers.throwError(
                        'Failed to find callback method `' + callbackName + '` for the module `' + moduleId + '`.');
                }
                routingCallback.apply(activeModule, routingArgs);
            }.bind(this));
        };

        var routingService = {
            initialize: function (options) {
                utilsApi.helpers.ensureOption(options, 'defaultUrl');
                thisOptions = options;
                _.each(configs, function (config) {
                    var moduleProxy = new ModuleProxy({
                        config: config
                    });
                    moduleProxy.on('module:loading', __onModuleLoading);
                    moduleProxy.on('module:loaded', __onModuleLoaded);
                    new Marionette.AppRouter({
                        controller: moduleProxy,
                        appRoutes: config.routes
                    });
                }, this);

                __registerDefaultRoute();
                Backbone.history.start();
            },

            // options: replace (history), trigger (routing)
            navigateToUrl: function (url, options) {
                options = options || {};
                if (options.trigger === undefined) {
                    options.trigger = true;
                }
                router.navigate(url, options);
            },

            logout: function () {
                Promise.resolve(Ajax.Home.Logout()).then(function () {
                    window.location = "/Home/Login";
                });
            }
        };
        return routingService;
    });
<commit_msg>bug/198216<commit_after>/**
 * Developer: Stepan Burguchev
 * Date: 6/26/2015
 * Copyright: 2009-2015 Comindware®
 *       All Rights Reserved
 *
 * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF Comindware
 *       The copyright notice above does not evidence any
 *       actual or intended publication of such source code.
 */

/* global define, require, Handlebars, Backbone, Marionette, $, _, Localizer */

define([
        'module/lib',
        'core/utils/utilsApi',
        './routing/ModuleProxy',
        'core/application/views/ContentLoadingView',
        'module/moduleConfigs',
        'project/module/moduleConfigs',
        'process/module/moduleConfigs'
    ],
    function (lib, utilsApi, ModuleProxy, ContentLoadingView, moduleConfigs, projectModuleConfigs, processModuleConfigs) {
        'use strict';

        // storing active url to get back to it while canceling module leave
        var previousUrl;
        var activeUrl;
        var originalCheckUrl = Backbone.history.checkUrl;
        Backbone.history.checkUrl = function (e) {
            previousUrl = activeUrl;
            activeUrl = window.location.hash;
            originalCheckUrl.apply(this, arguments);
        };

        var configs = _.flatten([ moduleConfigs, projectModuleConfigs, processModuleConfigs ]);

        var activeModule = null;
        var loadingContext = null;
        var thisOptions = null;
        var router;

        var __registerDefaultRoute = function () {
            var DefaultRouter = Marionette.AppRouter.extend({
                routes: {
                    "": "defaultRoute"
                },
                defaultRoute: function () {
                    routingService.navigateToUrl(thisOptions.defaultUrl, { replace: true });
                }
            });
            router = new DefaultRouter();
        };

        var __onModuleLoading = function (callbackName, routingArgs, config) {
            loadingContext = {
                config: config,
                leavingPromise: null,
                loaded: false
            };
            if (!activeModule) {
                window.application.contentLoadingRegion.show(new ContentLoadingView());
            } else {
                loadingContext.leavingPromise = Promise.resolve(activeModule.leave());
                loadingContext.leavingPromise.then(function (canLeave) {
                    if (!canLeave) {
                        // getting back to last url
                        routingService.navigateToUrl(previousUrl, { replace: true, trigger: false });
                        return;
                    }
                    if (!loadingContext.loaded) {
                        activeModule.view.setModuleLoading(true);
                    }
                }.bind(this));
            }
        };

        var __onModuleLoaded = function (callbackName, routingArgs, config, Module) {
            // reject race condition
            if (loadingContext === null || loadingContext.config.module !== config.module) {
                return;
            }

            loadingContext.loaded = true;
            Promise.resolve(loadingContext.leavingPromise ? loadingContext.leavingPromise : true).then(function (canLeave) {
                if (!canLeave) {
                    return;
                }

                // reset loading region
                window.application.contentLoadingRegion.reset();
                if (activeModule) {
                    activeModule.view.setModuleLoading(false);
                }
                var movingOut = activeModule && activeModule.options.config.module !== config.module;

                // destroy active module
                if (activeModule && movingOut) {
                    activeModule.destroy();
                }

                // construct new module
                if (!activeModule || movingOut) {
                    activeModule = new Module({
                        config: config,
                        region: window.application.contentRegion
                    });
                }

                // navigate to new module
                loadingContext = null;
                if (activeModule.onRoute) {
                    activeModule.onRoute.apply(activeModule, routingArgs);
                }
                var routingCallback = activeModule[callbackName];
                if (!routingCallback) {
                    var moduleId = config.id || config.module;
                    utilsApi.helpers.throwError(
                        'Failed to find callback method `' + callbackName + '` for the module `' + moduleId + '`.');
                }
                routingCallback.apply(activeModule, routingArgs);
            }.bind(this));
        };

        var routingService = {
            initialize: function (options) {
                utilsApi.helpers.ensureOption(options, 'defaultUrl');
                thisOptions = options;
                _.each(configs, function (config) {
                    var moduleProxy = new ModuleProxy({
                        config: config
                    });
                    moduleProxy.on('module:loading', __onModuleLoading);
                    moduleProxy.on('module:loaded', __onModuleLoaded);
                    new Marionette.AppRouter({
                        controller: moduleProxy,
                        appRoutes: config.routes
                    });
                }, this);

                __registerDefaultRoute();
                Backbone.history.start();
            },

            // options: replace (history), trigger (routing)
            navigateToUrl: function (url, options) {
                options = options || {};
                if (options.trigger === undefined) {
                    options.trigger = true;
                }
                router.navigate(url, options);
            },

            logout: function () {
                Promise.resolve(Ajax.Home.Logout()).then(function () {
                    window.location = "";
                });
            }
        };
        return routingService;
    });
<|endoftext|>


<commit_before>/** Editor UI for modern browsers that support contentEditable=true fields.
 *
 * This works on pretty much everything we target. Except for Victor's iPad.
 *
 * The options object should have the following properties:
 *   inputElement:: textarea for capturing events
 *   formSubmitter:: used to submit a form when the user presses Enter
 *   tokenizer:: conforms to the NextEditor.Tokenizer interface for deciding
 *               which parts of the text get highlighted
 */
NextEditor.UI.Fire = function(options) {
  this.inputElement = options.inputElement;
  if (!this.inputElement) {
    window.console && console.error("No input elment given! noop");
    return;
  }
  this.tokenizer = options.tokenizer;
  if (!this.tokenizer) {
    window.console && console.error("No tokenizer given! noop");
    return;
  }

  this.formSubmitter = options.formSubmitter;
  this.buildEditor();
};

/** The textarea or input backing the element's contents. */
NextEditor.UI.Fire.prototype.inputElement = null;

/** The form to be submitted when the user presses Enter. */
NextEditor.UI.Fire.prototype.formElement = null;

/** The DOM element with contentEditable=true. */
NextEditor.UI.Fire.prototype.editorElement = null;

/** Constructs the editor DOM UI. */
NextEditor.UI.Fire.prototype.buildEditor = function() {
  var inputClass = this.inputElement.className;
  this.inputElement.className = '';
  this.inputElement.style.visibility = 'hidden';
  this.inputElement.style.position = 'absolute';
  this.inputElement.style.width = 0;
  this.inputElement.style.height = 0;

  this.editorElement = document.createElement('div');
  this.editorElement.className = inputClass;
  $(this.editorElement).attr('contentEditable', 'true');
  $(this.inputElement).before(this.editorElement);

  var text = $(this.inputElement).attr('value');
  var tokens = this.tokenizer.tokenize(text + "\n");
  var cursor = (document.activeElement == this.editorElement) ?
               text.length : null;

  var domData = NextEditor.DOM.buildDom(tokens, text.length);
  this.setEditorContent(domData);
};

/** The contents of the editor element last time we did highlighting. */
NextEditor.UI.Fire.prototype.oldContent = null;

/** Parses the editor content to make it nice, only if it changed. */
NextEditor.UI.Fire.prototype.onPossibleChange = function() {
  var htmlContent = this.editorElement.innerHTML;
  if (this.oldContent == htmlContent) return;

  var selection = window.getSelection();
  var content = NextEditor.DOM.elementContent(this.editorElement, selection);

  // Always have a newline at the end, to appease Firefox. Never allow the
  // cursor to be set there.
  if (content.text[content.text.length - 1] != "\n") {
    content.text += "\n";
  }
  if (content.cursor == content.length) {
    content.cursor = content.length - 1;
  }

  var tokens = this.tokenizer.tokenize(content.text);
  var domData = NextEditor.DOM.buildDom(tokens, content.cursor);

  if (domData.cursorOffset != null) {
    this.setEditorContent(domData);
    this.oldContent = this.editorElement.innerHTML;
    // Strip the newline off the value.
    $(this.inputElement).attr('value',
        content.text.substr(0, content.text.length - 1));
  }
};

/** Updates the editor UI to reflect content change
 *
 * Args:
 *   domData:: the new DOM contents and selection information for the editor UI
 */
NextEditor.UI.Fire.prototype.setEditorContent = function(domData) {
  this.editorElement.innerHTML = '';
  for (var i = 0; i < domData.nodes.length; i++) {
    this.editorElement.appendChild(domData.nodes[i]);
  }

  if (domData.cursorOffset != null) {
    var range = document.createRange();
    var node = domData.cursorNode || this.editorElement;
    range.setStart(node, domData.cursorOffset);
    range.setEnd(node, domData.cursorOffset);

    var selection = window.getSelection();
    selection.removeAllRanges();
    selection.addRange(range);
  }
};

/** Submits the editor's form if the user presses Enter. */
NextEditor.UI.Fire.prototype.onSubmitKey = function() {
  this.formSubmitter.submit();
};

/** The DOM element receiving user input events. */
NextEditor.UI.Fire.prototype.eventSource = function() {
  return this.editorElement;
}

/** True if no change events should be generated when an IME UI is active. */
NextEditor.UI.Fire.prototype.needsImeSupport = function() {
  return true;
}
<commit_msg>Workaround annoying Firefox resize/move controls in the Fire UI.<commit_after>/** Editor UI for modern browsers that support contentEditable=true fields.
 *
 * This works on pretty much everything we target. Except for Victor's iPad.
 *
 * The options object should have the following properties:
 *   inputElement:: textarea for capturing events
 *   formSubmitter:: used to submit a form when the user presses Enter
 *   tokenizer:: conforms to the NextEditor.Tokenizer interface for deciding
 *               which parts of the text get highlighted
 */
NextEditor.UI.Fire = function(options) {
  this.inputElement = options.inputElement;
  if (!this.inputElement) {
    window.console && console.error("No input elment given! noop");
    return;
  }
  this.tokenizer = options.tokenizer;
  if (!this.tokenizer) {
    window.console && console.error("No tokenizer given! noop");
    return;
  }

  this.formSubmitter = options.formSubmitter;
  this.buildEditor();
};

/** The textarea or input backing the element's contents. */
NextEditor.UI.Fire.prototype.inputElement = null;

/** The form to be submitted when the user presses Enter. */
NextEditor.UI.Fire.prototype.formElement = null;

/** The DOM element with contentEditable=true. */
NextEditor.UI.Fire.prototype.editorElement = null;

/** Constructs the editor DOM UI. */
NextEditor.UI.Fire.prototype.buildEditor = function() {
  var inputClass = this.inputElement.className;
  this.inputElement.className = '';
  this.inputElement.style.visibility = 'hidden';
  this.inputElement.style.position = 'absolute';
  this.inputElement.style.width = 0;
  this.inputElement.style.height = 0;

  this.editorElement = document.createElement('div');
  this.editorElement.style.width = this.editorElement.style.height = '100%';
  this.editorElement.style.margin = '0';
  this.editorElement.style.padding = '0';
  this.editorElement.style.border = 'none';
  $(this.editorElement).attr('contentEditable', 'true');

  // Workaround Firefox bug that shows resizing and moving controls for
  // contentEditable=true elements if they have position: absolute.
  // https://bugzilla.mozilla.org/show_bug.cgi?id=531159
  var wrapper = document.createElement('div');
  wrapper.className = inputClass;
  $(this.inputElement).before(wrapper);
  wrapper.appendChild(this.editorElement);
  if (document.queryCommandEnabled('enableObjectResizing')) {
    document.execCommand('enableObjectResizing', false, 'false');
  }

  var text = $(this.inputElement).attr('value');
  var tokens = this.tokenizer.tokenize(text + "\n");
  var cursor = (document.activeElement == this.editorElement) ?
               text.length : null;

  var domData = NextEditor.DOM.buildDom(tokens, text.length);
  this.setEditorContent(domData);
};

/** The contents of the editor element last time we did highlighting. */
NextEditor.UI.Fire.prototype.oldContent = null;

/** Parses the editor content to make it nice, only if it changed. */
NextEditor.UI.Fire.prototype.onPossibleChange = function() {
  var htmlContent = this.editorElement.innerHTML;
  if (this.oldContent == htmlContent) return;

  var selection = window.getSelection();
  var content = NextEditor.DOM.elementContent(this.editorElement, selection);

  // Always have a newline at the end, to appease Firefox. Never allow the
  // cursor to be set there.
  if (content.text[content.text.length - 1] != "\n") {
    content.text += "\n";
  }
  if (content.cursor == content.length) {
    content.cursor = content.length - 1;
  }

  var tokens = this.tokenizer.tokenize(content.text);
  var domData = NextEditor.DOM.buildDom(tokens, content.cursor);

  if (domData.cursorOffset != null) {
    this.setEditorContent(domData);
    this.oldContent = this.editorElement.innerHTML;
    // Strip the newline off the value.
    $(this.inputElement).attr('value',
        content.text.substr(0, content.text.length - 1));
  }
};

/** Updates the editor UI to reflect content change
 *
 * Args:
 *   domData:: the new DOM contents and selection information for the editor UI
 */
NextEditor.UI.Fire.prototype.setEditorContent = function(domData) {
  this.editorElement.innerHTML = '';
  for (var i = 0; i < domData.nodes.length; i++) {
    this.editorElement.appendChild(domData.nodes[i]);
  }

  if (domData.cursorOffset != null) {
    var range = document.createRange();
    var node = domData.cursorNode || this.editorElement;
    range.setStart(node, domData.cursorOffset);
    range.setEnd(node, domData.cursorOffset);

    var selection = window.getSelection();
    selection.removeAllRanges();
    selection.addRange(range);
  }
};

/** Submits the editor's form if the user presses Enter. */
NextEditor.UI.Fire.prototype.onSubmitKey = function() {
  this.formSubmitter.submit();
};

/** The DOM element receiving user input events. */
NextEditor.UI.Fire.prototype.eventSource = function() {
  return this.editorElement;
}

/** True if no change events should be generated when an IME UI is active. */
NextEditor.UI.Fire.prototype.needsImeSupport = function() {
  return true;
}
<|endoftext|>


<commit_before>var olaMundo = function olaMundo(){
  console.log('Olá Mundo');

}

olaMundo();

var outro= olaMundo;

outro();

olaMundo= 'blah';

outro();

console.log(olaMundo);

function executadorDeFuncao(fcn){
  fcn('Executador de funcao');
}

function blah1(str){
  console.log(str+' blah1');
}

function blah2(str){
  console.log(str+' blah2');
}

executadorDeFuncao(blah1);
executadorDeFuncao(blah2);

function derivar(fcn){
  var deltax=0.0000000001;
  function derivada(x){
    return (fcn(x+deltax)-fcn(x))/deltax;
  }

  return derivada;
}

function reta(x){
  return x;
}

function parabola(x){
  return x*x;
}

var parabolaDerivada=derivar(parabola);

console.log(parabolaDerivada(1));
console.log(parabolaDerivada(2));

//var retaTransladada=derivar(reta);
//
//console.log(retaTransladada(1));
//console.log(retaTransladada(2));<commit_msg>Objeto Javascript<commit_after>var olaMundo = function olaMundo(){
  console.log('Olá Mundo');

}

olaMundo();

var outro= olaMundo;

outro();

olaMundo= 'blah';

outro();

console.log(olaMundo);

function executadorDeFuncao(fcn){
  fcn('Executador de funcao');
}

function blah1(str){
  console.log(str+' blah1');
}

function blah2(str){
  console.log(str+' blah2');
}

executadorDeFuncao(blah1);
executadorDeFuncao(blah2);

function derivar(fcn){
  var deltax=0.0000000001;
  function derivada(x){
    return (fcn(x+deltax)-fcn(x))/deltax;
  }

  return derivada;
}

function reta(x){
  return x;
}

function parabola(x){
  return x*x;
}

var parabolaDerivada=derivar(parabola);

console.log(parabolaDerivada(1));
console.log(parabolaDerivada(2));

var obj = {'a': 1, b: ['Renzo', 'Nuccitelli'], 1:{}};

console.log(obj);
console.log(obj.a);
console.log(obj.b);
console.log(obj[1]);
console.log(obj['b']);

//var retaTransladada=derivar(reta);
//
//console.log(retaTransladada(1));
//console.log(retaTransladada(2));<|endoftext|>


<commit_before>var assert = require("assert");
var types = require("../main");
var getFieldNames = types.getFieldNames;
var getFieldValue = types.getFieldValue;
var Node = types.namedTypes.Node;
var isArray = types.builtInTypes.array;
var isObject = types.builtInTypes.object;
var isDate = types.builtInTypes.Date;
var isRegExp = types.builtInTypes.RegExp;
var hasOwn = Object.prototype.hasOwnProperty;

function astNodesAreEquivalent(a, b, problemPath) {
    Node.assert(a);
    Node.assert(b);

    if (isArray.check(problemPath)) {
        problemPath.length = 0;
    } else {
        problemPath = null;
    }

    return areEquivalent(a, b, problemPath);
}

astNodesAreEquivalent.assert = function(a, b) {
    var problemPath = [];
    if (!astNodesAreEquivalent(a, b, problemPath)) {
        assert.ok(false, ("Nodes differ in the following path: " +
                          JSON.stringify(problemPath)));
    }
};

function areEquivalent(a, b, problemPath) {
    if (a === b) {
        return true;
    }

    if (isArray.check(a)) {
        return arraysAreEquivalent(a, b, problemPath);
    }

    if (isObject.check(a)) {
        return objectsAreEquivalent(a, b, problemPath);
    }

    if (isDate.check(a)) {
        return isDate.check(b) && (+a === +b);
    }

    if (isRegExp.check(a)) {
        return isRegExp.check(b) && (
            a.source === b.source &&
            a.global === b.global &&
            a.multiline === b.multiline &&
            a.ignoreCase === b.ignoreCase
        );
    }

    return false;
}

function arraysAreEquivalent(a, b, problemPath) {
    isArray.assert(a);
    var aLength = a.length;

    if (!isArray.check(b) || b.length !== aLength) {
        if (problemPath) {
            problemPath.push("length");
        }
        return false;
    }

    for (var i = 0; i < aLength; ++i) {
        if (problemPath) {
            problemPath.push(i);
        }

        if (i in a !== i in b) {
            return false;
        }

        if (!areEquivalent(a[i], b[i], problemPath)) {
            return false;
        }

        if (problemPath) {
            assert.strictEqual(problemPath.pop(), i);
        }
    }

    return true;
}

function objectsAreEquivalent(a, b, problemPath) {
    isObject.assert(a);
    if (!isObject.check(b)) {
        return false;
    }

    // Fast path for a common property of AST nodes.
    if (a.type !== b.type) {
        if (problemPath) {
            problemPath.push("type");
        }
        return false;
    }

    var aNames = getFieldNames(a);
    var aNameCount = aNames.length;

    var bNames = getFieldNames(b);
    var bNameCount = bNames.length;

    if (aNameCount === bNameCount) {
        for (var i = 0; i < aNameCount; ++i) {
            var name = aNames[i];
            var aChild = getFieldValue(a, name);
            var bChild = getFieldValue(b, name);

            if (problemPath) {
                problemPath.push(name);
            }

            if (!areEquivalent(aChild, bChild, problemPath)) {
                return false;
            }

            if (problemPath) {
                assert.strictEqual(problemPath.pop(), name);
            }
        }

        return true;
    }

    if (!problemPath) {
        return false;
    }

    // Since aNameCount !== bNameCount, we need to find some name that's
    // missing in aNames but present in bNames, or vice-versa.

    var seenNames = Object.create(null);

    for (i = 0; i < aNameCount; ++i) {
        seenNames[aNames[i]] = true;
    }

    for (i = 0; i < bNameCount; ++i) {
        name = bNames[i];

        if (!hasOwn.call(seenNames, name)) {
            problemPath.push(name);
            return false;
        }

        delete seenNames[name];
    }

    for (name in seenNames) {
        problemPath.push(name);
        break;
    }

    return false;
}

module.exports = astNodesAreEquivalent;
<commit_msg>Print problem paths more readably.<commit_after>var assert = require("assert");
var types = require("../main");
var getFieldNames = types.getFieldNames;
var getFieldValue = types.getFieldValue;
var Node = types.namedTypes.Node;
var isArray = types.builtInTypes.array;
var isObject = types.builtInTypes.object;
var isDate = types.builtInTypes.Date;
var isRegExp = types.builtInTypes.RegExp;
var hasOwn = Object.prototype.hasOwnProperty;

function astNodesAreEquivalent(a, b, problemPath) {
    Node.assert(a);
    Node.assert(b);

    if (isArray.check(problemPath)) {
        problemPath.length = 0;
    } else {
        problemPath = null;
    }

    return areEquivalent(a, b, problemPath);
}

astNodesAreEquivalent.assert = function(a, b) {
    var problemPath = [];
    if (!astNodesAreEquivalent(a, b, problemPath)) {
        assert.ok(false, ("Nodes differ in the following path: " +
                          problemPath.map(subscriptForProperty).join("")));
    }
};

function subscriptForProperty(property) {
    if (/[_$a-z][_$a-z0-9]*/i.test(property)) {
        return "." + property;
    }
    return "[" + JSON.stringify(property) + "]";
}

function areEquivalent(a, b, problemPath) {
    if (a === b) {
        return true;
    }

    if (isArray.check(a)) {
        return arraysAreEquivalent(a, b, problemPath);
    }

    if (isObject.check(a)) {
        return objectsAreEquivalent(a, b, problemPath);
    }

    if (isDate.check(a)) {
        return isDate.check(b) && (+a === +b);
    }

    if (isRegExp.check(a)) {
        return isRegExp.check(b) && (
            a.source === b.source &&
            a.global === b.global &&
            a.multiline === b.multiline &&
            a.ignoreCase === b.ignoreCase
        );
    }

    return false;
}

function arraysAreEquivalent(a, b, problemPath) {
    isArray.assert(a);
    var aLength = a.length;

    if (!isArray.check(b) || b.length !== aLength) {
        if (problemPath) {
            problemPath.push("length");
        }
        return false;
    }

    for (var i = 0; i < aLength; ++i) {
        if (problemPath) {
            problemPath.push(i);
        }

        if (i in a !== i in b) {
            return false;
        }

        if (!areEquivalent(a[i], b[i], problemPath)) {
            return false;
        }

        if (problemPath) {
            assert.strictEqual(problemPath.pop(), i);
        }
    }

    return true;
}

function objectsAreEquivalent(a, b, problemPath) {
    isObject.assert(a);
    if (!isObject.check(b)) {
        return false;
    }

    // Fast path for a common property of AST nodes.
    if (a.type !== b.type) {
        if (problemPath) {
            problemPath.push("type");
        }
        return false;
    }

    var aNames = getFieldNames(a);
    var aNameCount = aNames.length;

    var bNames = getFieldNames(b);
    var bNameCount = bNames.length;

    if (aNameCount === bNameCount) {
        for (var i = 0; i < aNameCount; ++i) {
            var name = aNames[i];
            var aChild = getFieldValue(a, name);
            var bChild = getFieldValue(b, name);

            if (problemPath) {
                problemPath.push(name);
            }

            if (!areEquivalent(aChild, bChild, problemPath)) {
                return false;
            }

            if (problemPath) {
                assert.strictEqual(problemPath.pop(), name);
            }
        }

        return true;
    }

    if (!problemPath) {
        return false;
    }

    // Since aNameCount !== bNameCount, we need to find some name that's
    // missing in aNames but present in bNames, or vice-versa.

    var seenNames = Object.create(null);

    for (i = 0; i < aNameCount; ++i) {
        seenNames[aNames[i]] = true;
    }

    for (i = 0; i < bNameCount; ++i) {
        name = bNames[i];

        if (!hasOwn.call(seenNames, name)) {
            problemPath.push(name);
            return false;
        }

        delete seenNames[name];
    }

    for (name in seenNames) {
        problemPath.push(name);
        break;
    }

    return false;
}

module.exports = astNodesAreEquivalent;
<|endoftext|>


<commit_before>var http = require('http'),
  _ = require('underscore'),
  updateTimer;
var sync = require('synchronize')

function JenkinsButler(options) {
  var self = this;

  self.options = options || {};
  self.host = self.options.host || null;
  if (!self.host) throw new Error('JenkinsButler: No Jenkins host provided.');

  self.port = self.options.port || null;
  if (!self.port) throw new Error('JenkinsButler: No Jenkins port provided.');

  self.username = self.options.username || null;
  if (!self.username) throw new Error('JenkinsButler: No username provided.');

  self.token = self.options.token || null;
  if (!self.token) throw new Error('JenkinsButler: No token provided.');

  self.jobs = self.options.jobs || null;
  if (!self.jobs) throw new Error('JenkinsButler: No jobs provided.');

  self.updateIntervall = self.options.updateIntervall || null;
}

JenkinsButler.prototype.buildRequestOptions = function(job) {
  var options = {
    hostname: this.host,
    port: this.port,
    path: '/job/' + job.job + '/lastBuild/api/json?token=' + this.token,
    headers: {
      'Authorization': 'Basic ' + new Buffer(this.username + ':' + this.token).toString('base64')
    }
  };
  return options;
}

JenkinsButler.prototype.getJobStatus = function(job, callback) {
  console.log('get status ' + JSON.stringify(job));

  http.get(this.buildRequestOptions(job), function(res) {

    if (res.statusCode != 200) {
      callback('Failed to fetch jenkins data, http status: ' + res.statusCode);
      return;
    }

    var response = '';

    res.on('data', function(data) {
      response += data;
    });

    res.on('end', function(){
      var resi = JSON.parse(response);
      callback(null, resi.building ? "BUILDING" : resi.result);
    })

  }).on('error', function(e) {
    console.error('Error: ' + e);
    callback(e);
    return;
  }).on('end', function(e) {
    console.error('End:' + e);
    callback(e);
    return;
  });
}

function updateStatesOfJobs(options) {
  console.log('update status from all jobs');

  for(var i = 0; i < butler.jobs.length; i++) {

  //}
  //butler.jobs.forEach(function(job) {
    sync.fiber(function() {
      butler.getJobStatus(job, function(err, result) {
        console.log('Result of ' + job.job + ' is ' + JSON.stringify(result));

        if (!err) {
          sync.fiber(function() {
            setLEDForJob(job, result, options, sync.defer())
          });
        } else {
          console.log("ERROR: " + err);
        }
      });
    });
  }
}

function setLEDForJob(job, result, options, callback) {
  console.log ("set led for " + job);
  setTimeout(function(){
    switch (result) {
      case "UNSTABLE":
        http.get(buildLedRequestOptions(options, job, options.leds.unstable)).on('error', onRequestError).on('end', callback);
        break;
      case "FAILURE":
        http.get(buildLedRequestOptions(options, job, options.leds.failure)).on('error', onRequestError).on('end', callback);
        break;
      case "SUCCESS":
        http.get(buildLedRequestOptions(options, job, options.leds.success)).on('error', onRequestError).on('end', callback);
        break;
      case "ABORTED":
        http.get(buildLedRequestOptions(options, job, options.leds.aborted)).on('error', onRequestError).on('end', callback);
        break;
      case "BUILDING":
        http.get(buildLedRequestOptions(options, job, options.leds.building)).on('error', onRequestError).on('end', callback);
        break;
      default:
        console.log('something is happen... Request: ' + JSON.stringify(option) + " JOB: " + JSON.stringify(job))
        http.get(buildLedRequestOptions(options, job, "000000")).on('error', onRequestError).on('end', callback);
    }
  }, 1000);
}

function onRequestError(err) {
  console.log("Got error: " + err.message);
}

function buildLedRequestOptions(options, job, color) {
  return {
    hostname: options.leds.host,
    port: options.leds.port,
    path: '/led/from/' + job.leds.start + '/to/' + job.leds.end + '/fill/' + color
  };
}

// function buildLedRequestOptionsPost(options) {
//   return {
//     hostname: options.leds.host,
//     port: options.leds.port,
//     method: "POST",
//     path: "/api/range",
//     headers: {
//       'Content-Type': "application/json"
//     }
//   };
// }
//
// function makeLedsShining(start, end, color, options) {
//   req = http.request(buildLedRequestOptionsPost(options));
//
//   req.on('error', function(e) {
//     console.log('problem with request: ' + e.message);
//   });
//
//   var post_data = JSON.stringify({
//     "from": start,
//     "to": end,
//     "rgb": color
//   });
//
//   req.write(post_data);
//   req.end();
// }

function JenkinsButlerService(options) {

}

JenkinsButlerService.prototype.setup = function(config) {
  butler = new JenkinsButler(config.jenkins);
  updateStatesOfJobs(config);
  updateTimer = setInterval(updateStatesOfJobs, config.jenkins.updateIntervall * 1000, config);
}

JenkinsButlerService.prototype.shutdown = function(config) {
  if (updateTimer) {
    console.log('JenkinsButlerService shutdown...')
    clearInterval(updateTimer);

    http.get({
      hostname: config.leds.host,
      port: config.leds.port,
      path: '/api/black'
    }, function(res) {
      console.log("Result: " + res.statusCode)
    });
  }
}

exports = module.exports = new JenkinsButlerService();
exports.JenkinsButler = JenkinsButler;
exports.ServiceName = 'JenkinsButlerService';
<commit_msg>Update jenkins-butler.js<commit_after>var http = require('http'),
  _ = require('underscore'),
  updateTimer;
var sync = require('synchronize')

function JenkinsButler(options) {
  var self = this;

  self.options = options || {};
  self.host = self.options.host || null;
  if (!self.host) throw new Error('JenkinsButler: No Jenkins host provided.');

  self.port = self.options.port || null;
  if (!self.port) throw new Error('JenkinsButler: No Jenkins port provided.');

  self.username = self.options.username || null;
  if (!self.username) throw new Error('JenkinsButler: No username provided.');

  self.token = self.options.token || null;
  if (!self.token) throw new Error('JenkinsButler: No token provided.');

  self.jobs = self.options.jobs || null;
  if (!self.jobs) throw new Error('JenkinsButler: No jobs provided.');

  self.updateIntervall = self.options.updateIntervall || null;
}

JenkinsButler.prototype.buildRequestOptions = function(job) {
  var options = {
    hostname: this.host,
    port: this.port,
    path: '/job/' + job.job + '/lastBuild/api/json?token=' + this.token,
    headers: {
      'Authorization': 'Basic ' + new Buffer(this.username + ':' + this.token).toString('base64')
    }
  };
  return options;
}

JenkinsButler.prototype.getJobStatus = function(job, callback) {
  console.log('get status ' + JSON.stringify(job));

  http.get(this.buildRequestOptions(job), function(res) {

    if (res.statusCode != 200) {
      callback('Failed to fetch jenkins data, http status: ' + res.statusCode);
      return;
    }

    var response = '';

    res.on('data', function(data) {
      response += data;
    });

    res.on('end', function(){
      var resi = JSON.parse(response);
      callback(null, resi.building ? "BUILDING" : resi.result);
    })

  }).on('error', function(e) {
    console.error('Error: ' + e);
    callback(e);
    return;
  }).on('end', function(e) {
    console.error('End:' + e);
    callback(e);
    return;
  });
}

function updateStatesOfJobs(options) {
  console.log('update status from all jobs');

  for(var i = 0; i < butler.jobs.length; i++) {

  //}
  //butler.jobs.forEach(function(job) {
    sync.fiber(function() {
      butler.getJobStatus(job, function(err, result) {
        console.log('Result of ' + job.job + ' is ' + JSON.stringify(result));

        if (!err) {
          sync.fiber(function() {
            setLEDForJob(job, result, options, sync.defer())
          });
        } else {
          console.log("ERROR: " + err);
        }
      });
    });
  }
}

function setLEDForJob(job, result, options, callback) {
  console.log ("set led for " + job);
  setTimeout(function(){
    switch (result) {
      case "UNSTABLE":
        http.get(buildLedRequestOptions(options, job, options.leds.unstable)).on('error', onRequestError).on('end', callback);
        break;
      case "FAILURE":
        http.get(buildLedRequestOptions(options, job, options.leds.failed)).on('error', onRequestError).on('end', callback);
        break;
      case "SUCCESS":
        http.get(buildLedRequestOptions(options, job, options.leds.success)).on('error', onRequestError).on('end', callback);
        break;
      case "ABORTED":
        http.get(buildLedRequestOptions(options, job, options.leds.aborted)).on('error', onRequestError).on('end', callback);
        break;
      case "BUILDING":
        http.get(buildLedRequestOptions(options, job, options.leds.building)).on('error', onRequestError).on('end', callback);
        break;
      default:
        console.log('something is happen... Request: ' + JSON.stringify(option) + " JOB: " + JSON.stringify(job))
        http.get(buildLedRequestOptions(options, job, "000000")).on('error', onRequestError).on('end', callback);
    }
  }, 1000);
}

function onRequestError(err) {
  console.log("Got error: " + err.message);
}

function buildLedRequestOptions(options, job, color) {
  return {
    hostname: options.leds.host,
    port: options.leds.port,
    path: '/led/from/' + job.leds.start + '/to/' + job.leds.end + '/fill/' + color
  };
}

// function buildLedRequestOptionsPost(options) {
//   return {
//     hostname: options.leds.host,
//     port: options.leds.port,
//     method: "POST",
//     path: "/api/range",
//     headers: {
//       'Content-Type': "application/json"
//     }
//   };
// }
//
// function makeLedsShining(start, end, color, options) {
//   req = http.request(buildLedRequestOptionsPost(options));
//
//   req.on('error', function(e) {
//     console.log('problem with request: ' + e.message);
//   });
//
//   var post_data = JSON.stringify({
//     "from": start,
//     "to": end,
//     "rgb": color
//   });
//
//   req.write(post_data);
//   req.end();
// }

function JenkinsButlerService(options) {

}

JenkinsButlerService.prototype.setup = function(config) {
  butler = new JenkinsButler(config.jenkins);
  updateStatesOfJobs(config);
  updateTimer = setInterval(updateStatesOfJobs, config.jenkins.updateIntervall * 1000, config);
}

JenkinsButlerService.prototype.shutdown = function(config) {
  if (updateTimer) {
    console.log('JenkinsButlerService shutdown...')
    clearInterval(updateTimer);

    http.get({
      hostname: config.leds.host,
      port: config.leds.port,
      path: '/api/black'
    }, function(res) {
      console.log("Result: " + res.statusCode)
    });
  }
}

exports = module.exports = new JenkinsButlerService();
exports.JenkinsButler = JenkinsButler;
exports.ServiceName = 'JenkinsButlerService';
<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc directive
 * @name ng.directive:ngInit
 * @restrict AC
 *
 * @description
 * The `ngInit` directive allows you to evaluate an expression in the
 * current scope.
 *
 *

 * The only appropriate use of `ngInit` for aliasing special properties of
 * {@link api/ng.directive:ngRepeat `ngRepeat`}, as seen in the demo bellow. Besides this case, you
 * should use {@link guide/dev_guide.mvc.understanding_controller controllers} rather than `ngInit`
 * to initialize values on a scope.
 *

 *
 * @element ANY
 * @param {expression} ngInit {@link guide/expression Expression} to eval.
 *
 * @example
   <doc:example>
     <doc:source>

          list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};

     </doc:source>
     <doc:scenario>
       it('should alias index positions', function() {
         expect(element('.example-init').text())
           .toBe('list[ 0 ][ 0 ] = a;' +
                 'list[ 0 ][ 1 ] = b;' +
                 'list[ 1 ][ 0 ] = c;' +
                 'list[ 1 ][ 1 ] = d;');
       });
     </doc:scenario>
   </doc:example>
 */
var ngInitDirective = ngDirective({
  compile: function() {
    return {
      pre: function(scope, element, attrs) {
        scope.$eval(attrs.ngInit);
      }
    }
  }
});
<commit_msg>docs(ngInit): fix typo<commit_after>'use strict';

/**
 * @ngdoc directive
 * @name ng.directive:ngInit
 * @restrict AC
 *
 * @description
 * The `ngInit` directive allows you to evaluate an expression in the
 * current scope.
 *
 *

 * The only appropriate use of `ngInit` for aliasing special properties of
 * {@link api/ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you
 * should use {@link guide/dev_guide.mvc.understanding_controller controllers} rather than `ngInit`
 * to initialize values on a scope.
 *

 *
 * @element ANY
 * @param {expression} ngInit {@link guide/expression Expression} to eval.
 *
 * @example
   <doc:example>
     <doc:source>

          list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};

     </doc:source>
     <doc:scenario>
       it('should alias index positions', function() {
         expect(element('.example-init').text())
           .toBe('list[ 0 ][ 0 ] = a;' +
                 'list[ 0 ][ 1 ] = b;' +
                 'list[ 1 ][ 0 ] = c;' +
                 'list[ 1 ][ 1 ] = d;');
       });
     </doc:scenario>
   </doc:example>
 */
var ngInitDirective = ngDirective({
  compile: function() {
    return {
      pre: function(scope, element, attrs) {
        scope.$eval(attrs.ngInit);
      }
    }
  }
});
<|endoftext|>


<commit_before>/**
 * Created by zhuangxk on 1/12/16.
 */

var PER_PAGE = 5;
var START_PAGE = 1;

var SearchBox = React.createClass({

    getInitialState: function() {
        return {data: [], search:{} };
    },

    loadSearchFromServer: function() {
       this.handleSearchSubmit({query:'', start_page:START_PAGE, per_page:PER_PAGE})
    },

    handleSearchSubmit: function(search) {
        search.sid = Date.now();
        $.ajax({
          url: this.props.url,
          dataType: 'json',
          type: 'GET',
          data: search,
          success: function(data) {
            this.setState({data: data, search:search});
              console.log({"ajax_return":this.state});
          }.bind(this),
          error: function(xhr, status, err) {
            console.error(this.props.url, status, err.toString());
          }.bind(this)
        });
    },

    componentDidMount: function () {
        this.loadSearchFromServer();
        setInterval(this.loadSearchFromServer, this.props.call_interval);
    },

    render: function() {
        return (

                <SearchBanner onSearchSubmit={this.handleSearchSubmit}/>
                <SearchResult data={this.state.data} search={this.state.search} onPageSubmit={this.handleSearchSubmit}/>

        );
    }

});

var SearchBanner = React.createClass({

    getInitialState: function () {
            return {query:'', start_page:START_PAGE, per_page:PER_PAGE};
        },

    handleTextChange: function (e) {
            this.setState({query:e.target.value});
        },

    handlerEnterSubmit: function(event){
         if(event.keyCode == 13){
            this.handleSubmit(event);
         }
     },

    handleSubmit: function (e) {
        e.preventDefault();
        if (!this.state.query.trim()) {
            return;
        }
        this.props.onSearchSubmit(this.state);
    },

    render: function() {
        return (

Just Search

                        <input className="form-control"
                               placeholder="Search words with regular expressions ..."
                               value={this.state.query}
                               onChange={this.handleTextChange}
                               onKeyDown={this.handlerEnterSubmit}
                               type="text"/>

                            <button className="btn-u"
                                    type="button"
                                    onClick={this.handleSubmit}>

                            </button>

        );
    }

});

var SearchResult = React.createClass({

  render: function() {
    return (

                    <SearchRelated/>

                    <SearchList data={this.props.data}/>
                    <SearchPagination search={this.props.search} onPageSubmit={this.props.onPageSubmit}/>

    );
  }

});

var SearchRelated = React.createClass({

  render: function() {
    return (

Related searches

Web design company

Web design tutorials

Self designing

Tutorials

Basic Concepts

Building your first web page

Advanced HTML

Trending topics

Bootstrap

Wrapbootstrap

Codrops

Search history

Web design articles

Tutorials for web design

                    See all

Related pictures

    );
  }

});

var SearchList = React.createClass({

    render: function() {
        var searchNodes = this.props.data.map(function(search) {
          return (
            <SearchItem title={search.title} desc={search.desc} />
          );
        });
        console.log(this.props.data);
    return (

            共计3345个职位，耗时0.023秒
            {searchNodes}

    );
  }

});

var SearchItem = React.createClass({

  render: function() {
    return (

{this.props.title}

en.wikipedia.org/wiki/Web_design

                    <button data-toggle="dropdown" className="btn btn-default dropdown-toggle" type="button">
                        More
                        Toggle Dropdown
                    </button>

Share

Similar

Advanced search

Wrapbootstrap

Dribbble

{this.props.desc}

3 years ago - By Anthon Brandley

234,034 views

Web designer

    );
  }

});

var Paginator = React.createClass({
    propTypes: {
        max: React.PropTypes.number.isRequired,
        maxVisible: React.PropTypes.number,
        onChange: React.PropTypes.func.isRequired
    },
    componentDidUpdate: function(prevProps, prevState) {
        if (prevState.currentPage !== this.state.currentPage) {
            this.props.onChange(this.state.currentPage);
        }
    },
    getDefaultProps: function() {
        return {
            maxVisible: 5
        };
    },
    getInitialState: function() {
        return {
            currentPage: 1,
            items: []
        };
    },
    goTo: function(page) {
        this.setState({currentPage: page});
    },
    onClickNext: function() {
        var page = this.state.currentPage;
        if (page < this.props.max) {
            this.goTo(page + 1);
        }
    },
    onClickPrev: function() {
        if (this.state.currentPage > 1) {
            this.goTo(this.state.currentPage - 1);
        }
    },
    render: function() {
        var className = this.props.className || '',
            p = this.props,
            s = this.state,
            skip = 0;

        if (s.currentPage > p.maxVisible - 1 && s.currentPage < p.max) {
            skip = s.currentPage - p.maxVisible + 1;
        } else if (s.currentPage === p.max) {
            skip = s.currentPage - p.maxVisible;
        }

        var iterator = Array.apply(null, Array(p.maxVisible)).map(function(v, i) {
            return skip + i + 1;
        });

        return (

                            «
                            Prev

                    {iterator.map(function(page) {
                        return (

                                {page}

                        );
                    }, this)}

                            »
                            Next

        );
    }
});

var SearchPagination = React.createClass({

    onChangePage: function(page) {
        var new_search = this.props.search;
        new_search.start_page = page;
        console.log(new_search);
        this.props.onPageSubmit(new_search);
    },

    render: function() {
        return (

                <Paginator max={10} onChange={this.onChangePage} />

        );
    }

});

ReactDOM.render(

  <SearchBox url="/api/search" call_interval={3600000} />,
  document.getElementById('search-box')

);<commit_msg>fix ini search<commit_after>/**
 * Created by zhuangxk on 1/12/16.
 */

var PER_PAGE = 5;
var START_PAGE = 1;

var SearchBox = React.createClass({

    getInitialState: function() {
        return {data: [], search:{} };
    },

    loadSearchFromServer: function() {
       this.handleSearchSubmit({query:'', start_page:START_PAGE, per_page:PER_PAGE})
    },

    handleSearchSubmit: function(search) {
        search.sid = Date.now();
        $.ajax({
          url: this.props.url,
          dataType: 'json',
          type: 'GET',
          data: search,
          success: function(data) {
            this.setState({data: data, search:search});
              console.log({"ajax_return":this.state});
          }.bind(this),
          error: function(xhr, status, err) {
            console.error(this.props.url, status, err.toString());
          }.bind(this)
        });
    },

    componentDidMount: function () {
        this.loadSearchFromServer();
        setInterval(this.loadSearchFromServer, this.props.call_interval);
    },

    render: function() {
        return (

                <SearchBanner onSearchSubmit={this.handleSearchSubmit}/>
                <SearchResult data={this.state.data} search={this.state.search} onPageSubmit={this.handleSearchSubmit}/>

        );
    }

});

var SearchBanner = React.createClass({

    getInitialState: function () {
            return {query:'', start_page:START_PAGE, per_page:PER_PAGE};
        },

    handleTextChange: function (e) {
            this.setState({query:e.target.value});
        },

    handlerEnterSubmit: function(event){
         if(event.keyCode == 13){
            this.handleSubmit(event);
         }
     },

    handleSubmit: function (e) {
        e.preventDefault();
        this.setState({start_page:START_PAGE});
        if (!this.state.query.trim()) {
            return;
        }
        this.props.onSearchSubmit(this.state);
    },

    render: function() {
        return (

Just Search

                        <input className="form-control"
                               placeholder="Search words with regular expressions ..."
                               value={this.state.query}
                               onChange={this.handleTextChange}
                               onKeyDown={this.handlerEnterSubmit}
                               type="text"/>

                            <button className="btn-u"
                                    type="button"
                                    onClick={this.handleSubmit}>

                            </button>

        );
    }

});

var SearchResult = React.createClass({

  render: function() {
    return (

                    <SearchRelated/>

                    <SearchList data={this.props.data}/>
                    <SearchPagination search={this.props.search} onPageSubmit={this.props.onPageSubmit}/>

    );
  }

});

var SearchRelated = React.createClass({

  render: function() {
    return (

Related searches

Web design company

Web design tutorials

Self designing

Tutorials

Basic Concepts

Building your first web page

Advanced HTML

Trending topics

Bootstrap

Wrapbootstrap

Codrops

Search history

Web design articles

Tutorials for web design

                    See all

Related pictures

    );
  }

});

var SearchList = React.createClass({

    render: function() {
        var searchNodes = this.props.data.map(function(search) {
          return (
            <SearchItem title={search.title} desc={search.desc} />
          );
        });
        console.log(this.props.data);
    return (

            共计3345个职位，耗时0.023秒
            {searchNodes}

    );
  }

});

var SearchItem = React.createClass({

  render: function() {
    return (

{this.props.title}

en.wikipedia.org/wiki/Web_design

                    <button data-toggle="dropdown" className="btn btn-default dropdown-toggle" type="button">
                        More
                        Toggle Dropdown
                    </button>

Share

Similar

Advanced search

Wrapbootstrap

Dribbble

{this.props.desc}

3 years ago - By Anthon Brandley

234,034 views

Web designer

    );
  }

});

var Paginator = React.createClass({
    propTypes: {
        max: React.PropTypes.number.isRequired,
        maxVisible: React.PropTypes.number,
        onChange: React.PropTypes.func.isRequired
    },
    componentDidUpdate: function(prevProps, prevState) {
        if (prevState.currentPage !== this.state.currentPage) {
            this.props.onChange(this.state.currentPage);
        }
    },
    getDefaultProps: function() {
        return {
            maxVisible: 5
        };
    },
    getInitialState: function() {
        return {
            currentPage: this.props.currentPage
        };
    },
    goTo: function(page) {
        this.setState({currentPage: page});
    },
    onClickNext: function() {
        var page = this.state.currentPage;
        if (page < this.props.max) {
            this.goTo(page + 1);
        }
    },
    onClickPrev: function() {
        if (this.state.currentPage > 1) {
            this.goTo(this.state.currentPage - 1);
        }
    },
    render: function() {
        var className = this.props.className || '',
            p = this.props,
            s = this.state,
            skip = 0;

        if (s.currentPage > p.maxVisible - 1 && s.currentPage < p.max) {
            skip = s.currentPage - p.maxVisible + 1;
        } else if (s.currentPage === p.max) {
            skip = s.currentPage - p.maxVisible;
        }

        var iterator = Array.apply(null, Array(p.maxVisible)).map(function(v, i) {
            return skip + i + 1;
        });

        return (

                            «
                            Prev

                    {iterator.map(function(page) {
                        return (

                                {page}

                        );
                    }, this)}

                            »
                            Next

        );
    }
});

var SearchPagination = React.createClass({

    getInitialState: function() {
        return {
            search: this.props.search
        };
    },

    onChangePage: function(page) {
        this.state.search.start_page = page;
        console.log(this.state.search);
        this.props.onPageSubmit(this.state.search);
    },

    render: function() {
        return (

                <Paginator max={10} onChange={this.onChangePage} currentPage={this.state.search.start_page}/>

        );
    }

});

ReactDOM.render(

  <SearchBox url="/api/search" call_interval={3600000} />,
  document.getElementById('search-box')

);<|endoftext|>


<commit_before>var util = require('util'), config = {};

/**
 *  An error class with support for message parameter
 *  replacement and exit status codes.
 *
 *  @param message The error message or error instance.
 *  @param code An exit status code.
 *  @param parameters Array of message replacement parameters.
 *  @param name A specific name for the error.
 */
var CliError = function(message, code, parameters, name) {
  var source = (message instanceof Error) ? message : null;
  var msg = (message instanceof Error) ? message.message : message;
  Error.call(this);
  this.name = name || config.name || 'CliError';
  this.message = msg;
  this.code = typeof(code) === 'number' ? code : 1;
  this.parameters = parameters || [];
  if(source) {
    source.code = this.code;
    source.parameters = this.parameters;
    //console.error(source.stack);
  }
  this._source = source;
  this._key = null;
  var prepare = Error.prepareStackTrace;
  Error.prepareStackTrace = function(_, stack) {
    return stack;
  }
  //console.dir('' + source.stack);
  var estack = source ? source.stack : null;
  Error.captureStackTrace(source || this, this.constructor);
  this.__stack = estack ? estack : this.stack;
  Error.prepareStackTrace = prepare;
  this.update();
  //console.dir(source.stack);
}

util.inherits(CliError, Error);

/**
 *  Get an error wrapped by this error that is deemed
 *  to be the cause of this error.
 *
 *  @return An error that caused this error or null.
 */
CliError.prototype.cause = function(e) {
  if(!arguments.length) return this._source;
  this._source = e;
}

/**
 *  Remove the first element from the raw stack trace
 *  information and update the underlying data.
 */
CliError.prototype.shift = function() {
  var val = this.__stack.shift();
  this.update();
  return val;
}

/**
 *  Remove the last element from the raw stack trace
 *  information and update the underlying data.
 */
CliError.prototype.pop = function() {
  var val = this.__stack.pop();
  this.update();
  return val;
}

/**
 *  Splice the raw stack trace and update the underlying data.
 *
 *  Does not allow inserting elements.
 *
 *  @param index The start index.
 *  @param amount The number of elements to delete.
 */
CliError.prototype.splice = function(index, amount) {
  var val = this.__stack.splice.apply(
    this.__stack, [].slice.call(arguments, 0, 2));
  this.update();
  return val;
}

/**
 *  Update the underlying stacktrace information.
 *
 *  @api private
 */
CliError.prototype.update = function() {
  // NOTE: some errors with some versions of node
  // NOTE: ie, RangeError: Maximum call stack exceeded
  // NOTE: do not have a stack trace
  if(!this.__stack) return;
  var params = this.parameters.slice(0);
  params.unshift(this.message);
  var strace = this._stacktrace = [];
  var callers = this.callers = [];
  var stack = this.name + ': '
    + util.format.apply(util, params) + '\n';
  // TODO: FIX
  this.__stack.forEach(function(caller) {
    callers.push(caller);
    strace.push('' + caller);
    stack += config.pad + caller + '\n';
  });
  this.stack = stack.trim();
}

/**
 *  Get the error key.
 */
CliError.prototype.__defineGetter__('key', function() {
  return this._key;
});

/**
 *  Set the error key.
 */
CliError.prototype.__defineSetter__('key', function(key) {
  if(this._source) {
    this._source.key = key;
  }
  this._key = key;
});

/**
 *  Get the raw stack trace information.
 */
CliError.prototype.__defineGetter__('info', function() {
  return this.__stack;
});

/**
 *  Get a source error if this error wraps another error.
 */
CliError.prototype.__defineGetter__('source', function() {
  return this._source;
});

/**
 *  Get an array of the stack trace lines.
 */
CliError.prototype.__defineGetter__('stacktrace', function() {
  return this._stacktrace;
});

/**
 *  Print a warning message from the contents
 *  of this error.
 *
 *  @api private
 *
 *  @param method The console method.
 *  @param trace Whether to include the stack trace.
 *  @param parameters Message replacement parameters.
 */
CliError.prototype.print = function(method, trace, parameters) {
  var msg = this.message, prefix = config.prefix;
  if(prefix === true) {
    msg = this.name + ': ' + msg;
  }else if(typeof prefix == 'string') {
    msg = prefix + msg;
  }else if(typeof prefix == 'function') {
    msg = prefix() + msg;
  }
  parameters = parameters.length ? parameters : this.parameters;
  parameters = parameters.slice();
  parameters.unshift(msg);
  method.apply(console, parameters);
}

/**
 *  Print the stack strace.
 *
 *  @api private
 *
 *  @param method The method to invoke.
 *  @param scope A scope for the method.
 */
CliError.prototype.printstack = function(method, scope) {
  // NOTE: some errors with some versions of node
  // NOTE: ie, RangeError: Maximum call stack exceeded
  // NOTE: do not have a stack trace
  if(!this._stacktrace) return;
  for(var i = 0;i < this._stacktrace.length;i++) {
    method.call(scope, config.pad + this._stacktrace[i]);
  }
}

/**
 *  Print a warning message from the contents
 *  of this error.
 *
 *  @param trace Whether to include the stack trace.
 *  @param ... Message replacement parameters.
 */
CliError.prototype.warn = function(trace) {
  this.print(console.warn, trace, [].slice.call(arguments, 1));
  if(trace) {
    this.printstack(console.warn);
  }
}

/**
 *  Print an error message from the contents
 *  of this error.
 *
 *  @param trace Whether to include the stack trace.
 *  @param ... Message replacement parameters.
 */
CliError.prototype.error = function(trace) {
  this.print(console.error, trace, [].slice.call(arguments, 1));
  if(trace) {
    this.printstack(console.error);
  }
}

/**
 *  Retrieve a formatted string of the error message.
 *
 *  @param ... Message replacement parameters.
 */
CliError.prototype.format = function() {
  var args = [].slice.call(arguments, 0);
  if(!args.length) {
    args = this.parameters;
  }
  args.unshift(this.message);
  return util.format.apply(util, args);
}

/**
 *  Retrieve an object suitable for JSON serialization.
 *
 *  @param trace Whether to include the stack trace.
 *  @param ... Message replacement parameters.
 */
CliError.prototype.toObject = function(trace) {
  var o = {};
  var stack = this._stacktrace;
  var msg = this.message;
  var parameters = [].slice.call(arguments, 1);
  if(!parameters.length && this.parameters.length) {
    parameters = this.parameters;
  }
  if(parameters.length) {
    parameters.unshift(msg);
    msg = util.format.apply(util, parameters);
  }
  o.message = msg;
  o.name = this.name;
  o.code = this.code;
  if(this.key) {
    o.key = this.key;
  }
  if(trace) {
    o.stack = stack;
  }
  return o;
}

/**
 *  Returns a JSON string representation of this error.
 *
 *  @param trace Whether to include the stack trace.
 *  @param ... Message replacement parameters.
 */
CliError.prototype.stringify = function(trace) {
  var o = this.toObject.apply(this, arguments);
  return JSON.stringify(o);
}

/**
 *  Exit the process with the status code
 *  associated with this error.
 */
CliError.prototype.exit = function() {
  process.exit(this.code);
  return this.code;
}

module.exports = function(conf) {
  config = conf;
  return module.exports;
}

module.exports.CliError = CliError;
<commit_msg>Tidy stack generation handling.<commit_after>var util = require('util'), config = {};

/**
 *  An error class with support for message parameter
 *  replacement and exit status codes.
 *
 *  @param message The error message or error instance.
 *  @param code An exit status code.
 *  @param parameters Array of message replacement parameters.
 *  @param name A specific name for the error.
 */
var CliError = function(message, code, parameters, name) {
  var source = (message instanceof Error) ? message : null;
  var msg = (message instanceof Error) ? message.message : message;
  Error.call(this);
  this.name = name || config.name || 'CliError';
  this.message = msg;
  this.code = typeof(code) === 'number' ? code : 1;
  this.parameters = parameters || [];
  if(source) {
    source.code = this.code;
    source.parameters = this.parameters;
    //console.error(source.stack);
  }
  this._source = source;
  this._key = null;
  //console.dir(source.stack);
  this.getStack(source);
}

util.inherits(CliError, Error);

CliError.prototype.getStack = function(source) {
  source = source || this;
  var prepare = Error.prepareStackTrace;
  Error.prepareStackTrace = function(_, stack) {
    return stack;
  }
  //console.dir('' + source.stack);
  var estack = source.stack;
  Error.captureStackTrace(source, this.constructor);
  this.__stack = estack ? estack : this.stack;
  Error.prepareStackTrace = prepare;
  this.update();
}

/**
 *  Get an error wrapped by this error that is deemed
 *  to be the cause of this error.
 *
 *  @return An error that caused this error or null.
 */
CliError.prototype.cause = function(e) {
  if(!arguments.length) return this._source;
  this._source = e;
  if(e) {
    this.getStack(e);
  }
}

/**
 *  Remove the first element from the raw stack trace
 *  information and update the underlying data.
 */
CliError.prototype.shift = function() {
  var val = this.__stack.shift();
  this.update();
  return val;
}

/**
 *  Remove the last element from the raw stack trace
 *  information and update the underlying data.
 */
CliError.prototype.pop = function() {
  var val = this.__stack.pop();
  this.update();
  return val;
}

/**
 *  Splice the raw stack trace and update the underlying data.
 *
 *  Does not allow inserting elements.
 *
 *  @param index The start index.
 *  @param amount The number of elements to delete.
 */
CliError.prototype.splice = function(index, amount) {
  var val = this.__stack.splice.apply(
    this.__stack, [].slice.call(arguments, 0, 2));
  this.update();
  return val;
}

/**
 *  Update the underlying stacktrace information.
 *
 *  @api private
 */
CliError.prototype.update = function() {
  // NOTE: some errors with some versions of node
  // NOTE: ie, RangeError: Maximum call stack exceeded
  // NOTE: do not have a stack trace
  if(!this.__stack) return;
  var params = this.parameters.slice(0);
  params.unshift(this.message);
  var strace = this._stacktrace = [];
  var callers = this.callers = [];
  var stack = this.name + ': '
    + util.format.apply(util, params) + '\n';
  // TODO: FIX
  this.__stack.forEach(function(caller) {
    callers.push(caller);
    strace.push('' + caller);
    stack += config.pad + caller + '\n';
  });
  this.stack = stack.trim();
}

/**
 *  Get the error key.
 */
CliError.prototype.__defineGetter__('key', function() {
  return this._key;
});

/**
 *  Set the error key.
 */
CliError.prototype.__defineSetter__('key', function(key) {
  if(this._source) {
    this._source.key = key;
  }
  this._key = key;
});

/**
 *  Get the raw stack trace information.
 */
CliError.prototype.__defineGetter__('info', function() {
  return this.__stack;
});

/**
 *  Get a source error if this error wraps another error.
 */
CliError.prototype.__defineGetter__('source', function() {
  return this._source;
});

/**
 *  Get an array of the stack trace lines.
 */
CliError.prototype.__defineGetter__('stacktrace', function() {
  return this._stacktrace;
});

/**
 *  Print a warning message from the contents
 *  of this error.
 *
 *  @api private
 *
 *  @param method The console method.
 *  @param trace Whether to include the stack trace.
 *  @param parameters Message replacement parameters.
 */
CliError.prototype.print = function(method, trace, parameters) {
  var msg = this.message, prefix = config.prefix;
  if(prefix === true) {
    msg = this.name + ': ' + msg;
  }else if(typeof prefix == 'string') {
    msg = prefix + msg;
  }else if(typeof prefix == 'function') {
    msg = prefix() + msg;
  }
  parameters = parameters.length ? parameters : this.parameters;
  parameters = parameters.slice();
  parameters.unshift(msg);
  method.apply(console, parameters);
}

/**
 *  Print the stack strace.
 *
 *  @api private
 *
 *  @param method The method to invoke.
 *  @param scope A scope for the method.
 */
CliError.prototype.printstack = function(method, scope) {
  // NOTE: some errors with some versions of node
  // NOTE: ie, RangeError: Maximum call stack exceeded
  // NOTE: do not have a stack trace
  if(!this._stacktrace) return;
  for(var i = 0;i < this._stacktrace.length;i++) {
    method.call(scope, config.pad + this._stacktrace[i]);
  }
}

/**
 *  Print a warning message from the contents
 *  of this error.
 *
 *  @param trace Whether to include the stack trace.
 *  @param ... Message replacement parameters.
 */
CliError.prototype.warn = function(trace) {
  this.print(console.warn, trace, [].slice.call(arguments, 1));
  if(trace) {
    this.printstack(console.warn);
  }
}

/**
 *  Print an error message from the contents
 *  of this error.
 *
 *  @param trace Whether to include the stack trace.
 *  @param ... Message replacement parameters.
 */
CliError.prototype.error = function(trace) {
  this.print(console.error, trace, [].slice.call(arguments, 1));
  if(trace) {
    this.printstack(console.error);
  }
}

/**
 *  Retrieve a formatted string of the error message.
 *
 *  @param ... Message replacement parameters.
 */
CliError.prototype.format = function() {
  var args = [].slice.call(arguments, 0);
  if(!args.length) {
    args = this.parameters;
  }
  args.unshift(this.message);
  return util.format.apply(util, args);
}

/**
 *  Retrieve an object suitable for JSON serialization.
 *
 *  @param trace Whether to include the stack trace.
 *  @param ... Message replacement parameters.
 */
CliError.prototype.toObject = function(trace) {
  var o = {};
  var stack = this._stacktrace;
  var msg = this.message;
  var parameters = [].slice.call(arguments, 1);
  if(!parameters.length && this.parameters.length) {
    parameters = this.parameters;
  }
  if(parameters.length) {
    parameters.unshift(msg);
    msg = util.format.apply(util, parameters);
  }
  o.message = msg;
  o.name = this.name;
  o.code = this.code;
  if(this.key) {
    o.key = this.key;
  }
  if(trace) {
    o.stack = stack;
  }
  return o;
}

/**
 *  Returns a JSON string representation of this error.
 *
 *  @param trace Whether to include the stack trace.
 *  @param ... Message replacement parameters.
 */
CliError.prototype.stringify = function(trace) {
  var o = this.toObject.apply(this, arguments);
  return JSON.stringify(o);
}

/**
 *  Exit the process with the status code
 *  associated with this error.
 */
CliError.prototype.exit = function() {
  process.exit(this.code);
  return this.code;
}

module.exports = function(conf) {
  config = conf;
  return module.exports;
}

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


<commit_before>// 73: Generator - `return` inside a generator is special
// To do: make all tests pass, leave the assert lines unchanged!

describe('`return` in a generator function is special', function() {

  describe('the returned value is an IteratorResult (just like any value returned via `yield`)', function() {

    it('returns an IteratorResult (an object with the properties `value` and `done`)', function() {
      function* generatorFunction() { return 1; }
      const returned = generatorFunction().next();
      assert.deepEqual(Object.keys(returned), ['value', 'done']);
    });

    it('the property `value` is the value given after the `return` statement', function() {
      function* generatorFunction() { return 23; }
      const {value} = generatorFunction().next();
      assert.deepEqual(value, 23);
    });

    it('the property `done` is true', function() {
      function* generatorFunction() { return 42; }
      const {done} = generatorFunction().next();
      assert.deepEqual(done, true);
    });

    it('NOTE: `yield` does not return `done=true` but `done=false`!', function() {
      function* generatorFunction() { yield 1; }
      const returned = generatorFunction().next();
      assert.deepEqual(returned, {value: 1, done: false});
    });

    it('a missing `return` returns {value: undefined, done: true}', function() {
      function* generatorFunction() {}
      const returned = generatorFunction().next();
      assert.deepEqual(returned, {value: void 0, done: true});
    });

  });

  describe('mixing `return` and `yield`', function() {

    function* generatorFunctionWithYieldAndReturn() {
      yield 1;
      return 2;
    }

    it('is possible', function() {
      const iterator = generatorFunctionWithYieldAndReturn();
      const values = [
        iterator.next().value,
        iterator.next().value
      ];
      assert.deepEqual(values, [1, 2]);
    });

    it('the mix behaves different to two `yield`s', function() {
      const iterator = generatorFunctionWithYieldAndReturn();
      assert.deepEqual(Array.from(iterator), [1]);
    });

    it('two `yield`s returning values', function() {
      function* generatorFunctionWithTwoYields() {
        yield 1;
        yield 2;
      }
      const iterator = generatorFunctionWithTwoYields();
      assert.deepEqual(Array.from(iterator), [1, 2]);
    });

    it('returning a yielded value', function() {
      function* generatorFunction() {
        return yield 1;
      }
      const iterator = generatorFunction();
      const values = [
        iterator.next().value,
        iterator.next(2).value
      ];
      assert.deepEqual(values, [1, 2]);
    });

  });

});
<commit_msg>Made it a kata, all tests fail.<commit_after>// 73: Generator - `return` inside a generator is special
// To do: make all tests pass, leave the assert lines unchanged!

describe('`return` in a generator function is special', function() {

  describe('the returned value is an IteratorResult (just like any value returned via `yield`)', function() {

    it('returns an IteratorResult (an object with the properties `value` and `done`)', function() {
      function* generatorFunction() { return 1; }
      const returned = generatorFunction().next();
      const propertyNames = [];
      assert.deepEqual(Object.keys(returned), propertyNames);
    });

    it('the property `value` is the value given after the `return` statement', function() {
      function* generatorFunction() { return; }
      const {value} = generatorFunction().next();
      assert.deepEqual(value, 23);
    });

    it('the property `done` is true', function() {
      function* generatorFunction() { yield 42; }
      const {done} = generatorFunction().next();
      assert.deepEqual(done, true);
    });

    it('NOTE: `yield` does not return `done=true` but `done=false`!', function() {
      function* generatorFunction() { return 1; }
      const returned = generatorFunction().next();
      assert.deepEqual(returned, {value: 1, done: false});
    });

    it('a missing `return` returns {value: undefined, done: true}', function() {
      function* generatorFunction() { return 1; }
      const returned = generatorFunction().next();
      assert.deepEqual(returned, {value: void 0, done: true});
    });

  });

  describe('mixing `return` and `yield`', function() {

    function* generatorFunctionWithYieldAndReturn() {
      yield 1;
    }

    it('is possible', function() {
      const iterator = generatorFunctionWithYieldAndReturn();
      const values = [
        iterator.next().value,
        iterator.next().value
      ];
      assert.deepEqual(values, [1, 2]);
    });

    it('the mix behaves different to two `yield`s', function() {
      const iterator = generatorFunctionWithYieldAndReturn();
      const values = [1, 2];
      assert.deepEqual(Array.from(iterator), values);
    });

    it('two `yield`s returning values', function() {
      function* generatorFunctionWithTwoYields() {
      }
      assert.deepEqual(Array.from(generatorFunctionWithTwoYields()), [1, 2]);
    });

    it('returning a yielded value', function() {
      function* generatorFunction() {
        return 1;
      }
      const iterator = generatorFunction();
      const values = [
        iterator.next().value,
        iterator.next(2).value
      ];
      assert.deepEqual(values, [1, 2]);
    });

  });

});
<|endoftext|>


<commit_before>var async = require('async');
var util = require('util');
var request = require('request');
var debug = require('debug')('site-parser:fetch');
var userAgents = require('./user-agents')();
var iconv = require('iconv-lite');

exports = module.exports = function(site, agent, callback) {
    var requestOptions = {
        url: site.url,
        encoding: null, // return body as a buffer with no encoding
        headers: {
            'user-agent': userAgents[site.format] || userAgents['desktop']
        },
        pool: agent,
        timeout: this.timeOut
    };

    request(requestOptions, function(err, response, body) {
        if (!err && site.charset && iconv.encodingExists(site.charset)) {
            debug('<- converting charset to ' + site.charset + ' ->');
            var temp = iconv.decode(body, site.charset);
            body = iconv.encode(temp, 'utf-8');
        }

        // replace breakpoints with spaces
        body = body
          .replace(/<\s*\/?\s*br?\s*\/?> {1}/ig, ' ')
          .replace(/<\s*\/?\s*br?\s*\/?>/ig, ' ')

        callback(err, body);
    });
};
<commit_msg>fix bug<commit_after>var async = require('async');
var util = require('util');
var request = require('request');
var debug = require('debug')('site-parser:fetch');
var userAgents = require('./user-agents')();
var iconv = require('iconv-lite');

exports = module.exports = function(site, agent, callback) {
    var requestOptions = {
        url: site.url,
        encoding: null, // return body as a buffer with no encoding
        headers: {
            'user-agent': userAgents[site.format] || userAgents['desktop']
        },
        pool: agent,
        timeout: this.timeOut
    };

    request(requestOptions, function(err, response, body) {
        if (!err && site.charset && iconv.encodingExists(site.charset)) {
            debug('<- converting charset to ' + site.charset + ' ->');
            var temp = iconv.decode(body, site.charset);
            body = iconv.encode(temp, 'utf-8');
        }

        // replace breakpoints with spaces
        var cleanedBody = (body || '')
          .replace(/<\s*\/?\s*br?\s*\/?> {1}/ig, ' ')
          .replace(/<\s*\/?\s*br?\s*\/?>/ig, ' ')

        callback(err, body);
    });
};
<|endoftext|>