<commit_before>var generators = require('yeoman-generator');
var git = require('nodegit');
var fse = require('fs-extra');
var mysql = require('mysql');

// Vars
var repo = null;
var cwd = process.cwd();

module.exports = generators.Base.extend({

  // ## Clone odddrupal

  // Clone https://github.com/oddhill/odddrupal.git.
  // And rename origin to odddrupal.
  clone: function () {
    // Check if cwd is empty or not.
    var files = fse.readdirSync(cwd);
    if (files.length > 0) {
      // quit
      console.error('Current dir not empty! Emergency, quits.');
      return;
    }

    console.log('Cloning odddrupal to ' + cwd + '...');

    // Clone odddrupal to cwd
    var options = {
      remoteCallbacks: {
        certificateCheck: function() {
          return 1;
        }
      }
    };
    git.Clone.clone('https://github.com/oddhill/odddrupal.git', cwd, options)
      .then(function(repository) {
        // Make sure we can use it later.
        repo = repository;

        // Remove remote
        git.Remote.delete(repo, 'origin').then(function() {
          console.log('Done');
        });
      }
    ).catch(function(err) {
      console.log('Waow, sry something went wrong. :(');
      return;
    }).done();
  },

  // Rename current branch to master
  createMaster: function () {
    console.log('Renaming the 7.x branch to master...');
    // Rename current local branch to master
    git.Branch.lookup(repo, '7.x', git.Branch.GIT_BRANCH_LOCAL).then(function(branchRef) {
      var signature = git.Signature.default(repo);
      git.Branch.move(branchRef, 'master', true, signature, null).then(function(reference) {
        console.log('Done');
      });
    });
  },

  // ## Install odddrupal

  // Copy .htaccess.default to .htaccess.
  htaccess: function () {
    fse.copy(cwd + '.htaccess.default', cwd + '.htaccess', function(err) {
      if (!err) {
        console.log('Copied .htaccess.default to .htaccess');
      }
    });
  },

  // Create a new mysql db.
  createDb: function () {
    // Connect to mysql
    var connection = mysql.createConnection({
      host: '127.0.0.1',
      user: 'root',
      password: ''
    });

    connection.connect();

    var db_name = cwd.split('/');
    db_name = db_name[db_name.length-1];

    connection.query('CREATE DATABASE ' + db_name, function (err) {
      if (!err) {
        console.log('Added a new database named ' + db_name + '.');
      }
    });

    connection.end();
  },

  // Copy sites/default/settings.local.php.default to settings.local.php.
  dbSettings: function () {
    fse.copy(cwd + 'sites/default/settings.local.php.default', cwd + 'sites/default/settings.local.php', function(err) {
      if (!err) {
        console.log('Copied settings.local.php.default to settings.local.php');

        // @TODO:
        // Add db settings to file.
      }
    });
  },

  // Make sure the files folder (sites/all/files) is 777.
  filesChmod: function () {
    fse.ensureDirSync(cwd + 'sites/all/files', function(err) {
      if (!err) {
        fse.chmodSync(cwd + 'sites/all/files', 777);
        console.log('Created files dir');
      }
    });
  }

});
<commit_msg>Bug fixes<commit_after>var generators = require('yeoman-generator');
var git = require('nodegit');
var fse = require('fs-extra');
var mysql = require('mysql');

// Vars
var repo = null;
var cwd = process.cwd();

module.exports = generators.Base.extend({

  // ## Clone odddrupal

  // Clone https://github.com/oddhill/odddrupal.git.
  // And rename origin to odddrupal.
  clone: function () {
    var done = this.async();
    // Check if cwd is empty or not.
    var files = fse.readdirSync(cwd);
    if (files.length > 0) {
      // quit
      console.error('Current dir not empty! Emergency, quits.');
      return;
    }

    console.log('Cloning odddrupal to ' + cwd + '...');

    // Clone odddrupal to cwd
    var options = {
      remoteCallbacks: {
        certificateCheck: function() {
          return 1;
        }
      }
    };

    git.Clone.clone('https://github.com/oddhill/odddrupal.git', cwd, options).then(function(repository) {
      // Make sure we can use it later.
      repo = repository;

      console.log('Done');
      done();

      // @TODO
      // Remove origin remote
    });
  },

  // Rename current branch to master
  createMaster: function () {
    console.log('Renaming the 7.x branch to master...');
    // Rename current local branch to master
    git.Branch.lookup(repo, '7.x', git.Branch.GIT_BRANCH_LOCAL).then(function(branchRef) {
      var signature = git.Signature.default(repo);
      git.Branch.move(branchRef, 'master', true, signature, null).then(function(reference) {
        console.log('Done');
      });
    });
  },

  // ## Install odddrupal

  // Copy .htaccess.default to .htaccess.
  htaccess: function () {
    fse.copy(cwd + '.htaccess.default', cwd + '.htaccess', function(err) {
      if (!err) {
        console.log('Copied .htaccess.default to .htaccess');
      }
    });
  },

  // Create a new mysql db.
  createDb: function () {
    // Connect to mysql
    var connection = mysql.createConnection({
      host: '127.0.0.1',
      user: 'root',
      password: ''
    });

    connection.connect();

    var db_name = cwd.split('/');
    db_name = db_name[db_name.length-1];

    connection.query('CREATE DATABASE ' + db_name, function (err) {
      if (!err) {
        console.log('Added a new database named ' + db_name + '.');
      }
    });

    connection.end();
  },

  // Copy sites/default/settings.local.php.default to settings.local.php.
  dbSettings: function () {
    fse.copy(cwd + 'sites/default/settings.local.php.default', cwd + 'sites/default/settings.local.php', function(err) {
      if (!err) {
        console.log('Copied settings.local.php.default to settings.local.php');

        // @TODO:
        // Add db settings to file.
      }
    });
  },

  // Make sure the files folder (sites/all/files) is 777.
  filesChmod: function () {
    fse.ensureDirSync(cwd + 'sites/all/files', function(err) {
      if (!err) {
        fse.chmodSync(cwd + 'sites/all/files', 777);
        console.log('Created files dir');
      }
    });
  }

});
<|endoftext|>


<commit_before>// @flow
import * as tt from './types'
import { Node, OperatorNode } from './node'
import type { Tree } from './types'
import { get } from '../utils'

type ExprssionItem = Node|Expression

type Options = {|
	parent?: Expression,
	params?: Set<string>,
	children?: ExprssionItem[],
|}

export default class Expression {
	// #private
	operators: OperatorNode[] = []
	lastWrap: number|null = null

	// #public
	items: ExprssionItem[] = []
	hasError: bool = false
	params: Set<string>
	parent: Expression|null

	constructor({
		parent,
		params = parent ? parent.params : new Set(),
		children,
	}: Options = {}) {
		this.params = params
		this.parent = parent || null

		if (children) {
			this.add(...children)
		}
	}

	// #private
	/* checks if operators need to be wrapped by brackets because order of operators */
	checkOperatorsOrder() {
		/* if there less than two operators this check is useless
		 * or if last item is the last operator,
		 * than needs the next item to see what will be need to move into a smaller scope */
		if (this.operators.length < 2 || this.get(-1) instanceof OperatorNode) return

		const lastOpOrder = this.getOperator(-1).getOrder()

		// if needs to be wrapped with brackets
		if (lastOpOrder > this.getOperator(-2).getOrder()) {
			/* if there was a wrapping in the previous time,
			 * than it will check operation against the inside wrapper brackets
			 * this happend in the following scenarios: num + num * num ^ num */
			if (this.lastWrap === this.items.length - 3) {
				const insideTree = this.get(-3)

				// actualy, it must be true because it was generated in this method earlier
				if (
					insideTree instanceof Expression
					&& insideTree.getOperator(-1).getOrder() < lastOpOrder
				) {
					insideTree.add(...this.remove(2))
					return
				}
			}

			const remove = this.remove(3)

			// setting lastwrap to current location
			this.lastWrap = this.items.length
			this.items = [
				...this.items,
				new Expression({
					parent: this,
					children: remove,
				}),
			]
		}
	}

	add(...vals: ExprssionItem[]) {
		for (const val of vals) {
			if (val instanceof Node) {
				if (val instanceof OperatorNode) {
					this.operators.push(val)
				} else if (val.is(tt.PARAM)) {
					this.params.add(val.value)
				} else if (!this.hasError && val.is(tt.ERROR)) {
					this.hasError = true
					if (this.parent) this.parent.hasError = true
				}
			}

			this.items.push(val)

			this.checkOperatorsOrder()
		}
	}

	remove(i: number = 1): ExprssionItem[] {
		const ret = this.items.splice(-i)
		// $FlowFixMe - flow can't tell that the filter method will return only OperatorNode[]
		this.operators = (this.items.filter(item => item instanceof OperatorNode): OperatorNode[])

		return ret
	}

	toArray(): Tree {
		return this.items.map(item => (
			item instanceof Expression ? item.toArray() : item
		))
	}

	get(i: number): ExprssionItem {
		return get(this.items, i)
	}

	getOperator(i: number): OperatorNode {
		return get(this.operators, i)
	}
}
<commit_msg>changes to wrapping<commit_after>// @flow
import * as tt from './types'
import { Node, OperatorNode } from './node'
import type { Tree } from './types'
import { get } from '../utils'

type ExprssionItem = Node|Expression

