<commit_before>var menu = function (config) {
    helpers.apply({
        color: '#AAA',
        selectedColor: '#FFF',
        mousePlaneOffset: 250,
        mousePlane: 'z',
        topMost: true,
        onmouseup: this.onmouseup.bind(this)
    }, this);
    helpers.apply(config, this);
    this.setItems(this.mainMenu);
};
menu.prototype = new entity();

menu.prototype.gotoRoot = function () {
    this.setItems(this.mainMenu);
};

menu.prototype.onmouseup = function(entity, hit){
	if(this.ignoreNextButtonUp){
		this.ignoreNextButtonUp = false;
	}
	else{
		if(this.selected && this.selected.onMousePlaneUp){
			this.selected.onMousePlaneUp(this, this);
		}
	}
};

menu.prototype.setItems = function(items){
	if(this.engine.buttonDown){
		this.ignoreNextButtonUp = true;
	}
	this.currentItems = items;
	this.clear();
	this.texts = [];
	var i = 0;
	for(var s in items){
		var text = s;
		if(items[s].getText){
			text = items[s].getText(this);
		}
		var config = helpers.apply(items[s],{
			font: '50px CBM64',
			color: this.color,
			engine: this.engine,
			text: text,
			position: {
				x: 0, // this.engine.width / 5,
				y: (this.engine.height / 3) + ( i * 60),
				z: this.mousePlaneOffset
			}
		});
		if(config.submenu){
			var self = this;
			config.onMousePlaneUp = function(entity, hit){
				self.setItems(entity.submenu);
			};
		}
		this.texts.push(config);
		i++;
	}
};

menu.prototype.show = function (items) {
    if (this.finished) {
        this.finished = false;
        if(!this.engine.contains(this)){
        	this.engine.add(this);
        }
        this.gotoRoot();
    }
    if(items){
    	this.setItems(items);
    }
};

menu.prototype.toggle = function () {
    if (this.finished) {
        this.finished = false;
        if(!this.engine.contains(this)){
        	this.engine.add(this);
        }
        this.gotoRoot();
    }
    else {
        this.finished = true;
    }
};

menu.prototype.hide = function () {
    this.finished = true;
};

menu.prototype.clear = function(){
	if(this.subEntities){
		for(var i = 0, l = this.subEntities.length; i < l; i++){
			this.subEntities[i].finished = true;
		}
	}
};

menu.prototype.select = function(entity){
	if(this.selected != entity){
		if(this.selected){
			this.selected.color = this.color;
		}
		this.selected = entity;
		if(this.selected){
			this.selected.color = this.selectedColor;
		}
	}
};

menu.prototype.update = function(time){
	if(this.mousePosition && this.texts){
		// Calculate item on the same height as the mouse
		var index = Math.floor( (this.mousePosition.y - (this.engine.height / 3)) / 60 ) + 1;
		if(index > -1 && index < this.texts.length && this.texts[index].onMousePlaneUp){
			this.select(this.texts[index]);
		    if(this.engine.touchController.touchable){
		    	this.onmouseup(this.texts[index], true);
		    	this.ignoreNextButtonUp = true;
		    }
		}
		else{
			this.select(null);
		}
	}
};

menu.prototype.render = function(time){

};
<commit_msg>Removal of .bind<commit_after>var menu = function (config) {
    helpers.apply({
        color: '#AAA',
        selectedColor: '#FFF',
        mousePlaneOffset: 250,
        mousePlane: 'z',
        topMost: true
    }, this);
    helpers.apply(config, this);
    this.setItems(this.mainMenu);
};
menu.prototype = new entity();

menu.prototype.gotoRoot = function () {
    this.setItems(this.mainMenu);
};

menu.prototype.onmouseup = function(entity, hit){
	if(this.ignoreNextButtonUp){
		this.ignoreNextButtonUp = false;
	}
	else{
		if(this.selected && this.selected.onMousePlaneUp){
			this.selected.onMousePlaneUp(this, this);
		}
	}
};

menu.prototype.setItems = function(items){
	if(this.engine.buttonDown){
		this.ignoreNextButtonUp = true;
	}
	this.currentItems = items;
	this.clear();
	this.texts = [];
	var i = 0;
	for(var s in items){
		var text = s;
		if(items[s].getText){
			text = items[s].getText(this);
		}
		var config = helpers.apply(items[s],{
			font: '50px CBM64',
			color: this.color,
			engine: this.engine,
			text: text,
			position: {
				x: 0, // this.engine.width / 5,
				y: (this.engine.height / 3) + ( i * 60),
				z: this.mousePlaneOffset
			}
		});
		if(config.submenu){
			var self = this;
			config.onMousePlaneUp = function(entity, hit){
				self.setItems(entity.submenu);
			};
		}
		this.texts.push(config);
		i++;
	}
};

menu.prototype.show = function (items) {
    if (this.finished) {
        this.finished = false;
        if(!this.engine.contains(this)){
        	this.engine.add(this);
        }
        this.gotoRoot();
    }
    if(items){
    	this.setItems(items);
    }
};

menu.prototype.toggle = function () {
    if (this.finished) {
        this.finished = false;
        if(!this.engine.contains(this)){
        	this.engine.add(this);
        }
        this.gotoRoot();
    }
    else {
        this.finished = true;
    }
};

menu.prototype.hide = function () {
    this.finished = true;
};

menu.prototype.clear = function(){
	if(this.subEntities){
		for(var i = 0, l = this.subEntities.length; i < l; i++){
			this.subEntities[i].finished = true;
		}
	}
};

menu.prototype.select = function(entity){
	if(this.selected != entity){
		if(this.selected){
			this.selected.color = this.color;
		}
		this.selected = entity;
		if(this.selected){
			this.selected.color = this.selectedColor;
		}
	}
};

menu.prototype.update = function(time){
	if(this.mousePosition && this.texts){
		// Calculate item on the same height as the mouse
		var index = Math.floor( (this.mousePosition.y - (this.engine.height / 3)) / 60 ) + 1;
		if(index > -1 && index < this.texts.length && this.texts[index].onMousePlaneUp){
			this.select(this.texts[index]);
		    if(this.engine.touchController.touchable){
		    	this.onmouseup(this.texts[index], true);
		    	this.ignoreNextButtonUp = true;
		    }
		}
		else{
			this.select(null);
		}
	}
};

menu.prototype.render = function(time){

};
<|endoftext|>


<commit_before>function logout() {
    $( '#logout' ).click( function() {
        $( '#logout-form' ).submit();
    });
}

$( document ).ready( logout );

<commit_msg>Fix 2 click bug<commit_after>function logout() {
    $( '#logout' ).click( function() {
        $( '#logout-form' ).submit();
        return false;
    });
}

$( document ).ready( logout );

<|endoftext|>


<commit_before>document.addEventListener(
    'DOMContentLoaded', function() {
        var button = document.getElementById( 'logout' );
        button.addEventListener(
            'click', function() {
                document.getElementById( 'logout-form' ).submit();
            }, false
        );
    }
);
<commit_msg>Migrate logout.js to jquery<commit_after>function logout() {
    $( '#logout' ).click( function() {
        $( '#logout-form' ).submit();
    });
}

$( document ).ready( logout );

<|endoftext|>


<commit_before>var _ = require('lodash');
var moment = require('frozen-moment');
var periodTools = require('./periodTools');
var ressourcesMap = require('./ressources');
var ind = require('./individu');
var men = require('./menage');
var fam = require('./famille');
var foy = require('./foyerFiscal');
var common = require('./common');
var PRESTATIONS = require('../prestations');

var isNotValidValue = function(value) {
    return _.isNaN(value) || _.isUndefined(value) || value === null;
};

var getPeriods = function(dateDeValeur) {
    dateDeValeur = moment(dateDeValeur).freeze();
    return {
        moisCourant: {
            key: dateDeValeur.format('YYYY-MM')
        },
        moisPrecedent: {
            key: dateDeValeur.subtract(1, 'months').format('YYYY-MM')
        },
        moisMMoins2: {
            key: dateDeValeur.subtract(2, 'months').format('YYYY-MM')
        },
        moisMMoins3: {
            key: dateDeValeur.subtract(3, 'months').format('YYYY-MM')
        },
       anneeGlissante: {
            debut: dateDeValeur.subtract(1, 'years').subtract(1, 'months'),
            fin: dateDeValeur,
            key: 'year:' + dateDeValeur.subtract(1, 'years').format('YYYY-MM')
        },
        anneeFiscalReference: {
            key: dateDeValeur.subtract(2, 'years').year()
        },
        trimestreGlissant: {
            debut: dateDeValeur.subtract(3, 'months').subtract(1, 'months'),
            fin: dateDeValeur,
            key: dateDeValeur.subtract(3, 'months').format('YYYY-MM') + ':3'
        }
    };
};

var applyRessources = function(mesAidesEntity, openFiscaEntity, schema, dateDeValeur) {
    var periods = getPeriods(dateDeValeur);

    function isPeriodWithin(agregatKey, periode) {
        return periode.isAfter(periods[agregatKey].debut, 'month') && periode.isBefore(periods[agregatKey].fin, 'month');
    }

    var ressourcesByType = _.groupBy(mesAidesEntity.ressources, 'type');

    _.forEach(schema, function(definitions, openFiscaKey) {
        if (! _.isArray(definitions)) {
            definitions = [definitions];
        }

        _.forEach(definitions, function(definition) {

            var srcKey = definition.src || definition;
            var fn = definition.fn;

            if (ressourcesByType[srcKey]) {
                var result = {};
                var agr = {};

                _.forEach(ressourcesByType[srcKey], function(item) {
                    if (item.periode) {
                        // Période d'origine
                        if (!result[item.periode]) result[item.periode] = 0;
                        result[item.periode] += item.montant;

                        // Aggrégats
                        _.keys(periods).forEach(function (agregatKey) {
                            if (agregatKey != 'anneeFiscalReference' && isPeriodWithin(agregatKey, moment(item.periode, 'YYYY-MM'))) {
                                if (!(agregatKey in agr)) agr[agregatKey] = 0;
                                agr[agregatKey] += fn ? fn(item.montant) : item.montant;
                            }
                        });
                    }
                });

                _.forEach(result, function(montant, periode) {
                    // Applique la transformation
                    if (fn) montant = fn(montant);
                    result[periode] = montant;
                });

                // On prolonge la ressource perçue quand c'est possible
                if (result[periods.moisPrecedent.key] && !_.contains(mesAidesEntity.interruptedRessources, srcKey)) {
                    result[periods.moisCourant.key] = result[periods.moisPrecedent.key];
                }

                if (_.size(result) > 0) {
                    if (_.size(openFiscaEntity[openFiscaKey]) > 0) {
                        openFiscaEntity[openFiscaKey] = _.extend(openFiscaEntity[openFiscaKey],result);
                    } else {
                        openFiscaEntity[openFiscaKey] = result;
                    }
                }

                _.forEach(agr, function (value, agregatKey) {
                    openFiscaEntity[openFiscaKey][periods[agregatKey].key] = value;
                });

                // On suppose que les revenus pour l'année fiscale de référence sont les mêmes que pour les 12 derniers mois, si ces revenus n'ont pas encore
                // été renseignés
                var anneeGlissanteKey = periods.anneeGlissante.key,
                    anneeFiscaleRefKey = periods.anneeFiscalReference.key;
                if (! openFiscaEntity[openFiscaKey][anneeFiscaleRefKey]) {
                    openFiscaEntity[openFiscaKey][anneeFiscaleRefKey] = openFiscaEntity[openFiscaKey][anneeGlissanteKey];
                }
            }
        });
    });
};