type Options = {|
	parent?: Expression,
	params?: Set<string>,
	children?: ExprssionItem[],
|}

export default class Expression {
	// #private
	operators: OperatorNode[] = []
	lastWrap: Expression|null = null

	// #public
	items: ExprssionItem[] = []
	hasError: bool = false
	params: Set<string>
	parent: Expression|null

	constructor({
		parent,
		params = parent ? parent.params : new Set(),
		children,
	}: Options = {}) {
		this.params = params
		this.parent = parent || null

		if (children) {
			this.add(...children)
		}
	}

	// #private
	/* checks if operators need to be wrapped by brackets because order of operators
	 * and wraps them out if needed */
	wrapItemsIfNeeded() {
		/* if there less than two operators this check is useless
		 * or if last item is the last operator,
		 * than needs the next item to see what will be need to move into a smaller scope */
		if (this.operators.length < 2 || this.get(-1) instanceof OperatorNode) return

		// if needs to be wrapped with brackets
		if (this.getOperator(-1).getOrder() > this.getOperator(-2).getOrder()) {
			/* if the last item which is not operator is the last wrap,
			 * the new items will go to the last wrap.
			 * this happend in the following scenarios: (num + num * num ^ num). */
			if (this.lastWrap && this.lastWrap === this.get(-3)) {
				this.lastWrap.add(...this.remove(2))
			} else {
				const remove = this.remove(3)

				this.lastWrap = new Expression({
					parent: this,
					children: remove,
				})

				this.items.push(this.lastWrap)
			}
		}
	}

	add(...vals: ExprssionItem[]) {
		for (const val of vals) {
			if (val instanceof Node) {
				if (val instanceof OperatorNode) {
					this.operators.push(val)
				} else if (val.is(tt.PARAM)) {
					this.params.add(val.value)
				} else if (!this.hasError && val.is(tt.ERROR)) {
					this.hasError = true
					if (this.parent) this.parent.hasError = true
				}
			}

			this.items.push(val)

			this.wrapItemsIfNeeded()
		}
	}

	remove(i: number = 1): ExprssionItem[] {
		const ret = this.items.splice(-i)
		// $FlowFixMe - flow can't tell that the filter method will return only OperatorNode[]
		this.operators = (this.items.filter(item => item instanceof OperatorNode): OperatorNode[])

		return ret
	}

	toArray(): Tree {
		return this.items.map(item => (
			item instanceof Expression ? item.toArray() : item
		))
	}

	get(i: number): ExprssionItem {
		return get(this.items, i)
	}

	getOperator(i: number): OperatorNode {
		return get(this.operators, i)
	}
}
<|endoftext|>


<commit_before>var posHeroY = 200;
var posHeroX = 0;
var posEnemyX = 600;
var dt = 100; // Tiempo de refresco en milisegundos.
var enemySpeed = 50; // pixeles por segundo
var ms2sec = 1000; // Para pasar de segundos a milisegundos.
var canvas;
var ctx;

function Hero(id, y, rad, color){
    this.id = id;
    this.x = posHeroX;
    this.y = y;
    this.rad = rad;
    this.color;

    this.move = function(despY){
        this.y = this.y + despY;
        if((this.y - this.rad) < 0){
            this.y = this.rad;
        }
        if(this.y + this.rad >= canvas.width){
            this.y = canvas.width - this.rad;
        }
    }
    this.draw = function(){
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.radious, 0, 2 * Math.PI, false);
        ctx.fillStyle = this.color;
        ctx.fill();
    }
}

function Enemy(id, x, y, sx, sy, color){
    this.id = id;
    this.x = x;
    this.y = y;
    this.sx = sx;
    this.sy = sy;
    this.color = color;

    this.draw = function(){
    }
}

function main(){
}
<commit_msg>Ya aparecen las naves enemigas, colisiones y añadidas vidas puntos y nivel<commit_after>var posHeroY = 200;
var posHeroX = 0;
var posEnemyX = 1200;
var dt = 100; // Tiempo de refresco en milisegundos.
var enemySpeed = 50000; // pixeles por segundo
var ms2sec = 1000; // Para pasar de segundos a milisegundos.
var canvas;
var ctx;
var shapes = [];
const desp = 25;
var count = 0;
var level = 0;
var heal = 3;
var click = 8;

function Hero(id, y, rad, color){
    this.id = id;
    this.x = rad;
    this.y = y;
    this.rad = rad;
    this.color = color;

    this.draw = function(){
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.rad, 0, 2 * Math.PI, false);
        ctx.fillStyle = this.color;
        ctx.fill();
    }

    this.move = function(despY){
        this.y = this.y + despY;
        if((this.y - this.rad) < 0){
            this.y = this.rad;
        }
        if((this.y + this.rad) >= canvas.height){
            this.y = canvas.height - this.rad;
        }
        drawShapes();
    }
}

function Enemy(id, x, y, sx, sy, color){
    this.id = id;
    this.x = x;
    this.y = y;
    this.sx = sx;
    this.sy = sy;
    this.color = color;

    this.draw = function(){
        if((this.y + this.sy) < canvas.height ){
            ctx.fillStyle = this.color;
            ctx.fillRect(this.x, this.y, this.sx, this.sy);
        }else{
            ctx.fillStyle = this.color;
            this.x = canvas.height;
            ctx.fillRect(this.x, this.y, this.sx, this.sy);
        }
    }

    this.move = function(despx){
        this.x = this.x + despx;
        drawShapes();
    }
}

function gameOver(){
    alert("GAME OVER");
    document.location.reload();
}

function moveEnemies(){
    // mueve a todas las naves enemigas.
    var i;

    for(i = 1; i < shapes.length; i++){
        if((shapes[i].x - enemySpeed/ms2sec) > -10 ){
            shapes[i].move(-(enemySpeed/ms2sec));
        }else{
            shapes.splice(i,1);
        }
    }
}

function checkCollides(){
    //Comprueba colisiones y cambia el valor de las vidas.
    var posBack;
    var posFront;
    var posLeft;
    var posRight;
    var i;

    posBack = shapes[0].x - shapes[0].rad;
    posFront = shapes[0].x + shapes[0].rad;
    posLeft = shapes[0].y - shapes[0].rad;
    posRight = shapes[0].y + shapes[0].rad;

    for(i = 1; i < shapes.length; i++){
        if(((shapes[i].x + shapes[i].sx) <= posFront)){
            if(((shapes[i].y + shapes[i].sy) <= posRight) && ((shapes[i].y + shapes[i].sy) >= posLeft)){
                if(heal > 0){
                    heal = heal - 1;
                    if(heal === 0){
                        gameOver();
                    }
                }
            }
        }
    }
}

function drawShapes(){
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    for(x in shapes){
        shapes[x].draw();
    }

    ctx.font = '10pt Arial';
    ctx.fillStyle = 'black';
    ctx.fillText('LEVEL: '+ level , 1000, 20);
    ctx.fillText('LIVES: '+ heal , 1000, 40);
    ctx.fillText('POINTS: '+ count, 1000,60);
}

function getShape(id) {
    for(x in shapes) {
        if(shapes[x].id === id){
            return shapes[x];
        }
    }
}

function keyHandler(event) {
    var obj;
    obj = getShape("hero");
    if(obj === undefined)
        return;

    switch(event.key) {
        case "w":
        obj.move(-desp);
        break;
    case "s":
        obj.move(+desp);
        break;
    default:
        console.log("Key not handled");
  }
}

function render() {

    var obj = getShape("hero");
    if((count === 1) || ((count % click) === 0 )){
        shapes.push(new Enemy("Enemy"+count , posEnemyX, 400*(Math.random()), 40, 20, 'rgba(255, 0, 0, 0.5)'));
    }
    checkCollides();
    moveEnemies();
    count++;
    drawShapes();
    if((count % 150) === 0){
        enemySpeed = enemySpeed + 10000;
        if(enemySpeed === 70000){
            click = 5;
        }
    }
}

function main(){
    canvas = document.getElementById('espacioexterior');
    if (!canvas) {
        console.log('Failed to retrieve the <canvas> element');
        return false;
    }
    ctx = canvas.getContext('2d');
    document.addEventListener('keydown', keyHandler, false);

    shapes.push(new Hero("hero", posHeroY, 20, 'rgba(0, 0, 255, 1)'));

    setInterval(render, dt);
}

<|endoftext|>


<commit_before>/*
 * Appcelerator Titanium Mobile
 * Copyright (c) 2011-2012 by Appcelerator, Inc. All Rights Reserved.
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 */

module.exports = new function() {
	var finish;
	var valueOf;
	this.init = function(testUtils) {
		finish = testUtils.finish;
		valueOf = testUtils.valueOf;
	}

	this.name = "ui_optionDialog";
	this.tests = [
		{name: "dialogBox", timeout: 60000}
	];

	//TIMOB-7548
	this.dialogBox = function(testRun){
		var win = Ti.UI.createWindow();
		var dialog = Titanium.UI.createOptionDialog({
			options: ['Option 1','Option 2'],
			cancel:1
		});
		var fun = function(){
			dialog.show();
			dialog.hide();
			setTimeout(function(){
				valueOf(testRun, function(){
					dialog.show();
				}).shouldNotThrowException();

				finish(testRun);
			},2000);
		};
		win.addEventListener('focus', fun);
		win.open();
	}
}<commit_msg>[QE-678] focus event replaced by postlayout<commit_after>/*
 * Appcelerator Titanium Mobile
 * Copyright (c) 2011-2012 by Appcelerator, Inc. All Rights Reserved.
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 */