var setNonInjectedPrestationsToZero = function(openFiscaEntity, dateDeValeur) {
    var periods = getPeriods(dateDeValeur);
    var concernedPeriods = ['moisPrecedent', 'moisMMoins2', 'moisMMoins3', 'anneeGlissante'];

    _.forEach(concernedPeriods, function(periodKey) {
        var period = periods[periodKey].key;
        var prestations = _.pick(PRESTATIONS, function(definition) {
            return definition.type == Number;
        });

        _.forEach(prestations, function(definition, prestationName) {
            if (! openFiscaEntity[prestationName]) {
                openFiscaEntity[prestationName] = {};
            }
            if (! openFiscaEntity[prestationName][period]) {
                openFiscaEntity[prestationName][period] = 0;
            }
        });

    });

};

var buildOpenFiscaEntity = function(src, schema, situation) {
    var result = {};
    _.forEach(schema, function(definition, openFiscaKey) {
        var params = _.isString(definition) ? { src: definition } : definition;

        if (params.values) {
            result[openFiscaKey] = params.values[src[params.src]];
        } else if (params.fn) {
            result[openFiscaKey] = params.src ? params.fn(src[params.src], src, situation) : params.fn(src, situation);
        } else {
            result[openFiscaKey] = src[params.src];
        }

        if (params.round && _.isNumber(result[openFiscaKey])) {
            result[openFiscaKey] = Math.round(result[openFiscaKey]);
        }

        // Supprime les null (mal supportés par OpenFisca)
        if (isNotValidValue(result[openFiscaKey])) {
            if ('default' in params) result[openFiscaKey] = params.default;
            else delete result[openFiscaKey];
        }
    });
    return result;
};

var mapIndividus = exports.mapIndividus = function (situation) {
    var individus = _.filter(situation.individus, function(individu) {
        return common.isIndividuValid(individu, situation);
    });

    return _.map(individus, function(individu) {
        if (individu.role === 'demandeur') {
            _.extend(individu, situation.patrimoine);

            var revenusLocatifs = situation.patrimoine.revenusLocatifs.map(function(revenu) {
                revenu.type = 'revenusLocatifs';
                return revenu;
            });

            var revenusDuCapital = situation.patrimoine.revenusDuCapital.map(function(revenu) {
                revenu.type = 'revenusDuCapital';
                return revenu;
            });

            individu.ressources = individu.ressources.concat(revenusLocatifs, revenusDuCapital);
        }
        var openFiscaIndividu = buildOpenFiscaEntity(individu, ind, situation);
        applyRessources(individu, openFiscaIndividu, ressourcesMap.individu, situation.dateDeValeur);
        return openFiscaIndividu;
    });
};

var mapFamille = function(situation) {
    var famille = buildOpenFiscaEntity(situation, fam, situation);
    var ressources = [];
    _.forEach(situation.individus, function(individu) {
        ressources = ressources.concat(individu.ressources);
    });
    applyRessources({ ressources: ressources }, famille, ressourcesMap.famille, situation.dateDeValeur);
    setNonInjectedPrestationsToZero(famille, situation.dateDeValeur);

    return famille;
};

var mapFoyerFiscal = exports.mapFoyerFiscal = function(situation) {
    var foyerFiscal = buildOpenFiscaEntity(situation, foy, situation);
    var ressources = [];
    _.forEach(situation.individus, function(individu) {
        ressources = ressources.concat(individu.ressources);
    });
    applyRessources({ ressources: ressources }, foyerFiscal, ressourcesMap.foyerFiscal, situation.dateDeValeur);

    return foyerFiscal;
};

exports.buildOpenFiscaRequest = function(situation, debug) {
        return {
        intermediate_variables: debug,
        labels: true,
        scenarios: [{
            test_case: {
                familles: [mapFamille(situation)],
                foyers_fiscaux: [mapFoyerFiscal(situation)],
                individus: mapIndividus(situation),
                menages: [buildOpenFiscaEntity(situation, men, situation)]
            },
            period: 'month:' + periodTools.toOpenFiscaFormat(situation.dateDeValeur)
        }],
        variables: _.keys(PRESTATIONS)
    };
};
<commit_msg>src => mesAidesEntity schema => mappingSchema<commit_after>var _ = require('lodash');
var moment = require('frozen-moment');
var periodTools = require('./periodTools');
var ressourcesMap = require('./ressources');
var ind = require('./individu');
var men = require('./menage');
var fam = require('./famille');
var foy = require('./foyerFiscal');
var common = require('./common');
var PRESTATIONS = require('../prestations');

var isNotValidValue = function(value) {
    return _.isNaN(value) || _.isUndefined(value) || value === null;
};

var getPeriods = function(dateDeValeur) {
    dateDeValeur = moment(dateDeValeur).freeze();
    return {
        moisCourant: {
            key: dateDeValeur.format('YYYY-MM')
        },
        moisPrecedent: {
            key: dateDeValeur.subtract(1, 'months').format('YYYY-MM')
        },
        moisMMoins2: {
            key: dateDeValeur.subtract(2, 'months').format('YYYY-MM')
        },
        moisMMoins3: {
            key: dateDeValeur.subtract(3, 'months').format('YYYY-MM')
        },
       anneeGlissante: {
            debut: dateDeValeur.subtract(1, 'years').subtract(1, 'months'),
            fin: dateDeValeur,
            key: 'year:' + dateDeValeur.subtract(1, 'years').format('YYYY-MM')
        },
        anneeFiscalReference: {
            key: dateDeValeur.subtract(2, 'years').year()
        },
        trimestreGlissant: {
            debut: dateDeValeur.subtract(3, 'months').subtract(1, 'months'),
            fin: dateDeValeur,
            key: dateDeValeur.subtract(3, 'months').format('YYYY-MM') + ':3'
        }
    };
};

var applyRessources = function(mesAidesEntity, openFiscaEntity, schema, dateDeValeur) {
    var periods = getPeriods(dateDeValeur);

    function isPeriodWithin(agregatKey, periode) {
        return periode.isAfter(periods[agregatKey].debut, 'month') && periode.isBefore(periods[agregatKey].fin, 'month');
    }

    var ressourcesByType = _.groupBy(mesAidesEntity.ressources, 'type');

    _.forEach(schema, function(definitions, openFiscaKey) {
        if (! _.isArray(definitions)) {
            definitions = [definitions];
        }

        _.forEach(definitions, function(definition) {

            var srcKey = definition.src || definition;
            var fn = definition.fn;

            if (ressourcesByType[srcKey]) {
                var result = {};
                var agr = {};

                _.forEach(ressourcesByType[srcKey], function(item) {
                    if (item.periode) {
                        // Période d'origine
                        if (!result[item.periode]) result[item.periode] = 0;
                        result[item.periode] += item.montant;

                        // Aggrégats
                        _.keys(periods).forEach(function (agregatKey) {
                            if (agregatKey != 'anneeFiscalReference' && isPeriodWithin(agregatKey, moment(item.periode, 'YYYY-MM'))) {
                                if (!(agregatKey in agr)) agr[agregatKey] = 0;
                                agr[agregatKey] += fn ? fn(item.montant) : item.montant;
                            }
                        });
                    }
                });

                _.forEach(result, function(montant, periode) {
                    // Applique la transformation
                    if (fn) montant = fn(montant);
                    result[periode] = montant;
                });

                // On prolonge la ressource perçue quand c'est possible
                if (result[periods.moisPrecedent.key] && !_.contains(mesAidesEntity.interruptedRessources, srcKey)) {
                    result[periods.moisCourant.key] = result[periods.moisPrecedent.key];
                }

                if (_.size(result) > 0) {
                    if (_.size(openFiscaEntity[openFiscaKey]) > 0) {
                        openFiscaEntity[openFiscaKey] = _.extend(openFiscaEntity[openFiscaKey],result);
                    } else {
                        openFiscaEntity[openFiscaKey] = result;
                    }
                }

                _.forEach(agr, function (value, agregatKey) {
                    openFiscaEntity[openFiscaKey][periods[agregatKey].key] = value;
                });

                // On suppose que les revenus pour l'année fiscale de référence sont les mêmes que pour les 12 derniers mois, si ces revenus n'ont pas encore
                // été renseignés
                var anneeGlissanteKey = periods.anneeGlissante.key,
                    anneeFiscaleRefKey = periods.anneeFiscalReference.key;
                if (! openFiscaEntity[openFiscaKey][anneeFiscaleRefKey]) {
                    openFiscaEntity[openFiscaKey][anneeFiscaleRefKey] = openFiscaEntity[openFiscaKey][anneeGlissanteKey];
                }
            }
        });
    });
};

var setNonInjectedPrestationsToZero = function(openFiscaEntity, dateDeValeur) {
    var periods = getPeriods(dateDeValeur);
    var concernedPeriods = ['moisPrecedent', 'moisMMoins2', 'moisMMoins3', 'anneeGlissante'];

    _.forEach(concernedPeriods, function(periodKey) {
        var period = periods[periodKey].key;
        var prestations = _.pick(PRESTATIONS, function(definition) {
            return definition.type == Number;
        });

        _.forEach(prestations, function(definition, prestationName) {
            if (! openFiscaEntity[prestationName]) {
                openFiscaEntity[prestationName] = {};
            }
            if (! openFiscaEntity[prestationName][period]) {
                openFiscaEntity[prestationName][period] = 0;
            }
        });

    });

};

var buildOpenFiscaEntity = function(mesAidesEntity, mappingSchema, situation) {
    var result = {};
    _.forEach(mappingSchema, function(definition, openFiscaKey) {
        var params = _.isString(definition) ? { src: definition } : definition;

        if (params.values) {
            result[openFiscaKey] = params.values[mesAidesEntity[params.src]];
        } else if (params.fn) {
            result[openFiscaKey] = params.src ? params.fn(mesAidesEntity[params.src], mesAidesEntity, situation) : params.fn(mesAidesEntity, situation);
        } else {
            result[openFiscaKey] = mesAidesEntity[params.src];
        }

        if (params.round && _.isNumber(result[openFiscaKey])) {
            result[openFiscaKey] = Math.round(result[openFiscaKey]);
        }

        // Supprime les null (mal supportés par OpenFisca)
        if (isNotValidValue(result[openFiscaKey])) {
            if ('default' in params) result[openFiscaKey] = params.default;
            else delete result[openFiscaKey];
        }
    });
    return result;
};

var mapIndividus = exports.mapIndividus = function (situation) {
    var individus = _.filter(situation.individus, function(individu) {
        return common.isIndividuValid(individu, situation);
    });

    return _.map(individus, function(individu) {
        if (individu.role === 'demandeur') {
            _.extend(individu, situation.patrimoine);

            var revenusLocatifs = situation.patrimoine.revenusLocatifs.map(function(revenu) {
                revenu.type = 'revenusLocatifs';
                return revenu;
            });

            var revenusDuCapital = situation.patrimoine.revenusDuCapital.map(function(revenu) {
                revenu.type = 'revenusDuCapital';
                return revenu;
            });

            individu.ressources = individu.ressources.concat(revenusLocatifs, revenusDuCapital);
        }
        var openFiscaIndividu = buildOpenFiscaEntity(individu, ind, situation);
        applyRessources(individu, openFiscaIndividu, ressourcesMap.individu, situation.dateDeValeur);
        return openFiscaIndividu;
    });
};

var mapFamille = function(situation) {
    var famille = buildOpenFiscaEntity(situation, fam, situation);
    var ressources = [];
    _.forEach(situation.individus, function(individu) {
        ressources = ressources.concat(individu.ressources);
    });
    applyRessources({ ressources: ressources }, famille, ressourcesMap.famille, situation.dateDeValeur);
    setNonInjectedPrestationsToZero(famille, situation.dateDeValeur);

    return famille;
};