module.exports = new function() {
	var finish;
	var valueOf;
	this.init = function(testUtils) {
		finish = testUtils.finish;
		valueOf = testUtils.valueOf;
	}

	this.name = "ui_optionDialog";
	this.tests = [
		{name: "dialogBox", timeout: 60000}
	];

	//TIMOB-7548
	this.dialogBox = function(testRun){
		var win = Ti.UI.createWindow();
		var dialog = Titanium.UI.createOptionDialog({
			options: ['Option 1','Option 2'],
			cancel:1
		});
		var fun = function(){
			dialog.show();
			dialog.hide();
			setTimeout(function(){
				valueOf(testRun, function(){
					dialog.show();
				}).shouldNotThrowException();

				finish(testRun);
			},2000);
		};
		win.addEventListener('postlayout', fun);
		win.open();
	}
}<|endoftext|>


<commit_before>/*
 * grunt-github-changes
 * https://github.com/streetlight/grunt-github-changes
 *
 * Copyright (c) 2014 Nick Weingartner
 * Licensed under the MIT license.
 */

'use strict';

var exec = require('child_process').exec;

module.exports = function (grunt) {

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  grunt.registerMultiTask('githubChanges', 'Grunt plugin to run github changes (changelog generator)', function () {

    // Merge task-specific and/or target-specific options with these defaults.
    var done = this.async(),
       options = this.options({
        owner : 'owner',
        repository : 'repository',
        branch : null,
        tagName : null,
        auth : null,
        token : null,
        file : null,
        verbose : false,
        host : null,
        pathPrefix : null,
        noMerges : false,
        onlyMerges : false,
        onlyPulls : false,
        useCommitBody : false,
        orderSemver : false
    });

    if (!options.owner || !options.repository) {
        console.error("Owner and Repository fields are mandatory");
    }

    var createArgString = function (options) {

        var ghC = require.resolve('github-changes/bin/index.js'),
           owner = '-o '+ options.owner,
           repository = '-r ' + options.repository,
           branch = options.branch ? '-b ' + options.branch : null,
           tagName = options.tagName ? '-n ' + options.tagName : null,
           auth = options.auth ? '-a ' + options.auth : null,
           token = options.token ? '-k ' + options.token : null,
           file = options.file ? '-f ' + options.file : null,
           verbose = options.verbose ? '-v' : null,
           host = options.host ? '--host ' + options.host : null,
           pathPrefix = options.pathPrefix ? '--path-prefix ' + options.pathPrefix : null,
           noMerges = options.noMerges ? '--no-merges' : null,
           onlyMerges = options.onlyMerges ? '--only-merges' : null,
           onlyPulls = options.onlyPulls ? '--only-pulls' : null,
           useCommitBody = options.useCommitBody ? '--use-commit-body' : null,
           orderSemver = options.orderSemver ? '--order-semver' : null;

        return [
            ghC,
            owner,
            repository,
            branch,
            tagName,
            auth,
            token,
            file,
            verbose,
            host,
            pathPrefix,
            noMerges,
            onlyMerges,
            onlyPulls,
            useCommitBody,
            orderSemver
        ].join(" ");
    };

    var cp = exec(createArgString(options), {}, function (error) {
        if (!error) {
            console.log("Changelog generated");
            done();
        } else {
            grunt.warn(error);
        }
    });

    var captureOutput = function (child, output) {
        child.pipe(output);
    };

    captureOutput(cp.stdout, process.stdout);

  });

};
<commit_msg>Secondary clean<commit_after>/*
 * grunt-github-changes
 * https://github.com/streetlight/grunt-github-changes
 *
 * Copyright (c) 2014 Nick Weingartner
 * Licensed under the MIT license.
 */

'use strict';

var exec = require('child_process').exec;

module.exports = function (grunt) {

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  grunt.registerMultiTask('githubChanges', 'Grunt plugin to run github changes (changelog generator)', function () {

    // Merge task-specific and/or target-specific options with these defaults.
    var done = this.async(),
       options = this.options({
        owner : 'owner',
        repository : 'repository',
        branch : null,
        tagName : null,
        auth : null,
        token : null,
        file : null,
        verbose : false,
        host : null,
        pathPrefix : null,
        noMerges : false,
        onlyMerges : false,
        onlyPulls : false,
        useCommitBody : false,
        orderSemver : false
    });

    if (!options.owner || !options.repository) {
        console.error("Owner and Repository fields are mandatory");
    }

    var createArgString = function (options) {

        var ghC = require.resolve('github-changes/bin/index.js'),
           owner = '-o '+ options.owner,
           repository = '-r ' + options.repository,
           branch = options.branch ? '-b ' + options.branch : null,
           tagName = options.tagName ? '-n ' + options.tagName : null,
           auth = options.auth ? '-a ' + options.auth : null,
           token = options.token ? '-k ' + options.token : null,
           file = options.file ? '-f ' + options.file : null,
           verbose = options.verbose ? '-v' : null,
           host = options.host ? '--host ' + options.host : null,
           pathPrefix = options.pathPrefix ? '--path-prefix ' + options.pathPrefix : null,
           noMerges = options.noMerges ? '--no-merges' : null,
           onlyMerges = options.onlyMerges ? '--only-merges' : null,
           onlyPulls = options.onlyPulls ? '--only-pulls' : null,
           useCommitBody = options.useCommitBody ? '--use-commit-body' : null,
           orderSemver = options.orderSemver ? '--order-semver' : null;

        return [
            process.execPath,
            ghC,
            owner,
            repository,
            branch,
            tagName,
            auth,
            token,
            file,
            verbose,
            host,
            pathPrefix,
            noMerges,
            onlyMerges,
            onlyPulls,
            useCommitBody,
            orderSemver
        ].join(" ");
    };

    var cp = exec(createArgString(options), {}, function (error) {
        if (!error) {
            console.log("Changelog generated");
            done();
        } else {
            grunt.warn(error);
        }
    });

    var captureOutput = function (child, output) {
        child.pipe(output);
    };

    captureOutput(cp.stdout, process.stdout);

  });

};
<|endoftext|>