var mapFoyerFiscal = exports.mapFoyerFiscal = function(situation) {
    var foyerFiscal = buildOpenFiscaEntity(situation, foy, situation);
    var ressources = [];
    _.forEach(situation.individus, function(individu) {
        ressources = ressources.concat(individu.ressources);
    });
    applyRessources({ ressources: ressources }, foyerFiscal, ressourcesMap.foyerFiscal, situation.dateDeValeur);

    return foyerFiscal;
};

exports.buildOpenFiscaRequest = function(situation, debug) {
        return {
        intermediate_variables: debug,
        labels: true,
        scenarios: [{
            test_case: {
                familles: [mapFamille(situation)],
                foyers_fiscaux: [mapFoyerFiscal(situation)],
                individus: mapIndividus(situation),
                menages: [buildOpenFiscaEntity(situation, men, situation)]
            },
            period: 'month:' + periodTools.toOpenFiscaFormat(situation.dateDeValeur)
        }],
        variables: _.keys(PRESTATIONS)
    };
};
<|endoftext|>


<commit_before>var persistence = require("./persistence");
var Promise = require("bluebird");

var apiPath = "/v1";

var getRoutes = [
	{
		url: "/contest",
		handler: function(req, res) {
			// Get related games
			var getGames = function(dataObj) {
				return new Promise(function(resolve, reject) {
					var gameIds = dataObj.contests.map(contest => contest.game);
					persistence.fetchIn("game", gameIds)
						.then(function(dbData) {
							dataObj.games = dbData;
							resolve(dataObj);
						});
				});
			};
			// Get related tracks
			var getTracks = function(dataObj) {
				return new Promise(function(resolve, reject) {
					var trackIds = dataObj.contests.map(contest => contest.track);
					persistence.fetchIn("track", trackIds)
						.then(function(dbData) {
							dataObj.tracks = dbData;
							resolve(dataObj);
						});
				});
			};
			// Get related cars
			var getCars = function(dataObj) {
				return new Promise(function(resolve, reject) {
					var carIds = dataObj.contests.map(contest => contest.car);
						persistence.fetchIn("car", carIds)
							.then(function(dbData) {
								dataObj.cars = dbData;
								resolve(dataObj);
							});
				});
			};

			// Get list of contests
			var parseContests = function(data) {
				res.send(data);
			}
			var contests = persistence.fetchAll("contest")
				.then(getGames)
				.then(getTracks)
				.then(getCars)
				.then(parseContests);
		}
	},
	{
		url: "/contest/:id",
		handler: function(req, res) {
			var getGames = function(dataObj) {
				return new Promise(function(resolve, reject) {
					persistence.fetch("game", dataObj.game)
						.then(function(dbData) {
							dataObj.game = dbData.name;
							resolve(dataObj);
						});
				});
			};
			// Get related tracks
			var getTracks = function(dataObj) {
				return new Promise(function(resolve, reject) {
					persistence.fetch("track", dataObj.track)
						.then(function(dbData) {
							dataObj.track = dbData.name;
							resolve(dataObj);
						});
				});
			};
			// Get related cars
			var getCars = function(dataObj) {
				return new Promise(function(resolve, reject) {
					persistence.fetch("car", dataObj.car)
						.then(function(dbData) {
							dataObj.car = dbData.name;
							resolve(dataObj);
						});
				});
			};

			// Get related cars
			var getRecords = function(dataObj) {
				return new Promise(function(resolve, reject) {
					var query = "SELECT * FROM record WHERE contest = " + dataObj.contestid;
					persistence.rawGet(query)
						.then(function(dbData) {
							dataObj.records = dbData;
							resolve(dataObj);
						});
				});
			};

			// Get list of contests
			var parseContests = function(data) {
				data.records = data.records || [];
				res.send(data);
			}
			var contests = persistence.fetch("contest", req.params.id)
				.then(getGames)
				.then(getTracks)
				.then(getCars)
				.then(getRecords)
				.then(parseContests);
		}
	},
	{
		url: "/:entity",
		handler: function (req, res) {
			persistence.fetchAll(req.params.entity)
				.then(function(result) {
					res.send(result);
				});
		}
	},
	{
		url: "/:entity/:id",
		handler: function (req, res) {
			persistence.fetch(req.params.entity, req.params.id)
				.then(function(result) {
					res.send(result);
				});
		}
	},
	{
		url: "/:entity/:id/full",
		handler: function (req, res) {
			persistence.fetchFull(req.params.entity, req.params.id)
				.then(function(result) {
					res.send(result);
				});
		}
	}
];

var postRoutes = [
	{
		url: "/player",
		handler: function (req, res) {
			console.log("Adding player");
			persistence.insert("player", req.body.player)
				.then(function(status, something) {
					res.status(status ? 200 : 418).send("Added player");
				});
		}
	},
	{
		url: "/game",
		handler: function (req, res) {
			console.log("Adding game");
			persistence.insert("game", req.body.game)
				.then(function(status) {
					res.status(status ? 200 : 418).send("Added game");
				});
		}
	},
	{
		url: "/track",
		handler: function (req, res) {
			console.log("Adding track");
			persistence.insert("track", req.body.track)
				.then(function(status) {
					res.status(status ? 200 : 418).send("Added track");
				});
		}
	},
	{
		url: "/car",
		handler: function (req, res) {
			console.log("Adding car");
			persistence.insert("car", req.body.car)
				.then(function(status) {
					res.status(status ? 200 : 418).send("Added car");
				});
		}
	},
	{
		url: "/record",
		handler: function (req, res) {
			console.log("Adding record");
			var params = [
				req.body.time,
				req.body.gameid,
				req.body.playerid,
				req.body.trackid,
				req.body.carid
			]
			persistence.insert("record", params)
				.then(function(status, something) {
					console.log("Record inserted", JSON.stringify(params));
				});
		}
	}
];

module.exports = {
	apiPath: apiPath,
	getRoutes: getRoutes,
	postRoutes: postRoutes
};<commit_msg>contest list api finalization<commit_after>var _ = require("lodash");
var persistence = require("./persistence");
var Promise = require("bluebird");

var apiPath = "/v1";

var getRoutes = [
	{
		url: "/contest",
		handler: function(req, res) {
			// Get related games
			var getGames = function(dataObj) {
				return new Promise(function(resolve, reject) {
					var gameIds = dataObj.contests.map(contest => contest.game);
					persistence.fetchIn("game", gameIds)
						.then(function(dbData) {
							dataObj.games = dbData;
							resolve(dataObj);
						});
				});
			};
			// Get related tracks
			var getTracks = function(dataObj) {
				return new Promise(function(resolve, reject) {
					var trackIds = dataObj.contests.map(contest => contest.track);
					persistence.fetchIn("track", trackIds)
						.then(function(dbData) {
							dataObj.tracks = dbData;
							resolve(dataObj);
						});
				});
			};
			// Get related cars
			var getCars = function(dataObj) {
				return new Promise(function(resolve, reject) {
					var carIds = dataObj.contests.map(contest => contest.car);
						persistence.fetchIn("car", carIds)
							.then(function(dbData) {
								dataObj.cars = dbData;
								resolve(dataObj);
							});
				});
			};

			// Get list of contests
			var parseContests = function(data) {
				data.contests.forEach(contest => {
					var game = _.find(data.games, game => game.gameid === contest.game);
					contest.game = game ? game.name : "error";
					var track = _.find(data.tracks, track => track.trackid === contest.track);
					contest.track = track ? track.name : "error";
					var car = _.find(data.cars, car => car.carid === contest.car);
					contest.car = car ? car.name : "error";
				});
				res.send({contests: data.contests});
			}
			var contests = persistence.fetchAll("contest")
				.then(getGames)
				.then(getTracks)
				.then(getCars)
				.then(parseContests);
		}
	},
	{
		url: "/contest/:id",
		handler: function(req, res) {
			var getGames = function(dataObj) {
				return new Promise(function(resolve, reject) {
					persistence.fetch("game", dataObj.game)
						.then(function(dbData) {
							dataObj.game = dbData.name;
							resolve(dataObj);
						});
				});
			};
			// Get related tracks
			var getTracks = function(dataObj) {
				return new Promise(function(resolve, reject) {
					persistence.fetch("track", dataObj.track)
						.then(function(dbData) {
							dataObj.track = dbData.name;
							resolve(dataObj);
						});
				});
			};
			// Get related cars
			var getCars = function(dataObj) {
				return new Promise(function(resolve, reject) {
					persistence.fetch("car", dataObj.car)
						.then(function(dbData) {
							dataObj.car = dbData.name;
							resolve(dataObj);
						});
				});
			};

			// Get related cars
			var getRecords = function(dataObj) {
				return new Promise(function(resolve, reject) {
					var query = "SELECT * FROM record WHERE contest = " + dataObj.contestid;
					persistence.rawGet(query)
						.then(function(dbData) {
							dataObj.records = dbData;
							resolve(dataObj);
						});
				});
			};

			// Get list of contests
			var parseContests = function(data) {
				data.records = data.records || [];
				res.send(data);
			}
			var contests = persistence.fetch("contest", req.params.id)
				.then(getGames)
				.then(getTracks)
				.then(getCars)
				.then(getRecords)
				.then(parseContests);
		}
	},
	{
		url: "/:entity",
		handler: function (req, res) {
			persistence.fetchAll(req.params.entity)
				.then(function(result) {
					res.send(result);
				});
		}
	},
	{
		url: "/:entity/:id",
		handler: function (req, res) {
			persistence.fetch(req.params.entity, req.params.id)
				.then(function(result) {
					res.send(result);
				});
		}
	},
	{
		url: "/:entity/:id/full",
		handler: function (req, res) {
			persistence.fetchFull(req.params.entity, req.params.id)
				.then(function(result) {
					res.send(result);
				});
		}
	}
];

var postRoutes = [
	{
		url: "/player",
		handler: function (req, res) {
			console.log("Adding player");
			persistence.insert("player", req.body.player)
				.then(function(status, something) {
					res.status(status ? 200 : 418).send("Added player");
				});
		}
	},
	{
		url: "/game",
		handler: function (req, res) {
			console.log("Adding game");
			persistence.insert("game", req.body.game)
				.then(function(status) {
					res.status(status ? 200 : 418).send("Added game");
				});
		}
	},
	{
		url: "/track",
		handler: function (req, res) {
			console.log("Adding track");
			persistence.insert("track", req.body.track)
				.then(function(status) {
					res.status(status ? 200 : 418).send("Added track");
				});
		}
	},
	{
		url: "/car",
		handler: function (req, res) {
			console.log("Adding car");
			persistence.insert("car", req.body.car)
				.then(function(status) {
					res.status(status ? 200 : 418).send("Added car");
				});
		}
	},
	{
		url: "/record",
		handler: function (req, res) {
			console.log("Adding record");
			var params = [
				req.body.time,
				req.body.gameid,
				req.body.playerid,
				req.body.trackid,
				req.body.carid
			]
			persistence.insert("record", params)
				.then(function(status, something) {
					console.log("Record inserted", JSON.stringify(params));
				});
		}
	}
];

module.exports = {
	apiPath: apiPath,
	getRoutes: getRoutes,
	postRoutes: postRoutes
};<|endoftext|>


<commit_before>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');

var TaskmasterGenerator = module.exports = function TaskmasterGenerator(args, options, config) {
  yeoman.generators.Base.apply(this, arguments);

  this.on('end', function () {
    this.installDependencies({ skipInstall: options['skip-install'] });
  });

  this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

util.inherits(TaskmasterGenerator, yeoman.generators.Base);

TaskmasterGenerator.prototype.askFor = function askFor() {
  var cb = this.async();

  // have Yeoman greet the user.
  console.log(this.yeoman);

  var prompts = [
  {
    name:    'siteName',
    message: 'What is the name of your site or project?',
  },
  {
    name:    'authorName',
    message: 'Who is the creator of this site?',
    default: "Carlos Ortega"
  }
  ];

  this.prompt(prompts, function (props) {
    this.siteName   = props.siteName;
    this.authorName = props.authorName;
    cb();
  }.bind(this));
};

TaskmasterGenerator.prototype.app = function app() {
  this.mkdir('site');
  this.mkdir('site/styles');
  this.mkdir('site/scripts');
  this.mkdir('site/images');

  this.copy('_package.json', 'package.json');
  this.copy('_bower.json', 'bower.json');
  this.copy('_GruntFile.js', 'GruntFile.js');
  this.copy('_gitignore', '.gitignore');

  this.copy('_script.coffee', 'site/scripts/scripts.coffee');
  this.copy('_style.styl', 'site/styles/styles.styl');
  this.template('_index.jade', 'site/index.jade');
};

// TaskmasterGenerator.prototype.projectfiles = function projectfiles() {
//   this.copy('editorconfig', '.editorconfig');
//   this.copy('jshintrc', '.jshintrc');
// };
<commit_msg>change site to src<commit_after>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');

var TaskmasterGenerator = module.exports = function TaskmasterGenerator(args, options, config) {
  yeoman.generators.Base.apply(this, arguments);

  this.on('end', function () {
    this.installDependencies({ skipInstall: options['skip-install'] });
  });

  this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

util.inherits(TaskmasterGenerator, yeoman.generators.Base);

TaskmasterGenerator.prototype.askFor = function askFor() {
  var cb = this.async();

  // have Yeoman greet the user.
  console.log(this.yeoman);

  var prompts = [
  {
    name:    'siteName',
    message: 'What is the name of your site or project?',
  },
  {
    name:    'authorName',
    message: 'Who is the creator of this site?',
    default: "Carlos Ortega"
  }
  ];

  this.prompt(prompts, function (props) {
    this.siteName   = props.siteName;
    this.authorName = props.authorName;
    cb();
  }.bind(this));
};

TaskmasterGenerator.prototype.app = function app() {
  this.mkdir('src');
  this.mkdir('src/styles');
  this.mkdir('src/scripts');
  this.mkdir('src/images');

  this.copy('_package.json', 'package.json');
  this.copy('_bower.json', 'bower.json');
  this.copy('_GruntFile.js', 'GruntFile.js');
  this.copy('_gitignore', '.gitignore');

  this.copy('_script.coffee', 'src/scripts/scripts.coffee');
  this.copy('_style.styl', 'src/styles/styles.styl');
  this.template('_index.jade', 'src/index.jade');
};

// TaskmasterGenerator.prototype.projectfiles = function projectfiles() {
//   this.copy('editorconfig', '.editorconfig');
//   this.copy('jshintrc', '.jshintrc');
// };
<|endoftext|>


<commit_before>/**
 * Terminal core script
 * jQuery plugin for ascii terminal window
 * Espen Andersen, Norwegian Broadcast Corporation
 * espen.andersen@nrk.no
 * (c) 2013 - NRK Investigative unit
 * Released under the MIT license
 * http://opensource.org/licenses/MIT
 */
( function( $ ) {

	var
		ROOT_SELECTOR = '.__window__manager__root__',

		that,
		root,
		persistent = { windows: { } },

		public_members = {
			'close_window': closeWindow,
			'move_window': moveWindow,
			'open_window': openWindow,
			'send_message': sendMessage
		};

	// Produce a random, unique hexadecimal ID string
	function getUniqueId( prefix ) {
		return 	prefix +
					 String( '00000000' +
							 Math.floor( 0xFFFFFFFF * Math.random() )
							.toString( 16 ) )
					.slice( -8 );
	}

	// brings specified window to the front, normalizing but preserving
	// the z-order index for the other windows
	function bringToFront( hWnd ) {

		var
			i,

			hierarchy =
				root
					.find( '.window' )
					.toArray();

		persistent.windows[ hWnd ].css( 'z-index', 9999 );
		hierarchy.sort( function( a, b ) {
			return ( Number( a.style.zIndex ) - Number( b.style.zIndex ) );
		} );

		for( i = 0; i < hierarchy.length; i++ ) {
			$( hierarchy[ i ] ).css( 'z-index', 10 + i );
		}
	}

	function closeWindow( param ) {

		var
			hWnd = typeof param === 'object' ? param.hWnd : param;

		if( persistent.windows[ hWnd ] ) {

			var

				win =
					root
						.find( '#' + hWnd ),

				winInfo =
					win.data( 'wininfo' );

			sendMessage( { msg: 'wm_before_close' }, winInfo.hWnd );

			win.removeData( 'wininfo' );

			delete winInfo.hWnd;

			win
				.remove();

			delete persistent.windows[ hWnd ];

			var e = new $.Event( 'notify' );
			e.msg = 'close_window';
			e.winInfo = winInfo;
			that.trigger( e );
		}
	}

	function createWindow( param ) {

		var

			styles = { display: 'none' },

			winCount = root.find( '.window' ).length,

			winInfo = {
				eventDispatcher: that,
				windowManager: root,
				hWnd: getUniqueId( 'win_' ),
				wndTitle: ( param && param.wndTitle ) || '',
				wndClass: ( param && param.wndClass ) || 'default',
				wndClose: ( param && param.wndClose ) || ''
			};

			if( param ) {
				if( param.width ) styles.width = param.width;
				if( param.height ) styles.height = param.height;
			}
			else {
				param = { };
			}

			if( styles.left === undefined ) {
				styles.left = winCount * 30;
			}

			if( styles.top === undefined ) {
				styles.top = winCount * 30;
			}

		var newWin = { };
		newWin[ winInfo.hWnd ] =

			root
				.prepend( 	'
' +
						   		'
' +
									winInfo.wndTitle +
									' X' +
								'
' +
								'
' +
								'
' +
							'
' )

				.find( '#' + winInfo.hWnd )
				.addClass( winInfo.wndClass )
				.data( 'wininfo', winInfo )
				.css( styles )
				.draggable( {
					handle: 'h2',
					start:
						function( e ) {
							bringToFront( $( e.target ).closest( '.window' ).attr( 'id' ) );
						}
				} )
				.find( '.titleBar .close' )
				.click( function( e ) {
					var
						hWnd =
							$( e.target )
								.closest( '.window' )
								.attr( 'id' );

					closeWindow( hWnd );
					e.preventDefault();
				} )
				.end();

		persistent.windows = $.extend( { }, persistent.windows, newWin );

		param && param.wndProc && param.wndProc( winInfo );

		return winInfo;
	}

	function defaultWndProc( winInfo ) {
		showWindow( winInfo.hWnd );
	}

	function init( _options ) {
		root =
			$( that )
				.html( '

' )
				.find( ROOT_SELECTOR );
		root
			.on( 'click', '.window', function( e ) {
				$( e.target )
					.closest( '.window' )
					.each( function( index, win ) {
						bringToFront( $( win ).attr( 'id' ) );
					} )
					.siblings( '.focus' )
					.removeClass( 'focus' )
					.end()
					.addClass( 'focus' );

			} );
	}

	// Move a window
	function moveWindow( hWnd, pos ) {
		root
			.find( '#' + hWnd )
			.css( {
				top: pos.top,
				left: pos.left } );
	}

	function openWindow( param ) {

		var winInfo;

		if( param === undefined ||
			param.hWnd === undefined ||
			persistent.windows[ param.hWnd ] === undefined ) {

			winInfo = createWindow( param );
		}
		else {
			winInfo = param;
		}

		showWindow( winInfo.hWnd );
	}

	function savePersistent() {
		root
			.data( 'persistent', persistent );
	}

	function sendMessage( param, hWnd ) {
		if( param && param.msg ) {
			var
				e = new $.Event( param.msg ),
				selector = hWnd !== undefined ? '#' + hWnd : '.window';
			e.msg = param.msg;
			e.param = param;
			root
				.find( selector )
				.trigger( e );
		}
	}

	function showWindow( hWnd ) {

		var
			wnd = persistent.windows[ hWnd ];

		bringToFront( hWnd );

		if( wnd !== undefined ) {
			$( wnd )
				.hide()
				.fadeIn( 250 );
		}
	}

	// Expose interface
	$.fn.windowManager = function( param ) {

		var retVal,
			index = 0,
			argv = arguments,
			argc = argv.length;

		this.each( function() {
			that = $( this );
			if( param === undefined || typeof param === 'object' ) {
				// Initialization
				init.apply( this, [ param ] );
				savePersistent();
			}
			else if( public_members[ param ] !== undefined ) {
				// Call to public member
				root = that.find( ROOT_SELECTOR );
				persistent = $( root ).data( 'persistent' );
				retVal = public_members[ param ].apply( this, Array.prototype.slice.call( argv, 1 ) );
				// Callback func should be the last argument
				if( argc > 0 && typeof argv[ argc - 1 ] === 'function' ) {
					// Pass return value for each element to callback function
					( argv[ argc - 1 ] )( index, retVal );
					savePersistent();
					retVal = null;
				}
				else {
					savePersistent();
					// No callback; break loop if return value was present
					if( retVal ) return false;
				}
			}
			else {
				$.error( 'Method not found in windowManager' );
			}
			index++;
		} );
		// Maintain chainability unless returning something
		return retVal || this;
	}

} )( jQuery );<commit_msg>added some comments<commit_after>/**
 * Terminal/WindowManager core script
 * jQuery plugin for opening windows from the terminal
 * Espen Andersen, Norwegian Broadcast Corporation
 * espen.andersen@nrk.no
 * (c) 2013 - NRK Investigative unit
 * Released under the MIT license
 * http://opensource.org/licenses/MIT
 */
( function( $ ) {

	var
		ROOT_SELECTOR = '.__window__manager__root__',

		that,
		root,
		persistent = { windows: { } },

		public_members = {
			'close_window': closeWindow,
			'move_window': moveWindow,
			'open_window': openWindow,
			'send_message': sendMessage
		};

	// Produce a random, unique hexadecimal ID string
	function getUniqueId( prefix ) {
		return 	prefix +
					 String( '00000000' +
							 Math.floor( 0xFFFFFFFF * Math.random() )
							.toString( 16 ) )
					.slice( -8 );
	}

	// brings specified window to the front, normalizing but preserving
	// the z-order index for the other windows
	function bringToFront( hWnd ) {

		var
			i,

			hierarchy =
				root
					.find( '.window' )
					.toArray();

		persistent.windows[ hWnd ].css( 'z-index', 9999 );
		hierarchy.sort( function( a, b ) {
			return ( Number( a.style.zIndex ) - Number( b.style.zIndex ) );
		} );

		for( i = 0; i < hierarchy.length; i++ ) {
			$( hierarchy[ i ] ).css( 'z-index', 10 + i );
		}
	}

	// Close window, param must be either the window handle,
	// or an object with the handle stored in a hWnd property.
	function closeWindow( param ) {

		var
			hWnd = typeof param === 'object' ? param.hWnd : param;

		if( persistent.windows[ hWnd ] ) {

			var

				win =
					root
						.find( '#' + hWnd ),

				winInfo =
					win.data( 'wininfo' );

			sendMessage( { msg: 'wm_before_close' }, winInfo.hWnd );

			win.removeData( 'wininfo' );

			delete winInfo.hWnd;

			win
				.remove();

			delete persistent.windows[ hWnd ];

			var e = new $.Event( 'notify' );
			e.msg = 'close_window';
			e.winInfo = winInfo;
			that.trigger( e );
		}
	}

	// Create new window
	function createWindow( param ) {

		var

			styles = { display: 'none' },

			winCount = root.find( '.window' ).length,

			winInfo = {
				eventDispatcher: that,
				windowManager: root,
				hWnd: getUniqueId( 'win_' ),
				wndTitle: ( param && param.wndTitle ) || '',
				wndClass: ( param && param.wndClass ) || 'default',
				wndClose: ( param && param.wndClose ) || ''
			};

			if( param ) {
				if( param.width ) styles.width = param.width;
				if( param.height ) styles.height = param.height;
			}
			else {
				param = { };
			}

			// Default positioning:
			if( styles.left === undefined ) {
				styles.left = winCount * 30;
			}
			if( styles.top === undefined ) {
				styles.top = winCount * 30;
			}

		var newWin = { };
		newWin[ winInfo.hWnd ] =

			root
				.prepend( 	'
' +
						   		'
' +
									winInfo.wndTitle +
									' X' +
								'
' +
								'
' +
								'
' +
							'
' )

				.find( '#' + winInfo.hWnd )
				.addClass( winInfo.wndClass )
				.data( 'wininfo', winInfo )
				.css( styles )
				.draggable( {
					handle: 'h2',
					start:
						function( e ) {
							bringToFront( $( e.target ).closest( '.window' ).attr( 'id' ) );
						}
				} )
				.find( '.titleBar .close' )
				.click( function( e ) {
					var
						hWnd =
							$( e.target )
								.closest( '.window' )
								.attr( 'id' );

					closeWindow( hWnd );
					e.preventDefault();
				} )
				.end();

		persistent.windows = $.extend( { }, persistent.windows, newWin );

		param && param.wndProc && param.wndProc( winInfo );

		return winInfo;
	}

	// Default window proc displays en empty window
	function defaultWndProc( winInfo ) {
		showWindow( winInfo.hWnd );
	}

	// Initialize WindowManager
	function init( _options ) {
		root =
			$( that )
				.html( '

' )
				.find( ROOT_SELECTOR );
		root
			.on( 'click', '.window', function( e ) {
				$( e.target )
					.closest( '.window' )
					.each( function( index, win ) {
						bringToFront( $( win ).attr( 'id' ) );
					} )
					.siblings( '.focus' )
					.removeClass( 'focus' )
					.end()
					.addClass( 'focus' );

			} );
	}

	// Move a window
	function moveWindow( hWnd, pos ) {
		root
			.find( '#' + hWnd )
			.css( {
				top: pos.top,
				left: pos.left } );
	}

	// Open a window, create new if no handle to existing window is provided
	function openWindow( param ) {

		var winInfo;

		if( param === undefined ||
			param.hWnd === undefined ||
			persistent.windows[ param.hWnd ] === undefined ) {

			winInfo = createWindow( param );
		}
		else {
			winInfo = param;
		}

		showWindow( winInfo.hWnd );
	}

	// WindowManager data store
	function savePersistent() {
		root
			.data( 'persistent', persistent );
	}

	// Send message to one or all windows. If no handle is provided
	// (i.e. undefined), the message is broadcasted to all windows
	function sendMessage( param, hWnd ) {
		if( param && param.msg ) {
			var
				e = new $.Event( param.msg ),
				selector = hWnd !== undefined ? '#' + hWnd : '.window';
			e.msg = param.msg;
			e.param = param;
			root
				.find( selector )
				.trigger( e );
		}
	}

	// Make window visible
	function showWindow( hWnd ) {

		var
			wnd = persistent.windows[ hWnd ];

		bringToFront( hWnd );

		if( wnd !== undefined ) {
			$( wnd )
				.hide()
				.fadeIn( 250 );
		}
	}

	// Expose interface
	$.fn.windowManager = function( param ) {

		var retVal,
			index = 0,
			argv = arguments,
			argc = argv.length;

		this.each( function() {
			that = $( this );
			if( param === undefined || typeof param === 'object' ) {
				// Initialization
				init.apply( this, [ param ] );
				savePersistent();
			}
			else if( public_members[ param ] !== undefined ) {
				// Call to public member
				root = that.find( ROOT_SELECTOR );
				persistent = $( root ).data( 'persistent' );
				retVal = public_members[ param ].apply( this, Array.prototype.slice.call( argv, 1 ) );
				// Callback func should be the last argument
				if( argc > 0 && typeof argv[ argc - 1 ] === 'function' ) {
					// Pass return value for each element to callback function
					( argv[ argc - 1 ] )( index, retVal );
					savePersistent();
					retVal = null;
				}
				else {
					savePersistent();
					// No callback; break loop if return value was present
					if( retVal ) return false;
				}
			}
			else {
				$.error( 'Method not found in windowManager' );
			}
			index++;
		} );
		// Maintain chainability unless returning something
		return retVal || this;
	}

} )( jQuery );<|endoftext|>


<commit_before>'use strict';

var path = require('path');
var util = require('util');
var yeoman = require('yeoman-generator');
var chalk = require('chalk');

var Generator = module.exports = function Generator(args, options, config) {
    yeoman.generators.Base.apply(this, arguments);

    // set source root path to templates
    this.sourceRoot(path.join(__dirname, 'templates'));
};

util.inherits(Generator, yeoman.generators.Base);

Generator.prototype.welcome = function welcome() {
    // welcome message
    if (!this.options['skip-welcome-message']) {
        console.log(this.yeoman);
        console.log(
            'Out of the box I include Bootstrap and some AngularJS recommended modules.\n'
        );
    }
};

Generator.prototype.createFolder = function createFolder() {
    // create folders
    this.mkdir('Public');
    this.mkdir('Public/js/controllers');
    this.mkdir('Public/js/directives');
    this.mkdir('Public/js/filters');
    this.mkdir('Public/js/services');
    this.mkdir('Public/js/css/bootstrap/css');
    this.mkdir('Public/js/css/bootstrap/fonts');
    this.mkdir('Public/js/views/Home/partials');
    this.mkdir('Helpers');
};<commit_msg>askForVirtualDirectory and ApplicateName if needed.<commit_after>'use strict';

var path = require('path');
var util = require('util');
var yeoman = require('yeoman-generator');
var chalk = require('chalk');

var Generator = module.exports = function Generator(args, options, config) {
    yeoman.generators.Base.apply(this, arguments);

    // set source root path to templates
    this.sourceRoot(path.join(__dirname, 'templates'));
};

util.inherits(Generator, yeoman.generators.Base);

Generator.prototype.welcome = function welcome() {
    // welcome message
    if (!this.options['skip-welcome-message']) {
        console.log(this.yeoman);
        console.log(
            'Out of the box I include Bootstrap and some AngularJS recommended modules.\n'
        );
    }
};

Generator.prototype.createFolder = function createFolder() {
    // create folders
    this.mkdir('Public');
    this.mkdir('Public/js/controllers');
    this.mkdir('Public/js/directives');
    this.mkdir('Public/js/filters');
    this.mkdir('Public/js/services');
    this.mkdir('Public/js/css/bootstrap/css');
    this.mkdir('Public/js/css/bootstrap/fonts');
    this.mkdir('Public/js/views/Home/partials');
    this.mkdir('Helpers');
};

Generator.prototype.askForVirtualDirectory = function askForVirtualDirectory() {
    var cb = this.async();

    var prompts = [{
        name: 'hasVirtualDirectory',
        message: 'Do your ASP.NET MVC Appliation run in virtualDirectory? (http://localhost/ApplicationName)',
        default: true
    }];

    this.prompt(prompts, function (props) {
        this.env.options.hasVirtualDirectory = props.hasVirtualDirectory;

        cb();
    }.bind(this));
}

Generator.prototype.askApplicationName = function askApplicationName() {
    var cb = this.async();
    var prompts;
    if (this.env.options.hasVirtualDirectory === true) {
        prompts = [{
            name: 'applicationName',
            message: 'What would you like to call Appliation name? (http://localhost/ApplicationName)',
            default: 'ApplicationName'
        }];
    } else {
        prompts = [];
    }

    this.prompt(prompts, function (props) {
        this.env.options.applicationName = props.applicationName;

        cb();
    }.bind(this));
};<|endoftext|>


<commit_before>/* global $ */
/* global Ladda */
/* global requirejs */

'use strict';

var exec = require('child_process').execFile;
var spawn = require('child_process').spawn;
var ipc = require("electron-safe-ipc/guest");

var userData;
var l = Ladda.create($('#start').get(0));
var logs = requirejs('./modules/logs');

exports.child;
exports.currentProcess;

exports.init = function() {
	userData = requirejs('./modules/userdata')
	ipc.on('farm', exports.farm);
	ipc.on('terminateProcess', exports.terminateProcess);

	$('#start').on('click', function (e) {
		if(exports.currentProcess) {
			exports.terminateProcess();
		} else if(userData.hasValidSettings()) {
			exports.farm();
		}
	});
};

var realizeUI = function() {
	var isDisabled = exports.currentProcess !== null;

	$(".main").toggleClass('disabled', isDisabled );
	$("#address").prop('disabled', isDisabled);
	$("#directory").prop('disabled', isDisabled);
	$("#browse").prop('disabled', isDisabled);
	$("#size").prop('disabled', isDisabled);
	$('#size-unit').prop('disabled', isDisabled);

	if(isDisabled) {
		l.start();
		$('#start').prop('disabled', false); // l.start causes the bootstrap button to be unclickable, this ensures we can still click the button
		$('#start').css({ 'background-color': '#FFA500', 'border-color': '#FFA500' }); // orange
		$('#start-label').text('RUNNING, CLICK TO ABORT');
	} else {
		l.stop();
		$('#start').css({ 'background-color': '#88C425', 'border-color': '#88C425' }); // green
		$('#start-label').text('START');
	}
}

var bootstrapProcess = function(name, args) {

	exports.terminateProcess();
	exports.currentProcess = name;

	var output = userData.dataservClient + " ";
	for(var i = 0; i < args.length; ++i) {
		output += args[i];
		if(i < args.length - 1) {
			output += ' ';
		}
	}
	logs.addLog(output);
	console.log(output);

	exports.child = spawn(userData.dataservClient, args);
	exports.child.stdout.on('data', function (data) {
		var output = data.toString();
		logs.addLog(output);
		console.log(output);
	});
	exports.child.stderr.on('data', function (data) {
		var output = data.toString();
		logs.addLog(output);
		console.log(output);
	});

	ipc.send('processStarted');
	realizeUI();
};

exports.farm = function() {
	if(userData.hasValidSettings()) {
		bootstrapProcess('FARMING', ['--store_path=' + userData.dataservDirectory, '--max_size=' + userData.dataservSize, 'farm']);
	}
}

exports.build = function() {
	if(userData.hasValidSettings()) {
		bootstrapProcess('BUILDING', ['--store_path=' + userData.dataservDirectory, '--max_size=' + userData.dataservSize, 'build']);
	}
}

exports.register = function() {
	if(userData.hasValidSettings()) {
		bootstrapProcess('REGISTERING', ['register']);
	}
};

exports.poll = function() {
	if(userData.hasValidSettings()) {
		bootstrapProcess('POLLING', ['poll']);
	}
};

exports.saveConfig = function() {
	if(userData.hasValidDataservClient() && userData.hasValidPayoutAddress()) {
		exec(userData.dataservClient, ['config', '--set_payout_address=' + userData.payoutAddress]);
	}
}

exports.validateDataservClient = function(callback) {
	if(userData.hasValidDataservClient()) {
		exec(userData.dataservClient, ['version'], function(err, out, code) {
			var output;
			if(err) {
				output = err.toString();
			} else if(out === undefined || out === '') {
				output = 'invalid dataserv-client';
			}
			else {
				requirejs('./modules/logs').addLog('dataserv-client version ' + out);
			}
			if(callback) {
				callback(output);
			}
		});
	} else if(callback) {
		callback('invalid dataserv-client');
	}
}

exports.terminateProcess = function() {
	if(exports.child) {
		logs.addLog('exports.child ' + exports.child.pid + ' terminated');
		exports.child.kill();
		exports.child = null;
		exports.currentProcess = null;
		ipc.send('processTerminated');
		realizeUI();
		Ladda.create($('#start')).stop();
		$('#start').css({ 'background-color': '#88C425', 'border-color': '#88C425' }); // green
		$('#start-label').text('START');
	}
}<commit_msg>Fixed bug where size unit wasn't being sent to dataserv-client<commit_after>/* global $ */
/* global Ladda */
/* global requirejs */

'use strict';

var exec = require('child_process').execFile;
var spawn = require('child_process').spawn;
var ipc = require("electron-safe-ipc/guest");

var userData;
var l = Ladda.create($('#start').get(0));
var logs = requirejs('./modules/logs');

exports.child;
exports.currentProcess;

exports.init = function() {
	userData = requirejs('./modules/userdata')
	ipc.on('farm', exports.farm);
	ipc.on('terminateProcess', exports.terminateProcess);

	$('#start').on('click', function (e) {
		if(exports.currentProcess) {
			exports.terminateProcess();
		} else if(userData.hasValidSettings()) {
			exports.farm();
		}
	});
};

var realizeUI = function() {
	var isDisabled = exports.currentProcess !== null;

	$(".main").toggleClass('disabled', isDisabled );
	$("#address").prop('disabled', isDisabled);
	$("#directory").prop('disabled', isDisabled);
	$("#browse").prop('disabled', isDisabled);
	$("#size").prop('disabled', isDisabled);
	$('#size-unit').prop('disabled', isDisabled);

	if(isDisabled) {
		l.start();
		$('#start').prop('disabled', false); // l.start causes the bootstrap button to be unclickable, this ensures we can still click the button
		$('#start').css({ 'background-color': '#FFA500', 'border-color': '#FFA500' }); // orange
		$('#start-label').text('RUNNING, CLICK TO ABORT');
	} else {
		l.stop();
		$('#start').css({ 'background-color': '#88C425', 'border-color': '#88C425' }); // green
		$('#start-label').text('START');
	}
}

var bootstrapProcess = function(name, args) {

	exports.terminateProcess();
	exports.currentProcess = name;

	var output = userData.dataservClient + " ";
	for(var i = 0; i < args.length; ++i) {
		output += args[i];
		if(i < args.length - 1) {
			output += ' ';
		}
	}
	logs.addLog(output);
	console.log(output);

	exports.child = spawn(userData.dataservClient, args);
	exports.child.stdout.on('data', function (data) {
		var output = data.toString();
		logs.addLog(output);
		console.log(output);
	});
	exports.child.stderr.on('data', function (data) {
		var output = data.toString();
		logs.addLog(output);
		console.log(output);
	});

	ipc.send('processStarted');
	realizeUI();
};

exports.farm = function() {
	if(userData.hasValidSettings()) {
		bootstrapProcess('FARMING', ['--store_path=' + userData.dataservDirectory, '--max_size=' + userData.dataservSize + userData.dataservSizeUnit, 'farm']);
	}
}

exports.build = function() {
	if(userData.hasValidSettings()) {
		bootstrapProcess('BUILDING', ['--store_path=' + userData.dataservDirectory, '--max_size=' + userData.dataservSize + userData.dataservSizeUnit, 'build']);
	}
}

exports.register = function() {
	if(userData.hasValidSettings()) {
		bootstrapProcess('REGISTERING', ['register']);
	}
};

exports.poll = function() {
	if(userData.hasValidSettings()) {
		bootstrapProcess('POLLING', ['poll']);
	}
};

exports.saveConfig = function() {
	if(userData.hasValidDataservClient() && userData.hasValidPayoutAddress()) {
		exec(userData.dataservClient, ['config', '--set_payout_address=' + userData.payoutAddress]);
	}
}

exports.validateDataservClient = function(callback) {
	if(userData.hasValidDataservClient()) {
		exec(userData.dataservClient, ['version'], function(err, out, code) {
			var output;
			if(err) {
				output = err.toString();
			} else if(out === undefined || out === '') {
				output = 'invalid dataserv-client';
			}
			else {
				requirejs('./modules/logs').addLog('dataserv-client version ' + out);
			}
			if(callback) {
				callback(output);
			}
		});
	} else if(callback) {
		callback('invalid dataserv-client');
	}
}

exports.terminateProcess = function() {
	if(exports.child) {
		logs.addLog('exports.child ' + exports.child.pid + ' terminated');
		exports.child.kill();
		exports.child = null;
		exports.currentProcess = null;
		ipc.send('processTerminated');
		realizeUI();
		Ladda.create($('#start')).stop();
		$('#start').css({ 'background-color': '#88C425', 'border-color': '#88C425' }); // green
		$('#start-label').text('START');
	}
}<|endoftext|>


<commit_before>var express = require('express');

var http = require('http');
var path = require('path');

const exphbs = require('express-handlebars')

var app = express();

app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));

app.engine('.hbs', exphbs({
  defaultLayout: 'layout',
  extname: '.hbs',
  layoutsDir: path.join(__dirname),
  partialsDir: path.join(__dirname)
}))

app.set('view engine', '.hbs')
app.set('views', path.join(__dirname))

require('./course').init(app)
require('./admin').init(app)

module.exports = app<commit_msg>Fixed require lines.<commit_after>const express = require('express');
const path = require('path');
const exphbs = require('express-handlebars')
const app = express();

app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));

app.engine('.hbs', exphbs({
  defaultLayout: 'layout',
  extname: '.hbs',
  layoutsDir: path.join(__dirname),
  partialsDir: path.join(__dirname)
}))

app.set('view engine', '.hbs')
app.set('views', path.join(__dirname))

require('./course').init(app)
require('./admin').init(app)

module.exports = app<|endoftext|>


<commit_before>class robotry {

    // 클래스 내부에서 사용될 필드들을 이곳에서 선언합니다.
    constructor() {
        this.sp = null;
        this.socket = null;
        this.handler = null;
        this.config = null;
        this.isDraing = false;
        this.actionTypes = {
            GET: 1,
            SET: 2,
            RESET: 3,
        };

        this.sensorValueSize = {
            FLOAT: 2,
            SHORT: 3,
        };

        this.digitalPortTimeList = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];

        this.sensorData = {
            ULTRASONIC: 0,
            DIGITAL: {
                '0': 0,
                '1': 0,
                '2': 0,
                '3': 0,
                '4': 0,
                '5': 0,
                '6': 0,
                '7': 0,
                '8': 0,
                '9': 0,
                '10': 0,
                '11': 0,
                '12': 0,
                '13': 0,
            },
            ANALOG: {
                '0': 0,
                '1': 0,
                '2': 0,
                '3': 0,
                '4': 0,
                '5': 0,
                '6': 0,
                '7': 0,
            },
            PULSEIN: {},
            TIMER: 0,
        };

        this.defaultOutput = {};

        this.recentCheckData = {};

        this.sendBuffers = [];

        this.lastTime = 0;
        this.lastSendTime = 0;
        this.isDraing = false;
    }

    /*
    최초에 커넥션이 이루어진 후의 초기 설정.
    handler 는 워크스페이스와 통신하 데이터를 json 화 하는 오브젝트입니다. (datahandler/json 참고)
    config 은 module.json 오브젝트입니다.
    */
    init(handler, config) {
        this.handler = handler;
        this.config = config;
    }
    /*
    연결 후 초기에 송신할 데이터가 필요한 경우 사용합니다.
    requestInitialData 를 사용한 경우 checkInitialData 가 필수입니다.
    이 두 함수가 정의되어있어야 로직이 동작합니다. 필요없으면 작성하지 않아도 됩니다.
    */
    requestInitialData() {
        // return true;
        return this.makeSensorReadBuffer(this.sensorTypes.ANALOG, 0);
    }

    // 연결 후 초기에 수신받아서 정상연결인지를 확인해야하는 경우 사용합니다.
    // actual parameter is (data, config)
    checkInitialData() {
        return true;
    }

    // 주기적으로 하드웨어에서 받은 데이터의 검증이 필요한 경우 사용합니다.
    // actual parameter is (data)
    validateLocalData() {
        return true;
    }

    // 하드웨어
    requestLocalData() {}

    handleLocalData() {}

    // 엔트리
    requestRemoteData() {}

    handleRemoteData() {}

}

module.exports = robotry;
<commit_msg>Update robotry.js<commit_after>class robotry {

    // 클래스 내부에서 사용될 필드들을 이곳에서 선언합니다.
    constructor() {
        this.sp = null;
        this.socket = null;
        this.handler = null;
        this.config = null;
        this.isDraing = false;
        this.actionTypes = {
            GET: 1,
            SET: 2,
            RESET: 3,
        };

        this.sensorValueSize = {
            FLOAT: 2,
            SHORT: 3,
        };

        this.digitalPortTimeList = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];

        this.sensorData = {
            ULTRASONIC: 0,
            DIGITAL: {
                '0': 0,
                '1': 0,
                '2': 0,
                '3': 0,
                '4': 0,
                '5': 0,
                '6': 0,
                '7': 0,
                '8': 0,
                '9': 0,
                '10': 0,
                '11': 0,
                '12': 0,
                '13': 0,
            },
            ANALOG: {
                '0': 0,
                '1': 0,
                '2': 0,
                '3': 0,
                '4': 0,
                '5': 0,
                '6': 0,
                '7': 0,
            },
            PULSEIN: {},
            TIMER: 0,
        };

        this.defaultOutput = {};

        this.recentCheckData = {};

        this.sendBuffers = [];

        this.lastTime = 0;
        this.lastSendTime = 0;
        this.isDraing = false;
    }

    /*
    최초에 커넥션이 이루어진 후의 초기 설정.
    handler 는 워크스페이스와 통신하 데이터를 json 화 하는 오브젝트입니다. (datahandler/json 참고)
    config 은 module.json 오브젝트입니다.
    */
    init(handler, config) {
        this.handler = handler;
        this.config = config;
    }
    /*
    연결 후 초기에 송신할 데이터가 필요한 경우 사용합니다.
    requestInitialData 를 사용한 경우 checkInitialData 가 필수입니다.
    이 두 함수가 정의되어있어야 로직이 동작합니다. 필요없으면 작성하지 않아도 됩니다.
    */
    requestInitialData() {
        // return true;
    }

    // 연결 후 초기에 수신받아서 정상연결인지를 확인해야하는 경우 사용합니다.
    // actual parameter is (data, config)
    checkInitialData() {
        return true;
    }

    // 주기적으로 하드웨어에서 받은 데이터의 검증이 필요한 경우 사용합니다.
    // actual parameter is (data)
    validateLocalData() {
        return true;
    }

    // 하드웨어
    requestLocalData() {}

    handleLocalData() {}

    // 엔트리
    requestRemoteData() {}

    handleRemoteData() {}

}