<commit_before>/*!
 * Copyright 2014 Apereo Foundation (AF) Licensed under the
 * Educational Community License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may
 * obtain a copy of the License at
 *
 *     http://opensource.org/licenses/ECL-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an "AS IS"
 * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

define(['jquery', 'oae.core', 'jquery.history'], function($, oae) {

    return function(uid) {

        // The widget container
        var $rootel = $('#' + uid);

        // Variable that will be used to keep track of the provided page structure
        var lhNavigationPages = null;

        // Variable that will be used to keep track of the base URL of the current page
        var baseUrl = null;

        // Variable that will be used to keep track of the first part of the browser title
        // that needs to be set for each page
        var baseBrowserTitle = null;

        /**
         * Render a newly selected page. We first deselect the previously selected page, and then put an active
         * marker on the newly selected page in the navigation. Next, the page content associated to that is shown
         * (if it has been rendered previously) or rendered.
         */
        var renderPage = function() {
            // Remove the active indicator on the previously selected page
            $('.oae-lhnavigation ul li', $rootel).removeClass('active');

            // Get the current page from the History.js state and select it
            var selectedPage = getPage(History.getState().data.page);
            // Mark the selected page as active in the left hand navigation
            $('.oae-lhnavigation ul li[data-id="' + selectedPage.id + '"]', $rootel).addClass('active');

            // Set the browser title
            var browserTitle = baseBrowserTitle ? [baseBrowserTitle] : [];
            browserTitle.push(selectedPage.title);
            oae.api.util.setBrowserTitle(browserTitle);

            // Hide the current open page
            $('.oae-page > div:not(#lhnavigation-toggle-container)', $rootel).hide();

            // Render the page's content. We first check if the page has been rendered before. If that's
            // the case, we just show it again. Otherwise, we render the page structure first and render
            // all of the widgets
            var $pageContainer = $('.oae-page', $rootel);
            var $cachedPage = $('div[data-page="' + selectedPage.id + '"]', $pageContainer);
            if ($cachedPage.length > 0) {
                $cachedPage.show();
            } else {
                $pageContainer.append(oae.api.util.template().render($('#lhnavigation-page-template'), {
                    'selectedPage': selectedPage
                }));

                // Collect the widget data into a format that is understood by the widget loader
                var widgetData = {};
                $.each(selectedPage.layout, function(columnIndex, column) {
                    $.each(column.widgets, function(widgetIndex, widget) {
                        if (widget.settings) {
                            widgetData['lhnavigation-widget-' + (widget.id || widget.name)] = widget.settings;
                        }
                    });
                });

                // Render the widgets and pass in the widget data
                oae.api.widget.loadWidgets($pageContainer, false, widgetData);
            }
        };

        /**
         * Get the page with a given page id from the provided page structure.
         *
         * @param  {String}     pageId      Id of the page we want to retrieve from the provided pagestructure
         * @return {Object}                 Object representing the page with the provided page id. If no page with the provided page id can be found, the first page will be returned
         */
        var getPage = function(pageId) {
            for (var i = 0; i < lhNavigationPages.length; i++) {
                if (lhNavigationPages[i].id === pageId) {
                    return lhNavigationPages[i];
                }
            }
            // Return the first page if no page with the provided id can be found
            return lhNavigationPages[0];
        };

        /**
         * Render the left hand navigation based on the structure that has been passed in
         * and start listening to click events for the different elements in there.
         *
         * @param  {Object[]}    lhNavPages                 The page navigation structure
         * @param  {Object[]}    [lhNavActions]             The action buttons structure
         * @param  {String}      [baseUrl]                  The current page's base URL. The different page ids will be appended to this to generate the full URL of each page
         */
        var setUpNavigation = function(lhNavPages, lhNavActions, baseUrl) {
            // Render the navigation
            var renderedNavigation = oae.api.util.template().render($('#lhnavigation-navigation-template', $rootel), {
                'lhNavPages': lhNavPages,
                'lhNavActions': lhNavActions,
                'baseUrl': baseUrl
            });
            $('.oae-lhnavigation > ul.nav', $rootel).html(renderedNavigation);

            // Render clip actions first
            if (lhNavActions && lhNavActions.length) {
                setUpNavigationActions();
            }

            // Extract the currently selected page from the URL by parsing the URL fragment that's
            // inside of the current History.js hash. The expected URL structure is
            // `<baseUrl>/<pageId>/[<widgetPath>][?q=foo]`, where `pageId` represents the id of the
            // current page and `widgetPath` represents an optional URL fragment added by the page's
            // widget for internal navigation purposes.
            // This will only be executed when the page is loaded.
            var loadedUrl = $.url(History.getState().hash);

            // Remove the `baseUrl` from the URL
            loadedUrlSegments = loadedUrl.segment().slice(baseUrl.split('/').length - 1);
            var pageId = loadedUrlSegments[0];
            var selectedPage = getPage(pageId);
            var widgetPath = loadedUrlSegments[1];

            // Retrieve the search query from the querystring
            var query = loadedUrl.param().q;

            // When the page loads, the History.js state data object will either be empty (when having
            // followed a link or entering the URL directly) or will contain the previous state data when
            // refreshing the page. This is why we use the URL to determine the initial state. We want
            // to replace the initial state with all of the required state data for the requested URL so
            // we have the correct state data in all circumstances. Calling the `replaceState` function
            // will automatically trigger the statechange event, which will take care of the page rendering.
            // for the requested module. However, as the page can already have the History.js state data
            // when only doing a page refresh, we need to add a random number to make sure that History.js
            // recognizes this as a new state and triggers the `statechange` event.
            var data = {
                'basePath': baseUrl + '/' + pageId,
                'page': pageId,
                'widgetPath': widgetPath,
                '_': Math.random()
            };

            // Although the `title` and `url` field are optional, we need to enter them as IE9 simply doesn't
            // handle their absense very well. We cannot lose any parameters such as the `q` query string
            // parameter as IE9 is not able to recover it from its state.
            var title = selectedPage.title;
            var url = $.url(History.getState().hash).attr('path');
            if (query) {
                data.query = query;
                url += '?q=' + query;
            }

            // Replace the old state.
            History.replaceState(data, title, url);

            // Bind the click event
            $rootel.on('click', '.oae-lhnavigation ul li[data-id]', function(ev) {
                // Only push state when a link other than the active one has been clicked
                if (!$(this).hasClass('active')) {
                    var page = getPage($(this).attr('data-id'));
                    var title = page.title;
                    var url = $('a', $(this)).attr('href');
                    var data = {
                        'basePath': url,
                        'page': page.id
                    };
                    // Push the state and render the selected page
                    History.pushState(data, title, url);
                }
                ev.preventDefault();
            });
        };

        /**
         * Bind the navigation actions
         */
        var setUpNavigationActions = function() {
            // Set up the collapsable menu items
            $rootel.on('click', '.oae-lhnavigation > ul > li > button', function(ev) {
                $(this).next('.lhnavigation-collapsed').toggle({
                    'duration': 250,
                    'easing': 'linear'
                });
                $(this).find('.lhnavigation-caret-container i').toggle();
            });
        };

        /**
         * The statechange event will be triggered every time the browser back or forward button
         * is pressed or state is pushed/replaced using History.js.
         */
        $(window).on('statechange', renderPage);

        /**
         * Initialise a new left hand navigation structure by triggering event that define the pages
         * and actions that need to be rendered in the navigation. In case this widget isn't ready at
         * the time when the supplying page sends out its request, we also send out a ready event,
         * which allows for the supplying widget to resend its data.
         *
         * A left hand navigation contains 2 different sections. The first section is a list of action
         * buttons that can replace the page clips when the viewport width is too small to render them.
         * These actions can also be grouped into collapsible sections. An example array required to
         * initiate these action buttons is the following:
         *
         * [
         *     {
         *         'icon': 'fa-cloud-upload',
         *         'title': oae.api.i18n.translate('__MSG__UPLOAD__'),
         *         'class': 'oae-trigger-upload'
         *     },
         *     {
         *         'icon': 'fa-plus-circle',
         *         'title': oae.api.i18n.translate('__MSG__CREATE__'),
         *         'children': [
         *             {
         *                 'icon': 'fa-group',
         *                 'title': oae.api.i18n.translate('__MSG__GROUP__'),
         *                 'class': 'oae-trigger-creategroup'
         *             }
         *         ]
         *     }
         * ]
         *
         * Notes:
         *
         * - `title` is the title of the action button.
         * - `icon` is the FontAwesome icon class that preceeds the title of the action button.
         *    @see http://fontawesome.io/3.2.1/
         * - `class` can be used to add one or more CSS classes to the action button. Multiple classes can be
         *    added by separating them with a space. This can for example be used to add widget triggers to
         *    an action button.
         * - `closeNav` determines whether or not the left hand navigation should be closed when the current
         *   item is seelcted.
         * - `children` is an optional array of action buttons that will be rendered as children of the list item
         *   it belongs to. Each child item has the same properties as top level items.
         *
         * The second section is a list of pages. Each of these pages will render one or more widgets when clicked.
         * An example array required to initiate these pages is the following:
         *
         * [
         *     {
         *         'id': 'dashboard',
         *         'title': oae.api.i18n.translate('__MSG__RECENT_ACTIVITY__'),
         *         'closeNav': true,
         *         'icon': 'fa-tachometer',
         *         'layout': [
         *             {
         *                 'id': 'activity',
         *                 'width': 'col-md-12',
         *                 'widgets': [
         *                         'name': 'activity',
         *                         'settings': {
         *                             'context': oae.data.me,
         *                             'canManage': true
         *                         }
         *                     }
         *                 ]
         *             }
         *         ]
         *     }
         * ]
         *
         * Notes:
         *
         * - `id` is the page alias that will be used in the url (e.g. /baseUrl/<pageId>).
         * - `title` is the title of the navigation item.
         * - `icon` is the FontAwesome icon class that preceeds the title of the navigation item.
         *    @see http://fontawesome.io/3.2.1/
         * - `layout` defines the structure of the page that is associated to the navigation item.
         *    It contains the following properties:
         *     - `width` defines the page width, leveraging Bootstrap's grid system
         *       @see http://getbootstrap.com/css/#grid
         *     - `widgets` defines an array of widgets to be loaded on the page containing the following properties:
         *         - `id` is the unique id that should be applied to the widget container. If no `id` is provided,
         *            the widget name will be used instead
         *         - `name` is the name of the widget to be loaded
         *         - `settings` is a widget settings object that will be passed into the widget as widget data
         */
        $(window).on('oae.trigger.lhnavigation', function(ev, _lhNavigationPages, _lhNavigationActions, _baseUrl, _baseBrowserTitle) {
            lhNavigationPages = _lhNavigationPages;
            baseUrl = _baseUrl;
            baseBrowserTitle = _baseBrowserTitle;
            setUpNavigation(_lhNavigationPages, _lhNavigationActions, _baseUrl);
        });
        $(window).trigger('oae.ready.lhnavigation');

    };
});
<commit_msg>Fixed problem where undefined would show in the URL for a user's library<commit_after>/*!
 * Copyright 2014 Apereo Foundation (AF) Licensed under the
 * Educational Community License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may
 * obtain a copy of the License at
 *
 *     http://opensource.org/licenses/ECL-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an "AS IS"
 * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

define(['jquery', 'oae.core', 'jquery.history'], function($, oae) {

    return function(uid) {

        // The widget container
        var $rootel = $('#' + uid);

        // Variable that will be used to keep track of the provided page structure
        var lhNavigationPages = null;

        // Variable that will be used to keep track of the base URL of the current page
        var baseUrl = null;

        // Variable that will be used to keep track of the first part of the browser title
        // that needs to be set for each page
        var baseBrowserTitle = null;

        /**
         * Render a newly selected page. We first deselect the previously selected page, and then put an active
         * marker on the newly selected page in the navigation. Next, the page content associated to that is shown
         * (if it has been rendered previously) or rendered.
         */
        var renderPage = function() {
            // Remove the active indicator on the previously selected page
            $('.oae-lhnavigation ul li', $rootel).removeClass('active');

            // Get the current page from the History.js state and select it
            var selectedPage = getPage(History.getState().data.page);
            // Mark the selected page as active in the left hand navigation
            $('.oae-lhnavigation ul li[data-id="' + selectedPage.id + '"]', $rootel).addClass('active');

            // Set the browser title
            var browserTitle = baseBrowserTitle ? [baseBrowserTitle] : [];
            browserTitle.push(selectedPage.title);
            oae.api.util.setBrowserTitle(browserTitle);

            // Hide the current open page
            $('.oae-page > div:not(#lhnavigation-toggle-container)', $rootel).hide();

            // Render the page's content. We first check if the page has been rendered before. If that's
            // the case, we just show it again. Otherwise, we render the page structure first and render
            // all of the widgets
            var $pageContainer = $('.oae-page', $rootel);
            var $cachedPage = $('div[data-page="' + selectedPage.id + '"]', $pageContainer);
            if ($cachedPage.length > 0) {
                $cachedPage.show();
            } else {
                $pageContainer.append(oae.api.util.template().render($('#lhnavigation-page-template'), {
                    'selectedPage': selectedPage
                }));

                // Collect the widget data into a format that is understood by the widget loader
                var widgetData = {};
                $.each(selectedPage.layout, function(columnIndex, column) {
                    $.each(column.widgets, function(widgetIndex, widget) {
                        if (widget.settings) {
                            widgetData['lhnavigation-widget-' + (widget.id || widget.name)] = widget.settings;
                        }
                    });
                });

                // Render the widgets and pass in the widget data
                oae.api.widget.loadWidgets($pageContainer, false, widgetData);
            }
        };

        /**
         * Get the page with a given page id from the provided page structure.
         *
         * @param  {String}     pageId      Id of the page we want to retrieve from the provided pagestructure
         * @return {Object}                 Object representing the page with the provided page id. If no page with the provided page id can be found, the first page will be returned
         */
        var getPage = function(pageId) {
            for (var i = 0; i < lhNavigationPages.length; i++) {
                if (lhNavigationPages[i].id === pageId) {
                    return lhNavigationPages[i];
                }
            }
            // Return the first page if no page with the provided id can be found
            return lhNavigationPages[0];
        };

        /**
         * Render the left hand navigation based on the structure that has been passed in
         * and start listening to click events for the different elements in there.
         *
         * @param  {Object[]}    lhNavPages                 The page navigation structure
         * @param  {Object[]}    [lhNavActions]             The action buttons structure
         * @param  {String}      [baseUrl]                  The current page's base URL. The different page ids will be appended to this to generate the full URL of each page
         */
        var setUpNavigation = function(lhNavPages, lhNavActions, baseUrl) {
            // Render the navigation
            var renderedNavigation = oae.api.util.template().render($('#lhnavigation-navigation-template', $rootel), {
                'lhNavPages': lhNavPages,
                'lhNavActions': lhNavActions,
                'baseUrl': baseUrl
            });
            $('.oae-lhnavigation > ul.nav', $rootel).html(renderedNavigation);

            // Render clip actions first
            if (lhNavActions && lhNavActions.length) {
                setUpNavigationActions();
            }

            // Extract the currently selected page from the URL by parsing the URL fragment that's
            // inside of the current History.js hash. The expected URL structure is
            // `<baseUrl>/<pageId>/[<widgetPath>][?q=foo]`, where `pageId` represents the id of the
            // current page and `widgetPath` represents an optional URL fragment added by the page's
            // widget for internal navigation purposes.
            // This will only be executed when the page is loaded.
            var loadedUrl = $.url(History.getState().hash);

            // Remove the `baseUrl` from the URL
            loadedUrlSegments = loadedUrl.segment().slice(baseUrl.split('/').length - 1);
            // Extract the selected page from the URL. Note that the page id will not be
            // present in the URL when the base URL has been opened in itself. In that case,
            // we re-assign the page id once the first page in the navigation has been returned.
            var pageId = loadedUrlSegments[0];
            var selectedPage = getPage(pageId);
            pageId = selectedPage.id;
            var widgetPath = loadedUrlSegments[1];

            // Retrieve the search query from the querystring
            var query = loadedUrl.param().q;

            // When the page loads, the History.js state data object will either be empty (when having
            // followed a link or entering the URL directly) or will contain the previous state data when
            // refreshing the page. This is why we use the URL to determine the initial state. We want
            // to replace the initial state with all of the required state data for the requested URL so
            // we have the correct state data in all circumstances. Calling the `replaceState` function
            // will automatically trigger the statechange event, which will take care of the page rendering.
            // for the requested module. However, as the page can already have the History.js state data
            // when only doing a page refresh, we need to add a random number to make sure that History.js
            // recognizes this as a new state and triggers the `statechange` event.
            var data = {
                'basePath': baseUrl + '/' + pageId,
                'page': pageId,
                'widgetPath': widgetPath,
                '_': Math.random()
            };

            // Although the `title` and `url` field are optional, we need to enter them as IE9 simply doesn't
            // handle their absense very well. We cannot lose any parameters such as the `q` query string
            // parameter as IE9 is not able to recover it from its state.
            var title = selectedPage.title;
            var url = $.url(History.getState().hash).attr('path');
            if (query) {
                data.query = query;
                url += '?q=' + query;
            }

            // Replace the old state.
            History.replaceState(data, title, url);

            // Bind the click event
            $rootel.on('click', '.oae-lhnavigation ul li[data-id]', function(ev) {
                // Only push state when a link other than the active one has been clicked
                if (!$(this).hasClass('active')) {
                    var page = getPage($(this).attr('data-id'));
                    var title = page.title;
                    var url = $('a', $(this)).attr('href');
                    var data = {
                        'basePath': url,
                        'page': page.id
                    };
                    // Push the state and render the selected page
                    History.pushState(data, title, url);
                }
                ev.preventDefault();
            });
        };

        /**
         * Bind the navigation actions
         */
        var setUpNavigationActions = function() {
            // Set up the collapsable menu items
            $rootel.on('click', '.oae-lhnavigation > ul > li > button', function(ev) {
                $(this).next('.lhnavigation-collapsed').toggle({
                    'duration': 250,
                    'easing': 'linear'
                });
                $(this).find('.lhnavigation-caret-container i').toggle();
            });
        };

        /**
         * The statechange event will be triggered every time the browser back or forward button
         * is pressed or state is pushed/replaced using History.js.
         */
        $(window).on('statechange', renderPage);

        /**
         * Initialise a new left hand navigation structure by triggering event that define the pages
         * and actions that need to be rendered in the navigation. In case this widget isn't ready at
         * the time when the supplying page sends out its request, we also send out a ready event,
         * which allows for the supplying widget to resend its data.
         *
         * A left hand navigation contains 2 different sections. The first section is a list of action
         * buttons that can replace the page clips when the viewport width is too small to render them.
         * These actions can also be grouped into collapsible sections. An example array required to
         * initiate these action buttons is the following:
         *
         * [
         *     {
         *         'icon': 'fa-cloud-upload',
         *         'title': oae.api.i18n.translate('__MSG__UPLOAD__'),
         *         'class': 'oae-trigger-upload'
         *     },
         *     {
         *         'icon': 'fa-plus-circle',
         *         'title': oae.api.i18n.translate('__MSG__CREATE__'),
         *         'children': [
         *             {
         *                 'icon': 'fa-group',
         *                 'title': oae.api.i18n.translate('__MSG__GROUP__'),
         *                 'class': 'oae-trigger-creategroup'
         *             }
         *         ]
         *     }
         * ]
         *
         * Notes:
         *
         * - `title` is the title of the action button.
         * - `icon` is the FontAwesome icon class that preceeds the title of the action button.
         *    @see http://fontawesome.io/3.2.1/
         * - `class` can be used to add one or more CSS classes to the action button. Multiple classes can be
         *    added by separating them with a space. This can for example be used to add widget triggers to
         *    an action button.
         * - `closeNav` determines whether or not the left hand navigation should be closed when the current
         *   item is seelcted.
         * - `children` is an optional array of action buttons that will be rendered as children of the list item
         *   it belongs to. Each child item has the same properties as top level items.
         *
         * The second section is a list of pages. Each of these pages will render one or more widgets when clicked.
         * An example array required to initiate these pages is the following:
         *
         * [
         *     {
         *         'id': 'dashboard',
         *         'title': oae.api.i18n.translate('__MSG__RECENT_ACTIVITY__'),
         *         'closeNav': true,
         *         'icon': 'fa-tachometer',
         *         'layout': [
         *             {
         *                 'id': 'activity',
         *                 'width': 'col-md-12',
         *                 'widgets': [
         *                         'name': 'activity',
         *                         'settings': {
         *                             'context': oae.data.me,
         *                             'canManage': true
         *                         }
         *                     }
         *                 ]
         *             }
         *         ]
         *     }
         * ]
         *
         * Notes:
         *
         * - `id` is the page alias that will be used in the url (e.g. /baseUrl/<pageId>).
         * - `title` is the title of the navigation item.
         * - `icon` is the FontAwesome icon class that preceeds the title of the navigation item.
         *    @see http://fontawesome.io/3.2.1/
         * - `layout` defines the structure of the page that is associated to the navigation item.
         *    It contains the following properties:
         *     - `width` defines the page width, leveraging Bootstrap's grid system
         *       @see http://getbootstrap.com/css/#grid
         *     - `widgets` defines an array of widgets to be loaded on the page containing the following properties:
         *         - `id` is the unique id that should be applied to the widget container. If no `id` is provided,
         *            the widget name will be used instead
         *         - `name` is the name of the widget to be loaded
         *         - `settings` is a widget settings object that will be passed into the widget as widget data
         */
        $(window).on('oae.trigger.lhnavigation', function(ev, _lhNavigationPages, _lhNavigationActions, _baseUrl, _baseBrowserTitle) {
            lhNavigationPages = _lhNavigationPages;
            baseUrl = _baseUrl;
            baseBrowserTitle = _baseBrowserTitle;
            setUpNavigation(_lhNavigationPages, _lhNavigationActions, _baseUrl);
        });
        $(window).trigger('oae.ready.lhnavigation');

    };
});
<|endoftext|>