module.exports = robotry;
<|endoftext|>


<commit_before>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');

var CommonJSGenerator = module.exports = function CommonJSGenerator(args, options) {
  yeoman.generators.Base.apply(this, arguments);

  this.on('end', function () {
    this.installDependencies({ skipInstall: options['skip-install'] });
  });

  this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

util.inherits(CommonJSGenerator, yeoman.generators.NamedBase);

CommonJSGenerator.prototype.askFor = function askFor() {
  var cb = this.async();

  // welcome message
  var welcome =
  '\n     _-----_' +
  '\n    |       |' +
  '\n    |' + '--(o)--'.red + '|   .--------------------------.' +
  '\n   `---------´  |    ' + 'Welcome to Yeoman,'.yellow.bold + '    |' +
  '\n    ' + '( '.yellow + '_' + '´U`'.yellow + '_' + ' )'.yellow + '   |   ' + 'ladies and gentlemen!'.yellow.bold + '  |' +
  '\n    /___A___\\   \'__________________________\'' +
  '\n     |  ~  |'.yellow +
  '\n   __' + '\'.___.\''.yellow + '__' +
  '\n ´   ' + '`  |'.red + '° ' + '´ Y'.red + ' `\n' +
  '\n';

  console.log(welcome);

  var prompts = [{
    name: 'name'
  }, {
    name: 'description',
    'default': 'The best commonjs module ever.'
  }, {
    name: 'version'
  }, {
    name: 'repository'
  }, {
    name: 'bugs'
  }, {
    name: 'license',
    'default': 'MIT'
  }, {
    name: 'author_name'
  }, {
    name: 'author_email'
  }, {
    name: 'author_url'
  }, {
    name: 'main'
  }, {
    name: 'npm_test',
    'default': 'grunt nodeunit'
  },];

  var nameToMessage = function (name) {
    return name.split('_').map(
      function (x) { return this._.capitalize(x); }.bind(this)
    ).join(' ') + ':';
  }.bind(this);

  // Generate prompt messages if only the name is defined.
  prompts.map(function (entry) {
    if (entry.message === undefined) {
      entry.message = nameToMessage(entry.name);
    }
    return entry;
  }.bind(this));

  this.currentYear = (new Date()).getFullYear();

  this.prompt(prompts, function (err, props) {
    if (err) {
      return this.emit('error', err);
    }

    this.props = props;
    // For easier access in the templates.
    this.slugname = this._.slugify(props.name);
    cb();
  }.bind(this));
};

CommonJSGenerator.prototype.src = function app() {
  this.mkdir('src');
  this.copy('src/jshintrc', 'src/.jshintrc');
  this.template('src/name.js', 'src/' + this.slugname + '.js');
};

CommonJSGenerator.prototype.test = function app() {
  this.mkdir('test');
  this.copy('test/jshintrc', 'test/.jshintrc');
  this.template('test/name_test.js', 'test/' + this.slugname + '_test.js');
};

CommonJSGenerator.prototype.projectfiles = function projectfiles() {
  this.copy('editorconfig', '.editorconfig');
  this.copy('jshintrc', '.jshintrc');
  this.copy('gitignore', '.gitignore');
  this.copy('travis.yml', '.travis.yml');

  this.template('README.md');
  this.template('Gruntfile.js');
  this.template('_bower.json', 'bower.json');
  this.template('_package.json', 'package.json');
  this.template('bowerrc', '.bowerrc');
  this.copy('CONTRIBUTING.md', 'CONTRIBUTING.md');
};
<commit_msg>index.js: removing unnecessary refs to bower<commit_after>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');

var CommonJSGenerator = module.exports = function CommonJSGenerator(args, options) {
  yeoman.generators.Base.apply(this, arguments);

  this.on('end', function () {
    this.installDependencies({ skipInstall: options['skip-install'] });
  });

  this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

util.inherits(CommonJSGenerator, yeoman.generators.NamedBase);

CommonJSGenerator.prototype.askFor = function askFor() {
  var cb = this.async();

  // welcome message
  var welcome =
  '\n     _-----_' +
  '\n    |       |' +
  '\n    |' + '--(o)--'.red + '|   .--------------------------.' +
  '\n   `---------´  |    ' + 'Welcome to Yeoman,'.yellow.bold + '    |' +
  '\n    ' + '( '.yellow + '_' + '´U`'.yellow + '_' + ' )'.yellow + '   |   ' + 'ladies and gentlemen!'.yellow.bold + '  |' +
  '\n    /___A___\\   \'__________________________\'' +
  '\n     |  ~  |'.yellow +
  '\n   __' + '\'.___.\''.yellow + '__' +
  '\n ´   ' + '`  |'.red + '° ' + '´ Y'.red + ' `\n' +
  '\n';

  console.log(welcome);

  var prompts = [{
    name: 'name'
  }, {
    name: 'description',
    'default': 'The best commonjs module ever.'
  }, {
    name: 'version'
  }, {
    name: 'repository'
  }, {
    name: 'bugs'
  }, {
    name: 'license',
    'default': 'MIT'
  }, {
    name: 'author_name'
  }, {
    name: 'author_email'
  }, {
    name: 'author_url'
  }, {
    name: 'main'
  }, {
    name: 'npm_test',
    'default': 'grunt nodeunit'
  },];

  var nameToMessage = function (name) {
    return name.split('_').map(
      function (x) { return this._.capitalize(x); }.bind(this)
    ).join(' ') + ':';
  }.bind(this);

  // Generate prompt messages if only the name is defined.
  prompts.map(function (entry) {
    if (entry.message === undefined) {
      entry.message = nameToMessage(entry.name);
    }
    return entry;
  }.bind(this));

  this.currentYear = (new Date()).getFullYear();

  this.prompt(prompts, function (err, props) {
    if (err) {
      return this.emit('error', err);
    }

    this.props = props;
    // For easier access in the templates.
    this.slugname = this._.slugify(props.name);
    cb();
  }.bind(this));
};

CommonJSGenerator.prototype.src = function app() {
  this.mkdir('src');
  this.copy('src/jshintrc', 'src/.jshintrc');
  this.template('src/name.js', 'src/' + this.slugname + '.js');
};

CommonJSGenerator.prototype.test = function app() {
  this.mkdir('test');
  this.copy('test/jshintrc', 'test/.jshintrc');
  this.template('test/name_test.js', 'test/' + this.slugname + '_test.js');
};

CommonJSGenerator.prototype.projectfiles = function projectfiles() {
  this.copy('editorconfig', '.editorconfig');
  this.copy('jshintrc', '.jshintrc');
  this.copy('gitignore', '.gitignore');
  this.copy('travis.yml', '.travis.yml');

  this.template('README.md');
  this.template('Gruntfile.js');
  this.template('_package.json', 'package.json');
  this.copy('CONTRIBUTING.md', 'CONTRIBUTING.md');
};
<|endoftext|>


<commit_before>// Print diagnostic information for a few arguments instead of running Hyper.
if (['--help', '-v', '--version'].includes(process.argv[1])) {
  const {version} = require('./package');
  const configLocation = process.platform === 'win32' ? process.env.userprofile + '\\.hyper.js' : '~/.hyper.js';
  //eslint-disable-next-line no-console
  console.log(`Hyper version ${version}`);
  //eslint-disable-next-line no-console
  console.log('Hyper does not accept any command line arguments. Please modify the config file instead.');
  //eslint-disable-next-line no-console
  console.log(`Hyper configuration file located at: ${configLocation}`);
  // eslint-disable-next-line unicorn/no-process-exit
  process.exit();
}

const checkSquirrel = () => {
  let squirrel;

  try {
    squirrel = require('electron-squirrel-startup');
    //eslint-disable-next-line no-empty
  } catch (err) {}

  if (squirrel) {
    // eslint-disable-next-line unicorn/no-process-exit
    process.exit();
  }
};

// handle startup squirrel events
if (process.platform === 'win32') {
  // eslint-disable-next-line import/order
  const systemContextMenu = require('./system-context-menu');

  switch (process.argv[1]) {
    case '--squirrel-install':
    case '--squirrel-updated':
      systemContextMenu.add(() => {
        checkSquirrel();
      });
      break;
    case '--squirrel-uninstall':
      systemContextMenu.remove(() => {
        checkSquirrel();
      });
      break;
    default:
      checkSquirrel();
  }
}

// Native
const {resolve} = require('path');

// Packages
const {app, BrowserWindow, Menu} = require('electron');
const {gitDescribe} = require('git-describe');
const isDev = require('electron-is-dev');

const config = require('./config');

// set up config
config.setup();

const plugins = require('./plugins');
const {installCLI} = require('./utils/cli-install');
const AppMenu = require('./menus/menu');
const Window = require('./ui/window');
const windowUtils = require('./utils/window-utils');

const windowSet = new Set([]);

// expose to plugins
app.config = config;
app.plugins = plugins;
app.getWindows = () => new Set([...windowSet]); // return a clone

// function to retrieve the last focused window in windowSet;
// added to app object in order to expose it to plugins.
app.getLastFocusedWindow = () => {
  if (!windowSet.size) {
    return null;
  }
  return Array.from(windowSet).reduce((lastWindow, win) => {
    return win.focusTime > lastWindow.focusTime ? win : lastWindow;
  });
};

if (isDev) {
  //eslint-disable-next-line no-console
  console.log('running in dev mode');

  // Overide default appVersion which is set from package.json
  gitDescribe({customArguments: ['--tags']}, (error, gitInfo) => {
    if (!error) {
      app.setVersion(gitInfo.raw);
    }
  });
} else {
  //eslint-disable-next-line no-console
  console.log('running in prod mode');
}

const url = 'file://' + resolve(isDev ? __dirname : app.getAppPath(), 'index.html');
//eslint-disable-next-line no-console
console.log('electron will open', url);

app.on('ready', () =>
  installDevExtensions(isDev)
    .then(() => {
      function createWindow(fn, options = {}) {
        const cfg = plugins.getDecoratedConfig();

        const winSet = config.getWin();
        let [startX, startY] = winSet.position;

        const [width, height] = options.size ? options.size : cfg.windowSize || winSet.size;
        const {screen} = require('electron');

        const winPos = options.position;

        // Open the new window roughly the height of the header away from the
        // previous window. This also ensures in multi monitor setups that the
        // new terminal is on the correct screen.
        const focusedWindow = BrowserWindow.getFocusedWindow() || app.getLastFocusedWindow();
        // In case of options defaults position and size, we should ignore the focusedWindow.
        if (winPos !== undefined) {
          [startX, startY] = winPos;
        } else if (focusedWindow) {
          const points = focusedWindow.getPosition();
          const currentScreen = screen.getDisplayNearestPoint({
            x: points[0],
            y: points[1]
          });

          const biggestX = points[0] + 100 + width - currentScreen.bounds.x;
          const biggestY = points[1] + 100 + height - currentScreen.bounds.y;

          if (biggestX > currentScreen.size.width) {
            startX = 50;
          } else {
            startX = points[0] + 34;
          }
          if (biggestY > currentScreen.size.height) {
            startY = 50;
          } else {
            startY = points[1] + 34;
          }
        }

        if (!windowUtils.positionIsValid([startX, startY])) {
          [startX, startY] = config.windowDefaults.windowPosition;
        }

        const hwin = new Window({width, height, x: startX, y: startY}, cfg, fn);
        windowSet.add(hwin);
        hwin.loadURL(url);

        // the window can be closed by the browser process itself
        hwin.on('close', () => {
          hwin.clean();
          windowSet.delete(hwin);
        });

        hwin.on('closed', () => {
          if (process.platform !== 'darwin' && windowSet.size === 0) {
            app.quit();
          }
        });

        return hwin;
      }

      // when opening create a new window
      createWindow();

      // expose to plugins
      app.createWindow = createWindow;

      // mac only. when the dock icon is clicked
      // and we don't have any active windows open,
      // we open one
      app.on('activate', () => {
        if (!windowSet.size) {
          createWindow();
        }
      });

      const makeMenu = () => {
        const menu = plugins.decorateMenu(AppMenu.createMenu(createWindow, plugins.getLoadedPluginVersions));

        // If we're on Mac make a Dock Menu
        if (process.platform === 'darwin') {
          const dockMenu = Menu.buildFromTemplate([
            {
              label: 'New Window',
              click() {
                createWindow();
              }
            }
          ]);
          app.dock.setMenu(dockMenu);
        }

        Menu.setApplicationMenu(AppMenu.buildMenu(menu));
      };

      plugins.onApp(app);
      makeMenu();
      plugins.subscribe(plugins.onApp.bind(undefined, app));
      config.subscribe(makeMenu);
      if (!isDev) {
        // check if should be set/removed as default ssh protocol client
        if (config.getConfig().defaultSSHApp && !app.isDefaultProtocolClient('ssh')) {
          //eslint-disable-next-line no-console
          console.log('Setting Hyper as default client for ssh:// protocol');
          app.setAsDefaultProtocolClient('ssh');
        } else if (!config.getConfig().defaultSSHApp && app.isDefaultProtocolClient('ssh')) {
          //eslint-disable-next-line no-console
          console.log('Removing Hyper from default client for ssh:// protocl');
          app.removeAsDefaultProtocolClient('ssh');
        }
        installCLI(false);
      }
    })
    .catch(err => {
      //eslint-disable-next-line no-console
      console.error('Error while loading devtools extensions', err);
    })
);

app.on('open-file', (event, path) => {
  const lastWindow = app.getLastFocusedWindow();
  const callback = win => win.rpc.emit('open file', {path});
  if (lastWindow) {
    callback(lastWindow);
  } else if (!lastWindow && {}.hasOwnProperty.call(app, 'createWindow')) {
    app.createWindow(callback);
  } else {
    // If createWindow doesn't exist yet ('ready' event was not fired),
    // sets his callback to an app.windowCallback property.
    app.windowCallback = callback;
  }
});

app.on('open-url', (event, sshUrl) => {
  const lastWindow = app.getLastFocusedWindow();
  const callback = win => win.rpc.emit('open ssh', sshUrl);
  if (lastWindow) {
    callback(lastWindow);
  } else if (!lastWindow && {}.hasOwnProperty.call(app, 'createWindow')) {
    app.createWindow(callback);
  } else {
    // If createWindow doesn't exist yet ('ready' event was not fired),
    // sets his callback to an app.windowCallback property.
    app.windowCallback = callback;
  }
});

function installDevExtensions(isDev_) {
  if (!isDev_) {
    return Promise.resolve();
  }
  // eslint-disable-next-line import/no-extraneous-dependencies
  const installer = require('electron-devtools-installer');

  const extensions = ['REACT_DEVELOPER_TOOLS', 'REDUX_DEVTOOLS'];
  const forceDownload = Boolean(process.env.UPGRADE_EXTENSIONS);

  return Promise.all(extensions.map(name => installer.default(installer[name], forceDownload)));
}
<commit_msg>Disable Chromium GPU blacklist (#2895)<commit_after>// Print diagnostic information for a few arguments instead of running Hyper.
if (['--help', '-v', '--version'].includes(process.argv[1])) {
  const {version} = require('./package');
  const configLocation = process.platform === 'win32' ? process.env.userprofile + '\\.hyper.js' : '~/.hyper.js';
  //eslint-disable-next-line no-console
  console.log(`Hyper version ${version}`);
  //eslint-disable-next-line no-console
  console.log('Hyper does not accept any command line arguments. Please modify the config file instead.');
  //eslint-disable-next-line no-console
  console.log(`Hyper configuration file located at: ${configLocation}`);
  // eslint-disable-next-line unicorn/no-process-exit
  process.exit();
}

const checkSquirrel = () => {
  let squirrel;

  try {
    squirrel = require('electron-squirrel-startup');
    //eslint-disable-next-line no-empty
  } catch (err) {}

  if (squirrel) {
    // eslint-disable-next-line unicorn/no-process-exit
    process.exit();
  }
};

// handle startup squirrel events
if (process.platform === 'win32') {
  // eslint-disable-next-line import/order
  const systemContextMenu = require('./system-context-menu');

  switch (process.argv[1]) {
    case '--squirrel-install':
    case '--squirrel-updated':
      systemContextMenu.add(() => {
        checkSquirrel();
      });
      break;
    case '--squirrel-uninstall':
      systemContextMenu.remove(() => {
        checkSquirrel();
      });
      break;
    default:
      checkSquirrel();
  }
}

// Native
const {resolve} = require('path');

// Packages
const {app, BrowserWindow, Menu} = require('electron');
const {gitDescribe} = require('git-describe');
const isDev = require('electron-is-dev');

const config = require('./config');

// set up config
config.setup();

const plugins = require('./plugins');
const {installCLI} = require('./utils/cli-install');
const AppMenu = require('./menus/menu');
const Window = require('./ui/window');
const windowUtils = require('./utils/window-utils');

const windowSet = new Set([]);

// expose to plugins
app.config = config;
app.plugins = plugins;
app.getWindows = () => new Set([...windowSet]); // return a clone

// function to retrieve the last focused window in windowSet;
// added to app object in order to expose it to plugins.
app.getLastFocusedWindow = () => {
  if (!windowSet.size) {
    return null;
  }
  return Array.from(windowSet).reduce((lastWindow, win) => {
    return win.focusTime > lastWindow.focusTime ? win : lastWindow;
  });
};

//eslint-disable-next-line no-console
console.log('Disabling Chromium GPU blacklist');
app.commandLine.appendSwitch('ignore-gpu-blacklist');

if (isDev) {
  //eslint-disable-next-line no-console
  console.log('running in dev mode');

  // Overide default appVersion which is set from package.json
  gitDescribe({customArguments: ['--tags']}, (error, gitInfo) => {
    if (!error) {
      app.setVersion(gitInfo.raw);
    }
  });
} else {
  //eslint-disable-next-line no-console
  console.log('running in prod mode');
}

const url = 'file://' + resolve(isDev ? __dirname : app.getAppPath(), 'index.html');
//eslint-disable-next-line no-console
console.log('electron will open', url);

app.on('ready', () =>
  installDevExtensions(isDev)
    .then(() => {
      function createWindow(fn, options = {}) {
        const cfg = plugins.getDecoratedConfig();

        const winSet = config.getWin();
        let [startX, startY] = winSet.position;

        const [width, height] = options.size ? options.size : cfg.windowSize || winSet.size;
        const {screen} = require('electron');

        const winPos = options.position;

        // Open the new window roughly the height of the header away from the
        // previous window. This also ensures in multi monitor setups that the
        // new terminal is on the correct screen.
        const focusedWindow = BrowserWindow.getFocusedWindow() || app.getLastFocusedWindow();
        // In case of options defaults position and size, we should ignore the focusedWindow.
        if (winPos !== undefined) {
          [startX, startY] = winPos;
        } else if (focusedWindow) {
          const points = focusedWindow.getPosition();
          const currentScreen = screen.getDisplayNearestPoint({
            x: points[0],
            y: points[1]
          });

          const biggestX = points[0] + 100 + width - currentScreen.bounds.x;
          const biggestY = points[1] + 100 + height - currentScreen.bounds.y;

          if (biggestX > currentScreen.size.width) {
            startX = 50;
          } else {
            startX = points[0] + 34;
          }
          if (biggestY > currentScreen.size.height) {
            startY = 50;
          } else {
            startY = points[1] + 34;
          }
        }

        if (!windowUtils.positionIsValid([startX, startY])) {
          [startX, startY] = config.windowDefaults.windowPosition;
        }

        const hwin = new Window({width, height, x: startX, y: startY}, cfg, fn);
        windowSet.add(hwin);
        hwin.loadURL(url);

        // the window can be closed by the browser process itself
        hwin.on('close', () => {
          hwin.clean();
          windowSet.delete(hwin);
        });

        hwin.on('closed', () => {
          if (process.platform !== 'darwin' && windowSet.size === 0) {
            app.quit();
          }
        });

        return hwin;
      }

      // when opening create a new window
      createWindow();

      // expose to plugins
      app.createWindow = createWindow;

      // mac only. when the dock icon is clicked
      // and we don't have any active windows open,
      // we open one
      app.on('activate', () => {
        if (!windowSet.size) {
          createWindow();
        }
      });

      const makeMenu = () => {
        const menu = plugins.decorateMenu(AppMenu.createMenu(createWindow, plugins.getLoadedPluginVersions));

        // If we're on Mac make a Dock Menu
        if (process.platform === 'darwin') {
          const dockMenu = Menu.buildFromTemplate([
            {
              label: 'New Window',
              click() {
                createWindow();
              }
            }
          ]);
          app.dock.setMenu(dockMenu);
        }

        Menu.setApplicationMenu(AppMenu.buildMenu(menu));
      };

      plugins.onApp(app);
      makeMenu();
      plugins.subscribe(plugins.onApp.bind(undefined, app));
      config.subscribe(makeMenu);
      if (!isDev) {
        // check if should be set/removed as default ssh protocol client
        if (config.getConfig().defaultSSHApp && !app.isDefaultProtocolClient('ssh')) {
          //eslint-disable-next-line no-console
          console.log('Setting Hyper as default client for ssh:// protocol');
          app.setAsDefaultProtocolClient('ssh');
        } else if (!config.getConfig().defaultSSHApp && app.isDefaultProtocolClient('ssh')) {
          //eslint-disable-next-line no-console
          console.log('Removing Hyper from default client for ssh:// protocl');
          app.removeAsDefaultProtocolClient('ssh');
        }
        installCLI(false);
      }
    })
    .catch(err => {
      //eslint-disable-next-line no-console
      console.error('Error while loading devtools extensions', err);
    })
);

app.on('open-file', (event, path) => {
  const lastWindow = app.getLastFocusedWindow();
  const callback = win => win.rpc.emit('open file', {path});
  if (lastWindow) {
    callback(lastWindow);
  } else if (!lastWindow && {}.hasOwnProperty.call(app, 'createWindow')) {
    app.createWindow(callback);
  } else {
    // If createWindow doesn't exist yet ('ready' event was not fired),
    // sets his callback to an app.windowCallback property.
    app.windowCallback = callback;
  }
});

app.on('open-url', (event, sshUrl) => {
  const lastWindow = app.getLastFocusedWindow();
  const callback = win => win.rpc.emit('open ssh', sshUrl);
  if (lastWindow) {
    callback(lastWindow);
  } else if (!lastWindow && {}.hasOwnProperty.call(app, 'createWindow')) {
    app.createWindow(callback);
  } else {
    // If createWindow doesn't exist yet ('ready' event was not fired),
    // sets his callback to an app.windowCallback property.
    app.windowCallback = callback;
  }
});

function installDevExtensions(isDev_) {
  if (!isDev_) {
    return Promise.resolve();
  }
  // eslint-disable-next-line import/no-extraneous-dependencies
  const installer = require('electron-devtools-installer');

  const extensions = ['REACT_DEVELOPER_TOOLS', 'REDUX_DEVTOOLS'];
  const forceDownload = Boolean(process.env.UPGRADE_EXTENSIONS);

  return Promise.all(extensions.map(name => installer.default(installer[name], forceDownload)));
}
<|endoftext|>