<commit_before>// NIMOY

// -----------------------------------------------|
// trigger. build the system with specific options
// -----------------------------------------------|

var Environment = require('./_env_N')

var DefaultUser = {
  host:'blacksea',
  connections:'',
  modules:''
}

var EnvOpts = {
  path_wilds:'./_wilds',
  path_static:'./_static',
  path_styl:'./_static/default.styl',
  path_css:'./_static/styles.css',
  path_bundle:'./_static/bundle.js',
  path_js:'./_env_B.js',
  path_data:'./data',
  port:80,
}

// | ------------------------------------------------------------------
// | match process to scope in mod/desc ex. browser, pi, joyent, debian
// | provide process capabilities
// | -------------------------------------------------
// | implement level namespacing w. bookmarked modules
// | ----------------
// | port in watchify
// | ----------------
// | build ui in paperjs
// | ----------------------
// | implement modes & auth
// | -----------------------
// | build in module storage
// | -----------------------------------------------------
// | socket switch / router -- webRTC datachannel support?
// | -----------------------------------------------------

var Env = new Environment(EnvOpts, function serverRunning () {
  console.log('nimoy running on port '+EnvOpts.port)
  Env.api.write(['load',null])
  Env.api.write(['createBrico',DefaultUser])
})

// COMPILER

var through = require('through')
var asyncMap = require('slide').asyncMap
var uglifyJS = require('uglify-js')
var stylus = require('stylus')
var fs = require('fs')

// USE WATCHIFY TO UPDATE JS
// build with paperjs & ignore styles + html

var browserify = require('browserify')

module.exports = Compiler

function Compiler (opts) {
  if (opts.path_wilds[opts.path_wilds.length-1] !== '/') opts.path_wilds += '/'
  var Self = this
  var Wilds = opts.path_wilds
  var CSS = ''

  var b = browserify()
  b.add(opts.path_env)

  fs.readFile(opts.path_styl, function getDefaultStyl (e, buf) {
    if (e) console.error(e)
    if (!e) CSS += buf.toString()
  })

  this.s = through(HandleModule, Compile, {autoDestroy:false})

  function HandleModule (chunk) {
    var s = this
    var mod = JSON.parse(chunk.toString())

    b.require(Wilds+mod.id+'.js',{expose:mod.id})

    // handle deps
    if (!mod.deps) s.queue(chunk.toString())
    if (mod.deps) asyncMap(mod.deps, handleDep, function () {
      s.queue(JSON.stringify(mod))
      if (mod.fresh===true) Compile()
    })
    function handleDep (file, next) {
      var dep = ''
      var ext = file.split('.')[1]
      fs.readFile(Wilds+file, function (e,buf) {
        if (e) console.error(e)
        dep = buf.toString()
        if (ext==='styl') CSS += dep
        if (ext==='html') mod[ext] = dep
        next()
      })
    }
  }

  function Compile () {
    Self.s.emit('data', JSON.stringify({stat:'mapReady'}))

    var bundleFile = fs.createWriteStream(opts.path_bundle)
    b.bundle().pipe(bundleFile)

    bundleFile.on('error', function (e) {
      console.error(e)
    })
    bundleFile.on('close', function () {
      console.log('wrote '+opts.path_bundle)
      if (opts.compress === true) {
        var min = uglifyJS.minify(opts.path_bundle)
        fs.writeFile(opts.path_bundle, min.code, function (e) {
          if (!e) console.log('wrote minified '+opts.path_bundle)
        })
      }
    })

    stylus.render(CSS, {filename:opts.path_css}, function (e, compiledCSS) {
      if (e) console.error(e)
      fs.writeFile(opts.path_css, compiledCSS, function (e) {
        if (e) cosole.error(e)
        console.log('wrote '+opts.path_css)
      })
    })
  }
}
<commit_msg>update nimoy<commit_after>// NIMOY

var Brico = require('./_brico')
var Data = require('./_data')
var Map = require('./_map')
var Net = require('./_net')

var DefaultUser = {
  host:'blacksea',
  connections:'',
  modules:''
}

var EnvOpts = {
  path_wilds:'./_wilds',
  path_static:'./_static',
  path_styl:'./_static/default.styl',
  path_css:'./_static/styles.css',
  path_bundle:'./_static/bundle.js',
  path_js:'./_env_B.js',
  path_data:'./data',
  port:80,
}

<|endoftext|>


<commit_before>/**
 * This file is part of Shoop.
 *
 * Copyright (c) 2012-2015, Shoop Ltd. All rights reserved.
 *
 * This source code is licensed under the AGPLv3 license found in the
 * LICENSE file in the root directory of this source tree.
 */
var bowerFiles = require("./bower-files");
var root = require("path").resolve(__dirname + "/..");
module.exports = {
    "vendor": {
        "files": bowerFiles("./static_src/vendor")
    },
    "base": {
        "base": "./static_src/base",
        "es6": true,
        "files": [
            "js/materialize.js",
            "js/main-menu.js",
            "js/search.js",
            "js/tooltip.js",
            "js/timesince.js",
            "js/messages.js",
            "js/browse-widget.js",
            "js/side-nav.js",
            "js/content-blocks.js",
            "js/remarkable-field.js",
            "js/form-utils.js",
            "js/jquery.form-submission-attributes.polyfill.js",
            "js/datetimepicker.js"
        ]
    },
    "dashboard": {
        "files": bowerFiles("./static_src/dashboard")
    },
    "media-browser": {
        "webpack": root + "/modules/media/webpack.config.js",
        "watch": [
            "./modules/media/static_src/media/**/*.js"
        ]
    },
    "remarkable": {
        "webpack": root + "/static_src/remarkable/webpack.config.js",
        "watch": [
            "./static_src/remarkable/*.js"
        ]
    },
    "picotable": {
        "es6": true,
        "base": "./static_src/picotable",
        "files": [
            "picotable.js"
        ]
    },
    "product-variation-variable-editor": {
        "base": root + "/modules/products/static_src",
        "es6": true,
        "files": [
            "product-variation-variable-editor.js"
        ]
    },
    "product": {
        "base": "./static_src/product",
        "es6": true,
        "files": [
            "edit_media.js"
        ]
    },
    "order-creator": {
        "webpack": root + "/modules/orders/static_src/create/webpack.config.js",
        "watch": [
            root + "/modules/orders/static_src/create/**/*.js"
        ]
    }
};
<commit_msg>Admin js-packages: Turn on es6 switch for dashboard<commit_after>/**
 * This file is part of Shoop.
 *
 * Copyright (c) 2012-2015, Shoop Ltd. All rights reserved.
 *
 * This source code is licensed under the AGPLv3 license found in the
 * LICENSE file in the root directory of this source tree.
 */
var bowerFiles = require("./bower-files");
var root = require("path").resolve(__dirname + "/..");
module.exports = {
    "vendor": {
        "files": bowerFiles("./static_src/vendor")
    },
    "base": {
        "base": "./static_src/base",
        "es6": true,
        "files": [
            "js/materialize.js",
            "js/main-menu.js",
            "js/search.js",
            "js/tooltip.js",
            "js/timesince.js",
            "js/messages.js",
            "js/browse-widget.js",
            "js/side-nav.js",
            "js/content-blocks.js",
            "js/remarkable-field.js",
            "js/form-utils.js",
            "js/jquery.form-submission-attributes.polyfill.js",
            "js/datetimepicker.js"
        ]
    },
    "dashboard": {
        "es6": true,
        "files": bowerFiles("./static_src/dashboard")
    },
    "media-browser": {
        "webpack": root + "/modules/media/webpack.config.js",
        "watch": [
            "./modules/media/static_src/media/**/*.js"
        ]
    },
    "remarkable": {
        "webpack": root + "/static_src/remarkable/webpack.config.js",
        "watch": [
            "./static_src/remarkable/*.js"
        ]
    },
    "picotable": {
        "es6": true,
        "base": "./static_src/picotable",
        "files": [
            "picotable.js"
        ]
    },
    "product-variation-variable-editor": {
        "base": root + "/modules/products/static_src",
        "es6": true,
        "files": [
            "product-variation-variable-editor.js"
        ]
    },
    "product": {
        "base": "./static_src/product",
        "es6": true,
        "files": [
            "edit_media.js"
        ]
    },
    "order-creator": {
        "webpack": root + "/modules/orders/static_src/create/webpack.config.js",
        "watch": [
            root + "/modules/orders/static_src/create/**/*.js"
        ]
    }
};
<|endoftext|>


<commit_before>'use strict';

angular.module('app', ['ngRoute', 'frontendServices'])
.config(['$routeProvider', function($routeProvider) {
	$routeProvider.when('/main', {
		templateUrl: 'main.html',
		controller: 'MainCtrl'
	})
	.when('/register', {
		templateUrl: 'register.html',
		controller: 'RegisterCtrl'
	})
  .when('/dashboard', {
    templateUrl: 'dashboard.html',
    controller: 'DashboardCtrl'
  })
  .when('/pathflow', {
   templateUrl: 'pathflow.html',
   controller: 'PathFlowCtrl'
 })
  .when('/about', {
    templateUrl: 'about.html',
  })
  .otherwise({
    redirectTo: '/main'
  });
}])
.controller('MainCtrl', ['$scope', function($scope) {

}])
.controller('RegisterCtrl', ['$scope', function($scope) {

}])
.controller('DashboardCtrl', ['$scope', function($scope) {
  $scope.opt = {
    subsidizedPerc: 50
  }
  $scope.showAddOpt = false;
  $scope.opts = ['loans', 'car', 'major'];
  $scope.carYears = [];
  $scope.carPrices = [5000, 10000, 15000, 20000, 30000, 50000, 70000, 100000];
  for (var i = 2014; i < 2030; i++) {
    $scope.carYears.push(i);
  }
  $scope.majors=[
    'Petroleum Engineering',
    'Liberal Arts',
    'Mathematics',
    'Electrical Engineering',
    'Economics',
    'Computer Science',
    'Business Administration',
    'Biology',
    'Art',
    'Accounting'
  ];
  $scope.opt.salaries = []
  $scope.opt.salaries["Petroleum Engineering"] = [103000, 160000, 215200];
  $scope.opt.salaries["Liberal Arts"] = [36600, 60500, 60700];
  $scope.opt.salaries["Mathematics"] = [49400, 88000, 143570];
  $scope.opt.salaries["Electrical Engineering"] = [64300, 106000, 131200];
  $scope.opt.salaries["Economics"] = [50100, 96700, 154150];
  $scope.opt.salaries["Computer Science"] = [59800, 102000, 134100];
  $scope.opt.salaries["Business Administration"] = [43500, 71000, 121000];
  $scope.opt.salaries["Biology"] = [40200, 70800, 163000];
  $scope.opt.salaries["Art"] = [36100, 57100, 71240];
  $scope.opt.salaries["Accounting"] = [45300, 74900, 125100];

  $scope.chart = c3.generate({
    bindto: '#dashboard_chart',
    data: {
      x: 'x',
      columns: [
      ['x', '2014', '2015', '2016', '2017', '2018', '2019'],
       // ['data1', 80000 200, 100, 400, 150, 250],
       // ['data2', 50, 20, 10, 40, 15, 25],
       // ['data3', 50]
       ],
       axes: {
        salary: 'y2'
       }
     },
     axis: {
      x: {
        show: true
      },
      y2: {
        show: true
      }
    }
  });

 $scope.$watch('opt.carPrice', function() {

    console.log('caryear');

    var yearArr = new Array();
    var carArr = new Array();

    yearArr.push('x');
    carArr.push('Car Loan');
    for(var i = 2014; i < $scope.opt.carYear; i++ ) {
      yearArr.push(i);
      carArr.push(0);
    }
    yearArr.push($scope.opt.carYear);
    yearArr.push($scope.opt.carYear +1);
    yearArr.push($scope.opt.carYear + 2);
    yearArr.push($scope.opt.carYear +3);
    yearArr.push($scope.opt.carYear +4);

    carArr.push($scope.opt.carPrice);
    carArr.push($scope.opt.carPrice * 3/4);
    carArr.push($scope.opt.carPrice/2);
    carArr.push($scope.opt.carPrice/4);
    carArr.push(0);

    $scope.chart.load({
      columns: [
      yearArr,
      carArr
        //  ['data3', $scope.opt.subsidizedPerc, $scope.opt.subsidizedPerc * 2, $scope.subsidizedPerc * -1]
        ]
      });

  });

  $scope.$watch('opt.carYear', function() {
    testMe();
    console.log('caryear');

    var yearArr = new Array();
    var carArr = new Array();

    yearArr.push('x');
    carArr.push('Car Loan');
    for(var i = 2014; i < $scope.opt.carYear; i++ ) {
      yearArr.push(i);
      carArr.push(0);
    }
    yearArr.push($scope.opt.carYear);
    yearArr.push($scope.opt.carYear +1);
    yearArr.push($scope.opt.carYear + 2);
    yearArr.push($scope.opt.carYear +3);
    yearArr.push($scope.opt.carYear +4);

    carArr.push($scope.opt.carPrice);
    carArr.push($scope.opt.carPrice * 3/4);
    carArr.push($scope.opt.carPrice/2);
    carArr.push($scope.opt.carPrice/4);
    carArr.push(0);

    $scope.chart.load({
      columns: [
      yearArr,
      carArr
        //  ['data3', $scope.opt.subsidizedPerc, $scope.opt.subsidizedPerc * 2, $scope.subsidizedPerc * -1]
        ]
      });

  });

  $scope.$watch('opt.loanPayment', function() {
   if($scope.opt.subsidizedPerc <= 100 && $scope.opt.subsidizedPerc>=0 && $scope.opt.loanPayment > 500)  {
      var totalArr = calcTotal("UTA", $scope.opt.subsidizedPerc/100, $scope.opt.loanPayment);
      var returnArr = new Array();
      var yearArr = new Array();
      yearArr.push('x');
      returnArr.push('Loan Debt');
     // console.log(totalArr);
     for(var i = 0; i < totalArr.length; i ++)  {
      yearArr.push(2014+i);
      returnArr.push(totalArr[i].toFixed(2));
    }
    console.log(returnArr);
    $scope.chart.load({
      columns: [
      yearArr,
      returnArr,
        //  ['data3', $scope.opt.subsidizedPerc, $scope.opt.subsidizedPerc * 2, $scope.subsidizedPerc * -1]
        ]
      });
  }
}, true);

  $scope.$watch('opt.subsidizedPerc', function() {
    if($scope.opt.subsidizedPerc <= 100 && $scope.opt.subsidizedPerc>=0 && $scope.opt.loanPayment> 500)  {
      var totalArr = calcTotal("UTA", $scope.opt.subsidizedPerc/100, $scope.opt.loanPayment);
      var returnArr = new Array();
      var yearArr = new Array();
      yearArr.push('x');
      returnArr.push('Loan Debt');
     // console.log(totalArr);
     for(var i = 0; i < totalArr.length; i ++)  {
      yearArr.push(2014+i);
      returnArr.push(totalArr[i].toFixed(2));
    }
    console.log(returnArr);
    $scope.chart.load({
      columns: [
      yearArr,
      returnArr,
        //  ['data3', $scope.opt.subsidizedPerc, $scope.opt.subsidizedPerc * 2, $scope.subsidizedPerc * -1]
        ]
      });
  }
}, true);

  $scope.showHideAddOpt = function() {
    if ($scope.showAddOpt) {
      $scope.showAddOpt = '';
    }
    $scope.showAddOpt = !$scope.showAddOpt;
  }

  $scope.$watch('opt.major', function() {
    if ($scope.opt.major !== undefined) {
    var arr = ['salary: ' + $scope.opt.major, 0, 0, 0];
    arr.push.apply(arr, $scope.opt.salaries[$scope.opt.major]);
    $scope.chart.load({
      columns: [
        arr
      ]
    });
  }
  })
}])
.controller('CollegeFlowCtrl', ['$scope', function($scope) {
}])

.controller('PathFlowCtrl', ['$scope','Major', 'College', function($scope, Major, College) {
  $scope.majors = Major.query();
  $scope.orderProp = 'Total';
  $scope.colleges = College.query();
  $scope.collegeSelected = false;
  $scope.majorSelected = false;
    var total = 0;
        var majorPercentage = 0;

  $scope.universityClick = function(collegeId){
    $scope.collegeSelected = true;
    $scope.myCollege = college;
      total = $scope.myCollege.Total;

  };

  $scope.majorClick = function(major){
    $scope.majorSelected = true;
    $scope.myMajor = major;
      majorPercentage = ($scope.myMajor.StartingSalary / 12) * .25;
      $scope.chart = c3.generate({
          bindto: '#college-major-chart',
          data: {
              x: 'x',
              columns: [
                  ['x', '2014', '2015', '2016', '2017', '2018', '2019'],
                  // ['data1', 80000 200, 100, 400, 150, 250],
                  // ['data2', 50, 20, 10, 40, 15, 25],
                  // ['data3', 50]
              ]
          },
          axis: {
              x: {
                  show: true
              }
          }
      });

      var totalArr = calcTotalParse(total,.045, majorPercentage);
      var returnArr = new Array();
      var yearArr = new Array();
      yearArr.push('x');
      returnArr.push('data2');
      // console.log(totalArr);
      for(var i = 0; i < totalArr.length; i ++)  {
          yearArr.push(2014+i);
          returnArr.push(totalArr[i].toFixed(2));
      }
      console.log(returnArr);
      $scope.chart.load({
          columns: [
              yearArr,
              returnArr,
              //  ['data3', $scope.opt.subsidizedPerc, $scope.opt.subsidizedPerc * 2, $scope.subsidizedPerc * -1]
          ]
      });

  };

}]);<commit_msg>fixed<commit_after>'use strict';

angular.module('app', ['ngRoute', 'frontendServices'])
.config(['$routeProvider', function($routeProvider) {
	$routeProvider.when('/main', {
		templateUrl: 'main.html',
		controller: 'MainCtrl'
	})
	.when('/register', {
		templateUrl: 'register.html',
		controller: 'RegisterCtrl'
	})
  .when('/dashboard', {
    templateUrl: 'dashboard.html',
    controller: 'DashboardCtrl'
  })
  .when('/pathflow', {
   templateUrl: 'pathflow.html',
   controller: 'PathFlowCtrl'
 })
  .when('/about', {
    templateUrl: 'about.html',
  })
  .otherwise({
    redirectTo: '/main'
  });
}])
.controller('MainCtrl', ['$scope', function($scope) {

}])
.controller('RegisterCtrl', ['$scope', function($scope) {

}])
.controller('DashboardCtrl', ['$scope', function($scope) {
  $scope.opt = {
    subsidizedPerc: 50
  }
  $scope.showAddOpt = false;
  $scope.opts = ['loans', 'car', 'major'];
  $scope.carYears = [];
  $scope.carPrices = [5000, 10000, 15000, 20000, 30000, 50000, 70000, 100000];
  for (var i = 2014; i < 2030; i++) {
    $scope.carYears.push(i);
  }
  $scope.majors=[
    'Petroleum Engineering',
    'Liberal Arts',
    'Mathematics',
    'Electrical Engineering',
    'Economics',
    'Computer Science',
    'Business Administration',
    'Biology',
    'Art',
    'Accounting'
  ];
  $scope.opt.salaries = []
  $scope.opt.salaries["Petroleum Engineering"] = [103000, 160000, 215200];
  $scope.opt.salaries["Liberal Arts"] = [36600, 60500, 60700];
  $scope.opt.salaries["Mathematics"] = [49400, 88000, 143570];
  $scope.opt.salaries["Electrical Engineering"] = [64300, 106000, 131200];
  $scope.opt.salaries["Economics"] = [50100, 96700, 154150];
  $scope.opt.salaries["Computer Science"] = [59800, 102000, 134100];
  $scope.opt.salaries["Business Administration"] = [43500, 71000, 121000];
  $scope.opt.salaries["Biology"] = [40200, 70800, 163000];
  $scope.opt.salaries["Art"] = [36100, 57100, 71240];
  $scope.opt.salaries["Accounting"] = [45300, 74900, 125100];

  $scope.chart = c3.generate({
    bindto: '#dashboard_chart',
    data: {
      x: 'x',
      columns: [
      ['x', '2014', '2015', '2016', '2017', '2018', '2019'],
       // ['data1', 80000 200, 100, 400, 150, 250],
       // ['data2', 50, 20, 10, 40, 15, 25],
       // ['data3', 50]
       ],
       axes: {
        salary: 'y2'
       }
     },
     axis: {
      x: {
        show: true
      },
      y2: {
        show: true
      }
    }
  });

 $scope.$watch('opt.carPrice', function() {

    console.log('caryear');

    var yearArr = new Array();
    var carArr = new Array();

    yearArr.push('x');
    carArr.push('Car Loan');
    for(var i = 2014; i < $scope.opt.carYear; i++ ) {
      yearArr.push(i);
      carArr.push(0);
    }
    yearArr.push($scope.opt.carYear);
    yearArr.push($scope.opt.carYear +1);
    yearArr.push($scope.opt.carYear + 2);
    yearArr.push($scope.opt.carYear +3);
    yearArr.push($scope.opt.carYear +4);

    carArr.push($scope.opt.carPrice);
    carArr.push($scope.opt.carPrice * 3/4);
    carArr.push($scope.opt.carPrice/2);
    carArr.push($scope.opt.carPrice/4);
    carArr.push(0);

    $scope.chart.load({
      columns: [
      yearArr,
      carArr
        //  ['data3', $scope.opt.subsidizedPerc, $scope.opt.subsidizedPerc * 2, $scope.subsidizedPerc * -1]
        ]
      });

  });

  $scope.$watch('opt.carYear', function() {
    testMe();
    console.log('caryear');

    var yearArr = new Array();
    var carArr = new Array();

    yearArr.push('x');
    carArr.push('Car Loan');
    for(var i = 2014; i < $scope.opt.carYear; i++ ) {
      yearArr.push(i);
      carArr.push(0);
    }
    yearArr.push($scope.opt.carYear);
    yearArr.push($scope.opt.carYear +1);
    yearArr.push($scope.opt.carYear + 2);
    yearArr.push($scope.opt.carYear +3);
    yearArr.push($scope.opt.carYear +4);

    carArr.push($scope.opt.carPrice);
    carArr.push($scope.opt.carPrice * 3/4);
    carArr.push($scope.opt.carPrice/2);
    carArr.push($scope.opt.carPrice/4);
    carArr.push(0);

    $scope.chart.load({
      columns: [
      yearArr,
      carArr
        //  ['data3', $scope.opt.subsidizedPerc, $scope.opt.subsidizedPerc * 2, $scope.subsidizedPerc * -1]
        ]
      });

  });

  $scope.$watch('opt.loanPayment', function() {
   if($scope.opt.subsidizedPerc <= 100 && $scope.opt.subsidizedPerc>=0 && $scope.opt.loanPayment > 500)  {
      var totalArr = calcTotal("UTA", $scope.opt.subsidizedPerc/100, $scope.opt.loanPayment);
      var returnArr = new Array();
      var yearArr = new Array();
      yearArr.push('x');
      returnArr.push('Loan Debt');
     // console.log(totalArr);
     for(var i = 0; i < totalArr.length; i ++)  {
      yearArr.push(2014+i);
      returnArr.push(totalArr[i].toFixed(2));
    }
    console.log(returnArr);
    $scope.chart.load({
      columns: [
      yearArr,
      returnArr,
        //  ['data3', $scope.opt.subsidizedPerc, $scope.opt.subsidizedPerc * 2, $scope.subsidizedPerc * -1]
        ]
      });
  }
}, true);

  $scope.$watch('opt.subsidizedPerc', function() {
    if($scope.opt.subsidizedPerc <= 100 && $scope.opt.subsidizedPerc>=0 && $scope.opt.loanPayment> 500)  {
      var totalArr = calcTotal("UTA", $scope.opt.subsidizedPerc/100, $scope.opt.loanPayment);
      var returnArr = new Array();
      var yearArr = new Array();
      yearArr.push('x');
      returnArr.push('Loan Debt');
     // console.log(totalArr);
     for(var i = 0; i < totalArr.length; i ++)  {
      yearArr.push(2014+i);
      returnArr.push(totalArr[i].toFixed(2));
    }
    console.log(returnArr);
    $scope.chart.load({
      columns: [
      yearArr,
      returnArr,
        //  ['data3', $scope.opt.subsidizedPerc, $scope.opt.subsidizedPerc * 2, $scope.subsidizedPerc * -1]
        ]
      });
  }
}, true);

  $scope.showHideAddOpt = function() {
    if ($scope.showAddOpt) {
      $scope.showAddOpt = '';
    }
    $scope.showAddOpt = !$scope.showAddOpt;
  }

  $scope.$watch('opt.major', function() {
    if ($scope.opt.major !== undefined) {
    var arr = ['salary: ' + $scope.opt.major, 0, 0, 0];
    arr.push.apply(arr, $scope.opt.salaries[$scope.opt.major]);
    $scope.chart.load({
      columns: [
        arr
      ]
    });
  }
  })
}])
.controller('CollegeFlowCtrl', ['$scope', function($scope) {
}])

.controller('PathFlowCtrl', ['$scope','Major', 'College', function($scope, Major, College) {
  $scope.majors = Major.query();
  $scope.orderProp = 'Total';
  $scope.colleges = College.query();
  $scope.collegeSelected = false;
  $scope.majorSelected = false;
    var total = 0;
        var majorPercentage = 0;

  $scope.universityClick = function(college){
    $scope.collegeSelected = true;
    $scope.myCollege = college;
      total = $scope.myCollege.Total;

  };

  $scope.majorClick = function(major){
    $scope.majorSelected = true;
    $scope.myMajor = major;
      majorPercentage = ($scope.myMajor.StartingSalary / 12) * .25;
      $scope.chart = c3.generate({
          bindto: '#college-major-chart',
          data: {
              x: 'x',
              columns: [
                  ['x', '2014', '2015', '2016', '2017', '2018', '2019'],
                  // ['data1', 80000 200, 100, 400, 150, 250],
                  // ['data2', 50, 20, 10, 40, 15, 25],
                  // ['data3', 50]
              ]
          },
          axis: {
              x: {
                  show: true
              }
          }
      });

      var totalArr = calcTotalParse(total,.045, majorPercentage);
      var returnArr = new Array();
      var yearArr = new Array();
      yearArr.push('x');
      returnArr.push('data2');
      // console.log(totalArr);
      for(var i = 0; i < totalArr.length; i ++)  {
          yearArr.push(2014+i);
          returnArr.push(totalArr[i].toFixed(2));
      }
      console.log(returnArr);
      $scope.chart.load({
          columns: [
              yearArr,
              returnArr,
              //  ['data3', $scope.opt.subsidizedPerc, $scope.opt.subsidizedPerc * 2, $scope.subsidizedPerc * -1]
          ]
      });

  };

}]);<|endoftext|>