<commit_before>// Copyright 2021, University of Colorado Boulder

const execute = require( '../common/execute' );
const _ = require( 'lodash' ); // eslint-disable-line
const fs = require( 'fs' );

// constants
// Don't use getActiveRepos() since it cannot be run from the root
const contents = fs.readFileSync( 'perennial/data/active-repos', 'utf8' ).trim();
const repos = contents.split( '\n' ).map( sim => sim.trim() );

/**
 * Pulls all repos (with rebase)
 *
 * USAGE:
 * cd ${root containing all repos}
 * node perennial/js/scripts/pull-all.js
 *
 * @author Sam Reid (PhET Interactive Simulations)
 */
( async () => {

  const a = repos.map( repo => execute( 'git', [ 'pull', '--rebase' ], `${repo}`, {

    // resolve errors so Promise.all doesn't fail on first repo that cannot pull/rebase
    errors: 'resolve'
  } ) );
  const out = await Promise.all( a );

  // Report results
  for ( let i = 0; i < a.length; i++ ) {
    const repo = repos[ i ];
    const o = out[ i ];

    if ( o.code === 0 && o.stderr === '' && ( o.stdout === 'Already up to date.\nCurrent branch master is up to date.\n' ||
                                              o.stdout === 'Already up to date.\n' ) ) {

      // nothing to do
    }
    else {
      console.log( repo );
      if ( o.stdout.trim().length > 0 ) {
        console.log( o.stdout );
      }
      if ( o.stderr.trim().length > 0 ) {
        console.log( o.stderr );
      }
    }
  }
} )();<commit_msg>heading notation<commit_after>// Copyright 2021, University of Colorado Boulder

const execute = require( '../common/execute' );
const _ = require( 'lodash' ); // eslint-disable-line
const fs = require( 'fs' );

// constants
// Don't use getActiveRepos() since it cannot be run from the root
const contents = fs.readFileSync( 'perennial/data/active-repos', 'utf8' ).trim();
const repos = contents.split( '\n' ).map( sim => sim.trim() );

/**
 * Pulls all repos (with rebase)
 *
 * USAGE:
 * cd ${root containing all repos}
 * node perennial/js/scripts/pull-all.js
 *
 * @author Sam Reid (PhET Interactive Simulations)
 */
( async () => {

  const a = repos.map( repo => execute( 'git', [ 'pull', '--rebase' ], `${repo}`, {

    // resolve errors so Promise.all doesn't fail on first repo that cannot pull/rebase
    errors: 'resolve'
  } ) );
  const out = await Promise.all( a );

  // Report results
  for ( let i = 0; i < a.length; i++ ) {
    const repo = repos[ i ];
    const o = out[ i ];

    if ( o.code === 0 && o.stderr === '' && ( o.stdout === 'Already up to date.\nCurrent branch master is up to date.\n' ||
                                              o.stdout === 'Already up to date.\n' ) ) {

      // nothing to do
    }
    else {
      console.log( '##', repo );
      if ( o.stdout.trim().length > 0 ) {
        console.log( o.stdout );
      }
      if ( o.stderr.trim().length > 0 ) {
        console.log( o.stderr );
      }
    }
  }
} )();<|endoftext|>


<commit_before>export {OnsBackButton} from './ons-back-button';
export {OnsInput} from './ons-input';
export {OnsNavigator} from './ons-navigator';
export {OnsRange} from './ons-range';
export {OnsSelect} from './ons-select';
export {OnsSwitch} from './ons-switch';
export {OnsTab} from './ons-tab';
export {OnsTabbar} from './ons-tabbar';

import {PLATFORM} from 'aurelia-pal';
import {BrowserHistory} from 'aurelia-history-browser';
import {OnsRouter} from './ons-router';
import {Router, RouteLoader} from 'aurelia-router';
import {TemplatingRouteLoader} from 'aurelia-templating-router';
import {RouteRecognizer} from 'aurelia-route-recognizer';

Router.isNavigatingFirst;
Router.isNavigatingNew;
Router.isNavigatingForward;
Router.isNavigatingBack;
Router.isNavigatingRefresh;
Router.currentNavigationTracker;

Router.prototype.reset = function() {
  this.viewPorts = {};
  this.routes = [];
  this.baseUrl = '';
  this.isConfigured = false;
  this.isNavigating = false;
  this.isExplicitNavigation = false;
  this.isExplicitNavigationBack = false;
  this.isNavigatingFirst = false;
  this.isNavigatingNew = false;
  this.isNavigatingRefresh = false;
  this.isNavigatingForward = false;
  this.isNavigatingBack = false;
  this.navigation = [];
  this.currentInstruction = null;
  this._fallbackOrder = 100;
  this._recognizer = new RouteRecognizer();
  this._childRecognizer = new RouteRecognizer();
  this._configuredPromise = new Promise(resolve => {
    this._resolveConfiguredPromise = resolve;
  });
};

BrowserHistory.prototype.setState = function(key, value) {
  let state = Object.assign({}, this.history.state);
  state[key] = value;
  this.history.replaceState(state, null, null);
};

BrowserHistory.prototype.getState = function(key) {
  let state = Object.assign({}, this.history.state);
  return state[key];
};

export function configure(config) {
  config
    .singleton(RouteLoader, TemplatingRouteLoader)
    .singleton(Router, OnsRouter)
    .globalResources([
      './ons-back-button',
      './ons-input',
      './ons-navigator',
      './ons-range',
      './ons-select',
      './ons-switch',
      './ons-tab',
      './ons-tabbar',
      PLATFORM.moduleName('aurelia-templating-router/router-view'),
      PLATFORM.moduleName('aurelia-templating-router/route-href')
    ]);

  config.container.registerAlias(Router, OnsRouter);
}
<commit_msg>include history browser state fix<commit_after>export {OnsBackButton} from './ons-back-button';
export {OnsInput} from './ons-input';
export {OnsNavigator} from './ons-navigator';
export {OnsRange} from './ons-range';
export {OnsSelect} from './ons-select';
export {OnsSwitch} from './ons-switch';
export {OnsTab} from './ons-tab';
export {OnsTabbar} from './ons-tabbar';

import {DOM, PLATFORM} from 'aurelia-pal';
import {BrowserHistory} from 'aurelia-history-browser';
import {OnsRouter} from './ons-router';
import {Router, RouteLoader} from 'aurelia-router';
import {TemplatingRouteLoader} from 'aurelia-templating-router';
import {RouteRecognizer} from 'aurelia-route-recognizer';

Router.isNavigatingFirst;
Router.isNavigatingNew;
Router.isNavigatingForward;
Router.isNavigatingBack;
Router.isNavigatingRefresh;
Router.currentNavigationTracker;

Router.prototype.reset = function() {
  this.viewPorts = {};
  this.routes = [];
  this.baseUrl = '';
  this.isConfigured = false;
  this.isNavigating = false;
  this.isExplicitNavigation = false;
  this.isExplicitNavigationBack = false;
  this.isNavigatingFirst = false;
  this.isNavigatingNew = false;
  this.isNavigatingRefresh = false;
  this.isNavigatingForward = false;
  this.isNavigatingBack = false;
  this.navigation = [];
  this.currentInstruction = null;
  this._fallbackOrder = 100;
  this._recognizer = new RouteRecognizer();
  this._childRecognizer = new RouteRecognizer();
  this._configuredPromise = new Promise(resolve => {
    this._resolveConfiguredPromise = resolve;
  });
};

const routeStripper = /^#?\/*|\s+$/g;
const rootStripper = /^\/+|\/+$/g;
const trailingSlash = /\/$/;
const absoluteUrl = /^([a-z][a-z0-9+\-.]*:)?\/\//i;

function updateHash(location, fragment, replace) {
  if (replace) {
    let href = location.href.replace(/(javascript:|#).*$/, '');
    location.replace(href + '#' + fragment);
  } else {
    // Some browsers require that `hash` contains a leading #.
    location.hash = '#' + fragment;
  }
}

BrowserHistory.prototype.setState = function(key, value) {
  let state = Object.assign({}, this.history.state);
  state[key] = value;
  this.history.replaceState(state, null, null);
};

BrowserHistory.prototype.getState = function(key) {
  let state = Object.assign({}, this.history.state);
  return state[key];
};

BrowserHistory.prototype.activate = function(options) {
  if (this._isActive) {
    throw new Error('History has already been activated.');
  }

  let wantsPushState = !!options.pushState;

  this._isActive = true;
  this.options = Object.assign({}, { root: '/' }, this.options, options);

  // Normalize root to always include a leading and trailing slash.
  this.root = ('/' + this.options.root + '/').replace(rootStripper, '/');

  this._wantsHashChange = this.options.hashChange !== false;
  this._hasPushState = !!(this.history && this.history.pushState);
  this._usePushState = !!(this._hasPushState && this.options.pushState);

  // Determine how we check the URL state.
  let eventName;
  if (this._hasPushState) {
    eventName = 'popstate';
  } else if (this._wantsHashChange) {
    eventName = 'hashchange';
  }

  PLATFORM.addEventListener(eventName, this._checkUrlCallback);

  // Determine if we need to change the base url, for a pushState link
  // opened by a non-pushState browser.
  if (this._wantsHashChange && wantsPushState) {
    // Transition from hashChange to pushState or vice versa if both are requested.
    let loc = this.location;
    let atRoot = loc.pathname.replace(/[^\/]$/, '$&/') === this.root;

    // If we've started off with a route from a `pushState`-enabled
    // browser, but we're currently in a browser that doesn't support it...
    if (!this._usePushState && !atRoot) {
      this.fragment = this._getFragment(null, true);
      this.location.replace(this.root + this.location.search + '#' + this.fragment);
      // Return immediately as browser will do redirect to new url
      return true;

      // Or if we've started out with a hash-based route, but we're currently
      // in a browser where it could be `pushState`-based instead...
    } else if (this._usePushState && atRoot && loc.hash) {
      this.fragment = this._getHash().replace(routeStripper, '');
      this.history.replaceState({}, DOM.title, this.root + this.fragment + loc.search);
    }
  }

  if (!this.fragment) {
    this.fragment = this._getFragment();
  }

  this.linkHandler.activate(this);

  if (!this.options.silent) {
    return this._loadUrl();
  }
};

BrowserHistory.prototype.navigate = function(fragment, {trigger = true, replace = false} = {}) {
  if (fragment && absoluteUrl.test(fragment)) {
    this.location.href = fragment;
    return true;
  }

  if (!this._isActive) {
    return false;
  }

  fragment = this._getFragment(fragment || '');

  if (this.fragment === fragment && !replace) {
    return false;
  }

  this.fragment = fragment;

  let url = this.root + fragment;

  // Don't include a trailing slash on the root.
  if (fragment === '' && url !== '/') {
    url = url.slice(0, -1);
  }

  // If pushState is available, we use it to set the fragment as a real URL.
  if (this._hasPushState) {
    url = url.replace('//', '/');
    if (!this._usePushState) {
      url = '#' + url;
    }
    this.history[replace ? 'replaceState' : 'pushState']({}, DOM.title, url);
  } else if (this._wantsHashChange) {
    // If hash changes haven't been explicitly disabled, update the hash
    // fragment to store history.
    updateHash(this.location, fragment, replace);
  } else {
    // If you've told us that you explicitly don't want fallback hashchange-
    // based history, then `navigate` becomes a page refresh.
    return this.location.assign(url);
  }

  if (trigger) {
    return this._loadUrl(fragment);
  }
};

BrowserHistory.prototype._getFragment = function(fragment, forcePushState) {
  let root;

  if (!fragment) {
    if (this._usePushState || !this._wantsHashChange || forcePushState) {
      fragment = this.location.pathname + this.location.search;
      root = this.root.replace(trailingSlash, '');
      if (!fragment.indexOf(root)) {
        fragment = fragment.substr(root.length);
      }
    } else {
      fragment = this._getHash();
    }
  }

  return '/' + fragment.replace(routeStripper, '');
};

BrowserHistory.prototype._checkUrl = function(event) {
  let current = this._getFragment();
  if (current !== this.fragment) {
    if (event.type === "popstate") {
      this.history.replaceState(event.state, null);
    }
    this._loadUrl();
  }
};

export function configure(config) {
  config
    .singleton(RouteLoader, TemplatingRouteLoader)
    .singleton(Router, OnsRouter)
    .globalResources([
      './ons-back-button',
      './ons-input',
      './ons-navigator',
      './ons-range',
      './ons-select',
      './ons-switch',
      './ons-tab',
      './ons-tabbar',
      PLATFORM.moduleName('aurelia-templating-router/router-view'),
      PLATFORM.moduleName('aurelia-templating-router/route-href')
    ]);

  config.container.registerAlias(Router, OnsRouter);
}
<|endoftext|>


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

    wp.customize('trajano_bootstrap_css',
        function (value) {
            value.bind(function (to) {
                $('#bootstrap-css')[0].href = to;
            });
        });
    wp.customize('trajano_colorbox_css',
        function (value) {
            value.bind(function (to) {
                $('#colorbox-css')[0].href = to;
            });
        });
});
<commit_msg>Close color box when CSS has changed<commit_after>jQuery(function ($) {
    'use strict';

    wp.customize('trajano_bootstrap_css',
        function (value) {
            value.bind(function (to) {
                $('#bootstrap-css')[0].href = to;
            });
        });
    wp.customize('trajano_colorbox_css',
        function (value) {
            value.bind(function (to) {
                $('#colorbox-css')[0].href = to;
                $.colorbox.close();
            });
        });
});
<|endoftext|>


<commit_before>var jade = require('jade')
var fs = require('fs')

var testers = {}
var _testers = require('./testers.json')
Object.keys(_testers).forEach((esVersion) => {
  testers[esVersion] = {}
  Object.keys(_testers[esVersion]).forEach((path) =>
    $set(testers[esVersion], path, {path: path, code: _testers[esVersion][path]})
  )
})

var results = {
  unflagged: {},
  flagged: {}
}

var nodeVersions = fs.readFileSync('.versions').toString().trim().split('\n')
nodeVersions.unshift('nightly')
nodeVersions.forEach((version) => {
  results.unflagged[version] = tryRequire('./results/' + version + '.json')
  results.flagged[version] = tryRequire('./results/' + version + '--harmony.json')
})

function requiresFlag (nodeVersion, esVersion, path) {
  var flagged = $get(results.flagged, nodeVersion, esVersion)
  var unflagged = $get(results.unflagged, nodeVersion, esVersion)
  return flagged && unflagged && flagged[path] === true && unflagged[path] !== true
}
function result (type, nodeVersion, esVersion, path) {
  var result = $get(results, type, nodeVersion)
  if (!result) return
  result = $get(result, esVersion, path)

  var flaggd = type === 'flagged'
  var flagRequired = flaggd && requiresFlag(nodeVersion, esVersion, path)
  var title = result === true ? (flagRequired ? 'Yes, but requires --harmony flag' : 'Test passed') : typeof result === 'string' ? result : 'Test failed'
  result = result === true ? 'Yes' : typeof result === 'string' ? 'Error' : 'No'
  return `<div class="${result} ${type} ${flagRequired ? 'required' : ''}" title="${title}">${result}</div>`
}

var html = jade.renderFile('index.jade', {
  pretty: true,
  nodeVersions: nodeVersions,
  testers: testers,
  harmony: results.flagged,
  results: function (nodeVersion, esVersion, path) {
    return result('unflagged', nodeVersion, esVersion, path) + result('flagged', nodeVersion, esVersion, path)
  },
  requiresFlag: requiresFlag,
  tip: function (version) {
    return !results.flagged[version] ? '' : `v8: ${results.flagged[version]._v8}`
  },
  percent: function (nodeVersion, esVersion, unflagged) {
    var datasource = unflagged ? results.unflagged : results.flagged
    var data = $get(datasource, nodeVersion, esVersion)
    return data ? data._percent.toFixed(2).substr(-2) : ''
  }
})

fs.writeFileSync('index.html', html)

function $get (obj, path, ...more) {
  return more.length && obj[path] ? $get(obj[path], ...more) : obj[path]
}
function $set (target, path, value) {
  var parts = path.split('›')
  if (parts.length === 2) parts.splice(1, 0, '')

  var obj = target
  var last = parts.pop()

  parts.forEach(function (prop) {
    if (!obj[prop]) obj[prop] = {}
    obj = obj[prop]
  })

  obj[last] = value
}
function tryRequire (module) {
  try {
    return require(module)
  } catch (e) {
    console.log("couldn't find:", module)
  }
}
<commit_msg>Handle 100% 💯%!<commit_after>var jade = require('jade')
var fs = require('fs')

var testers = {}
var _testers = require('./testers.json')
Object.keys(_testers).forEach((esVersion) => {
  testers[esVersion] = {}
  Object.keys(_testers[esVersion]).forEach((path) =>
    $set(testers[esVersion], path, {path: path, code: _testers[esVersion][path]})
  )
})

var results = {
  unflagged: {},
  flagged: {}
}

var nodeVersions = fs.readFileSync('.versions').toString().trim().split('\n')
nodeVersions.unshift('nightly')
nodeVersions.forEach((version) => {
  results.unflagged[version] = tryRequire('./results/' + version + '.json')
  results.flagged[version] = tryRequire('./results/' + version + '--harmony.json')
})

function requiresFlag (nodeVersion, esVersion, path) {
  var flagged = $get(results.flagged, nodeVersion, esVersion)
  var unflagged = $get(results.unflagged, nodeVersion, esVersion)
  return flagged && unflagged && flagged[path] === true && unflagged[path] !== true
}
function result (type, nodeVersion, esVersion, path) {
  var result = $get(results, type, nodeVersion)
  if (!result) return
  result = $get(result, esVersion, path)

  var flaggd = type === 'flagged'
  var flagRequired = flaggd && requiresFlag(nodeVersion, esVersion, path)
  var title = result === true ? (flagRequired ? 'Yes, but requires --harmony flag' : 'Test passed') : typeof result === 'string' ? result : 'Test failed'
  result = result === true ? 'Yes' : typeof result === 'string' ? 'Error' : 'No'
  return `<div class="${result} ${type} ${flagRequired ? 'required' : ''}" title="${title}">${result}</div>`
}

var html = jade.renderFile('index.jade', {
  pretty: true,
  nodeVersions: nodeVersions,
  testers: testers,
  harmony: results.flagged,
  results: function (nodeVersion, esVersion, path) {
    return result('unflagged', nodeVersion, esVersion, path) + result('flagged', nodeVersion, esVersion, path)
  },
  requiresFlag: requiresFlag,
  tip: function (version) {
    return !results.flagged[version] ? '' : `v8: ${results.flagged[version]._v8}`
  },
  percent: function (nodeVersion, esVersion, unflagged) {
    var datasource = unflagged ? results.unflagged : results.flagged
    var data = $get(datasource, nodeVersion, esVersion)
    return data ? data._percent === 1 ? '100' : data._percent.toFixed(2).substr(-2) : ''
  }
})

fs.writeFileSync('index.html', html)

function $get (obj, path, ...more) {
  return more.length && obj[path] ? $get(obj[path], ...more) : obj[path]
}
function $set (target, path, value) {
  var parts = path.split('›')
  if (parts.length === 2) parts.splice(1, 0, '')

  var obj = target
  var last = parts.pop()

  parts.forEach(function (prop) {
    if (!obj[prop]) obj[prop] = {}
    obj = obj[prop]
  })

  obj[last] = value
}
function tryRequire (module) {
  try {
    return require(module)
  } catch (e) {
    console.log("couldn't find:", module)
  }
}
<|endoftext|>


<commit_before>var all_insults = "aldrabão,abécula,agarrado,analfabruto,atraso de vida,apanhado do clima,azeiteiro,alcoviteira,aselha,asno,anjinho,asqueroso,arruaceiro,artolas,|badameco,bandido,bruto,besta quadrada,barrigudo,brutamontes,borra-botas,bufo,boca de xarroco,boi,basbaque,biltre,bexigoso,bichona,bêbedo,bebedolas,batoque,banana,bardajona,badalhoca,bisbilhoteira,bandalho,bota de elástico,baldas,brochista,boneca de trapos,beata,bronco,bexigoso,betinho,bárbaro,|cunanas,camelo,chalado,camafeu,cona de sabão,cara de cu à paisana,coirão,choninhas,carroceiro,cabeçudo,cavalgadura,canalha,cretino,calhandreira,caga-tacos,cegueta,caixa de óculos,cornudo,coxo,candongueiro,careca,chupado das carochas,copinho de leite,cacique,calão,cabra,cabrão,cusca,coscuvilheira,cão,cabeça no ar,convencido,chanfrado,cagão,chato,cobardola,cavalona,chico-esperto,charlatão,caloteiro,cigano,comuna,carrancudo,corno,caceteiro,canalha,carapau de corrida,choné,cabeça de abóbora,|delambida,desenxabida,doido varrido,doidivanas,desmancha prazeres,desastrada,desengonçado,desaustinado,desbocado,|escanifobética,estafermo,embusteiro,estúpido,esqueleto vaidoso,engraxador,esgalgado,empecilho,estroina,escarumba,estouvada,estupor,espantalho,estapafúrdio,energúmeno,espalhafatoso,enjoado da trampa,|flausina,farsante,filho da puta,fufa,fersureira,falhado,foleiro,facínora,falsário,franganote,fanfarrão,fanático,fanchono,filho da mãe,|gatuno,gordalhufo,gabiru,galinha choca,galdéria,gabarola,gosma,gandulo,ganancioso,garganeira,|histérica,herege,|idiota,imbecil,incapaz,incompetente,inútil,|javardo,judeu,|lambisgóia,ladrão,lavajão,lambéconas,lambe-botas,lingrinhas,larápio,larilas,labrego,louco,lorpa,lunático,|morcão,malacueco,maluco,mariquinhas pé-de-salsa,meliante,mentiroso,malandro,malandreco,malandrim,marreco,maneta,mouco,mariconço,maricas,menino da mamã,mastronço,mostrengo,moina,meia-leca,medroso,monhé,molengão,mafioso,medricas,masoquista,mineteiro,maltrapilho,maria-vai-com-as-outras,miserável,magricela,mula,mal enjorcado,mimado,|nódoa,nulidade,nabo,nojento,não-tens-onde-cair-morto,nababo,|otário,olhos de carneiro mal morto,orelhas de abano,obcecado,ordinário,obstinado,|palerma,parvalhão,pateta,parvo,porcalhão,piroso,pirata,piolhoso,peida-gadoxa,pantomineiro,pote de banhas,pernas de alicate,pelintra,patego,panasca,paneleiro,putéfia,puta,panilas,pés de chumbo,patife,perliquiteques,palhaço,palhaçote,porco,punheteiro,preguiçoso,pacóvio,pobre de espírito,proxeneta,patinho feio,panhonhas,pintor,parasita,presunçoso,palonça,peneirenta,pobre diabo,|quadrilheira,queixinhas,quatro-olhos,|ranhoso,reles,rasca,rameira,rabeta,rafeiro,reaccionário,reaças,raquítico,|salafrário,safardana,sevandija,sacripanta,sacrista,sacana,sovina,somítico,safado,sabujo,saloio,soba,sebento,sapatona,sádico,serigaita,sarnento,snob,|tarado,trombalazanas,trapaceiro,trabeculoso,tísico,trombudo,trauliteiro,tinhoso,trique-lariques,tosco,totó,trombeiro,trouxa,tonto,traste,trinca-espinhas,troca-tintas,|unhas de fome,urso,|vaca gorda,vigarista,vândalo,vígaro,vigarista,velhaco,vendido,vagabundo,vira-casacas,vaidoso,|xé-xé,|zero à esquerda,zarolho,Zé-ninguém,|";

function write_meaning()
{
	full_name = get_text().toLowerCase();
	full_name = full_name.replace(/[áàãâ]+/g,'a');
	full_name = full_name.replace(/[éèẽê]+/g,'e');
	full_name = full_name.replace(/[íìĩî]+/g,'i');
	full_name = full_name.replace(/[óòõô]+/g,'o');
	full_name = full_name.replace(/[úùũû]+/g,'u');
	names = full_name.split(" ");

	var meaning_matrix = [];

	for(var i=0; i < names.length; i++){
		var name = names[i];

		meaning_matrix.push(get_meaning(name));
	}

	pretty_print(meaning_matrix);
}

function get_meaning(name)
{
	seed = serialize_name(name);
	seed_once(seed);

	var insults_res = [];
	for(var i = 0; i < name.length; i++){
		char = name[i];

		var insults_from_char = (get_insults(char));
		var splt = insults_from_char.split(",");

		r = random_int(0, splt.length-2);

		insults_res.push(splt[r]);
	}

	reset_seed();
	return insults_res;
}

function get_insults(char)
{
	split_by_char = all_insults.split("|");

	for(var i=0; i < split_by_char.length; i++){
		row = split_by_char[i];

		if(row[0] == char){
			return row;
		}
	}
}
<commit_msg>add suport for 'ç'<commit_after>var all_insults = "aldrabão,abécula,agarrado,analfabruto,atraso de vida,apanhado do clima,azeiteiro,alcoviteira,aselha,asno,anjinho,asqueroso,arruaceiro,artolas,|badameco,bandido,bruto,besta quadrada,barrigudo,brutamontes,borra-botas,bufo,boca de xarroco,boi,basbaque,biltre,bexigoso,bichona,bêbedo,bebedolas,batoque,banana,bardajona,badalhoca,bisbilhoteira,bandalho,bota de elástico,baldas,brochista,boneca de trapos,beata,bronco,bexigoso,betinho,bárbaro,|cunanas,camelo,chalado,camafeu,cona de sabão,cara de cu à paisana,coirão,choninhas,carroceiro,cabeçudo,cavalgadura,canalha,cretino,calhandreira,caga-tacos,cegueta,caixa de óculos,cornudo,coxo,candongueiro,careca,chupado das carochas,copinho de leite,cacique,calão,cabra,cabrão,cusca,coscuvilheira,cão,cabeça no ar,convencido,chanfrado,cagão,chato,cobardola,cavalona,chico-esperto,charlatão,caloteiro,cigano,comuna,carrancudo,corno,caceteiro,canalha,carapau de corrida,choné,cabeça de abóbora,|delambida,desenxabida,doido varrido,doidivanas,desmancha prazeres,desastrada,desengonçado,desaustinado,desbocado,|escanifobética,estafermo,embusteiro,estúpido,esqueleto vaidoso,engraxador,esgalgado,empecilho,estroina,escarumba,estouvada,estupor,espantalho,estapafúrdio,energúmeno,espalhafatoso,enjoado da trampa,|flausina,farsante,filho da puta,fufa,fersureira,falhado,foleiro,facínora,falsário,franganote,fanfarrão,fanático,fanchono,filho da mãe,|gatuno,gordalhufo,gabiru,galinha choca,galdéria,gabarola,gosma,gandulo,ganancioso,garganeira,|histérica,herege,|idiota,imbecil,incapaz,incompetente,inútil,|javardo,judeu,|lambisgóia,ladrão,lavajão,lambéconas,lambe-botas,lingrinhas,larápio,larilas,labrego,louco,lorpa,lunático,|morcão,malacueco,maluco,mariquinhas pé-de-salsa,meliante,mentiroso,malandro,malandreco,malandrim,marreco,maneta,mouco,mariconço,maricas,menino da mamã,mastronço,mostrengo,moina,meia-leca,medroso,monhé,molengão,mafioso,medricas,masoquista,mineteiro,maltrapilho,maria-vai-com-as-outras,miserável,magricela,mula,mal enjorcado,mimado,|nódoa,nulidade,nabo,nojento,não-tens-onde-cair-morto,nababo,|otário,olhos de carneiro mal morto,orelhas de abano,obcecado,ordinário,obstinado,|palerma,parvalhão,pateta,parvo,porcalhão,piroso,pirata,piolhoso,peida-gadoxa,pantomineiro,pote de banhas,pernas de alicate,pelintra,patego,panasca,paneleiro,putéfia,puta,panilas,pés de chumbo,patife,perliquiteques,palhaço,palhaçote,porco,punheteiro,preguiçoso,pacóvio,pobre de espírito,proxeneta,patinho feio,panhonhas,pintor,parasita,presunçoso,palonça,peneirenta,pobre diabo,|quadrilheira,queixinhas,quatro-olhos,|ranhoso,reles,rasca,rameira,rabeta,rafeiro,reaccionário,reaças,raquítico,|salafrário,safardana,sevandija,sacripanta,sacrista,sacana,sovina,somítico,safado,sabujo,saloio,soba,sebento,sapatona,sádico,serigaita,sarnento,snob,|tarado,trombalazanas,trapaceiro,trabeculoso,tísico,trombudo,trauliteiro,tinhoso,trique-lariques,tosco,totó,trombeiro,trouxa,tonto,traste,trinca-espinhas,troca-tintas,|unhas de fome,urso,|vaca gorda,vigarista,vândalo,vígaro,vigarista,velhaco,vendido,vagabundo,vira-casacas,vaidoso,|xé-xé,|zero à esquerda,zarolho,Zé-ninguém,|";

function write_meaning()
{
	var full_name = get_text().toLowerCase();
	full_name = full_name.replace(/[áàãâ]+/g,'a');
	full_name = full_name.replace(/[éèẽê]+/g,'e');
	full_name = full_name.replace(/[íìĩî]+/g,'i');
	full_name = full_name.replace(/[óòõô]+/g,'o');
	full_name = full_name.replace(/[úùũû]+/g,'u');
	full_name = full_name.replace(/ç/, 'c')
	var names = full_name.split(" ");

	var meaning_matrix = [];

	for(var i=0; i < names.length; i++){
		var name = names[i];

		meaning_matrix.push(get_meaning(name));
	}

	pretty_print(meaning_matrix);
}

function get_meaning(name)
{
	seed = serialize_name(name);
	seed_once(seed);

	var insults_res = [];
	for(var i = 0; i < name.length; i++){
		char = name[i];

		var insults_from_char = (get_insults(char));
		var splt = insults_from_char.split(",");

		r = random_int(0, splt.length-2);

		insults_res.push(splt[r]);
	}

	reset_seed();
	return insults_res;
}

function get_insults(char)
{
	split_by_char = all_insults.split("|");

	for(var i=0; i < split_by_char.length; i++){
		row = split_by_char[i];

		if(row[0] == char){
			return row;
		}
	}
}
<|endoftext|>


<commit_before>define([
    'require',
    'module',

    '{lodash}/lodash',
    '{angular}/angular',

    '[text]!{w20-business-theme}/templates/topbar.html',
    '[text]!{w20-business-theme}/templates/sidebar.html',

    '{angular-sanitize}/angular-sanitize',
    '{w20-ui}/modules/ui',
    '{w20-ui}/modules/notifications',
    '{w20-core}/modules/culture',
    '{w20-core}/modules/utils'
], function(require, module, _, angular, topbarTemplate, sidebarTemplate) {
    'use strict';

    var w20BusinessTheme = angular.module('w20BusinessTheme', ['w20CoreCulture', 'w20CoreUtils', 'w20UI', 'w20UINotifications', 'ngSanitize']),
        _config = module && module.config() || {},
        showTopbar = true,
        showSidebar = true;

    w20BusinessTheme.directive('w20Topbar', ['ApplicationService', 'EventService', 'EnvironmentService', 'DisplayService', 'MenuService',
        function (applicationService, eventService, environmentService, displayService, menuService) {
        return {
            template: topbarTemplate,
            replace: true,
            restrict: 'A',
            scope: true,
            link: function (scope, iElement, iAttrs) {
                scope.navActions = menuService.getActions;
                scope.navAction = menuService.getAction;
                scope.envtype = environmentService.environment;
                scope.title = iAttrs.title || '\'' + applicationService.applicationId + '\'';
                scope.description = iAttrs.subtitle || '';
                scope.logoUrl = _config.logoUrl;
                scope.brandFixedWidth = true;
                if (_config.brand) {
                    scope.brandFixedWidth = _config.brand.fixedWidth === false ? _config.brand.fixedWidth : true;
                    scope.brandBackgroundColor = _config.brand.backgroundColor ?  _config.brand.backgroundColor : undefined;
                    scope.brandTextColor = _config.brand.textColor ?  _config.brand.textColor : undefined;
                }

                scope.showTopbar = function () {
                    return showTopbar;
                };

                scope.toggleSidebar = function() {
                    eventService.emit('SidebarToggleEvent');
                };

                displayService.registerContentShiftCallback(function () {
                    return [showTopbar ? 50 : 0, 0, 0, 0];
                });
            }
        };
    }]);

    w20BusinessTheme.directive('w20Sidebar', ['EventService', 'DisplayService', 'NavigationService', 'MenuService', '$location',
        function (eventService, displayService, navigationService, menuService, $location) {
            return {
                template: sidebarTemplate,
                replace: true,
                restrict: 'A',
                scope: true,
                link: function (scope, element) {

                    if (_config.sidebar) {
                        scope.sideBarWidth = _config.sidebar.width ? _config.sidebar.width : undefined;
                    }

                    scope.menuSections = menuService.getSections;
                    scope.menuActiveSectionName = scope.menuSections()[0];

                    scope.showSidebar = function () {
                        return showSidebar;
                    };

                    scope.menuSection = function (name) {
                        return name ? menuService.getSection(name) : null;
                    };

                    scope.goTo = function(path) {
                        $location.path(path);
                    };

                    eventService.on('SidebarToggleEvent', function() {
                        showSidebar = !showSidebar;
                        displayService.computeContentShift();
                    });

                    displayService.registerContentShiftCallback(function () {
                        return [10, 0, 0, showSidebar ? (scope.sideBarWidth || 270) : 0];
                    });
                }
            };
    }]);

    w20BusinessTheme.filter('routeFilter', ['CultureService', 'SecurityExpressionService', function(cultureService, securityExpressionService) {
        function isRouteVisible(route) {
            return !route.hidden && (typeof route.security === 'undefined' || securityExpressionService.evaluate(route.security));
        }
        return function(routes, expected) {
            if (!expected) {
                return;
            }
            return _.filter(routes, function(route) {
                if(isRouteVisible(route) && cultureService.displayName(route).toLowerCase().indexOf(expected.toLowerCase()) !== -1) {
                    return route;
                }
            });
        };
    }]);

    w20BusinessTheme.controller('W20btViewsController', ['$scope', 'NavigationService', 'CultureService', '$route', '$location',
        function ($scope, navigationService, cultureService, $route, $location) {

            var openedCategories = navigationService.expandedRouteCategories();

            function recursiveOpen(tree) {
                openedCategories.push(tree.categoryName);
                for (var key in tree) {
                    if (tree.hasOwnProperty(key)) {
                        var subTree = tree[key];
                        if (subTree instanceof Array) {
                            recursiveOpen(subTree);
                        }
                    }
                }
            }

            $scope.routes = $route.routes;
            $scope.filteredRoutes = [];
            $scope.menuTree = navigationService.routeTree;
            $scope.subMenuTree = navigationService.computeSubTree;
            $scope.topLevelCategories = navigationService.topLevelRouteCategories;
            $scope.topLevelRoutes = navigationService.topLevelRoutes;
            $scope.routesFromCategory = navigationService.routesFromCategory;
            $scope.displayName = cultureService.displayName;

            if (_config.brand) {
                $scope.brandColor =  _config.brand.backgroundColor ? _config.brand.backgroundColor : undefined;
            }

            $scope.activeRoutePath = function() {
               return $location.path();
            };

            $scope.localizeCategory = function (categoryName) {
                var lastPartIndex = categoryName.lastIndexOf('.');
                if (lastPartIndex !== -1) {
                    return cultureService.localize('application.viewcategory.' + categoryName, undefined, null) || cultureService.localize('application.viewcategory.' + categoryName.substring(lastPartIndex + 1));
                } else {
                    return cultureService.localize('application.viewcategory.' + categoryName);
                }
            };

            $scope.toggleTree = function (tree) {
                if ($scope.isOpened(tree.categoryName)) {
                    openedCategories.splice(openedCategories.indexOf(tree.categoryName), 1);
                } else {
                    openedCategories.push(tree.categoryName);
                }
            };

            $scope.isOpened = function (categoryName) {
                return _.contains(openedCategories, categoryName);
            };

            $scope.routeSortKey = function (route) {
                return route.sortKey || route.path;
            };
        }]);

    w20BusinessTheme.run(['$rootScope', 'EventService', 'DisplayService', 'MenuService',
        function ($rootScope, eventService, displayService, menuService) {

            $rootScope.$on('$routeChangeSuccess', function (event, routeInfo) {

                if (routeInfo && routeInfo.$$route) {
                    switch (routeInfo.$$route.navigation) {
                        case 'none':
                            showSidebar = false;
                            showTopbar = false;
                            break;
                        case 'sidebar':
                            showSidebar = true;
                            showTopbar = false;
                            break;
                        case 'topbar':
                            showSidebar = false;
                            showTopbar = true;
                            break;
                        case 'full':
                        /* falls through */
                        default:
                            showSidebar = true;
                            showTopbar = true;
                            break;
                    }

                    displayService.computeContentShift();
                }
            });

            if (!_config.hideSecurity) {
                if (!_config.profileChooser) {
                    menuService.addAction('login', 'w20-login', {
                        sortKey: 100
                    });
                } else {
                    menuService.addAction('profile', 'w20-profile', {
                        sortKey: 100
                    });
                }
            }

            if (!_config.hideConnectivity) {
                menuService.addAction('connectivity', 'w20-connectivity', {
                    sortKey: 200
                });
            }

            if (!_config.hideCulture) {
                menuService.addAction('culture', 'w20-culture', {
                sortKey: 300
            });
            }

            _.each(_config.links, function (link, idx) {
                if (idx < 10) {
                    menuService.addAction('link-' + idx, 'w20-link', _.extend(link, {
                        sortKey: 400 + idx
                    }));
                }
            });

            if (!_config.hideSecurity && !_config.profileChooser) {
                menuService.addAction('logout', 'w20-logout', {
                    sortKey: 1000
                });
            }

            menuService.addSection('views', 'w20-views', {
                templateUrl: '{w20-business-theme}/templates/sidebar-views.html'
            });

            eventService.on('w20.security.authenticated', function () {
                displayService.computeContentShift();
            });

            eventService.on('w20.security.deauthenticated', function () {
                displayService.computeContentShift();
            });

            eventService.on('w20.security.refreshed', function () {
                displayService.computeContentShift();
            });
        }]);

    return {
        angularModules: ['w20BusinessTheme'],
        lifecycle: {
            pre: function (modules, fragments, callback) {
                angular.element('body').addClass('w20-top-shift-padding w20-right-shift-padding w20-bottom-shift-padding w20-left-shift-padding');
                callback(module);
            }
        }
    };
});<commit_msg>Added persistent state for sidebar<commit_after>define([
    'require',
    'module',

    '{lodash}/lodash',
    '{angular}/angular',

    '[text]!{w20-business-theme}/templates/topbar.html',
    '[text]!{w20-business-theme}/templates/sidebar.html',

    '{angular-sanitize}/angular-sanitize',
    '{w20-ui}/modules/ui',
    '{w20-ui}/modules/notifications',
    '{w20-core}/modules/culture',
    '{w20-core}/modules/utils'
], function(require, module, _, angular, topbarTemplate, sidebarTemplate) {
    'use strict';

    var w20BusinessTheme = angular.module('w20BusinessTheme', ['w20CoreCulture', 'w20CoreUtils', 'w20UI', 'w20UINotifications', 'ngSanitize']),
        _config = module && module.config() || {},
        showTopbar = true,
        showSidebar = true;

    w20BusinessTheme.directive('w20Topbar', ['ApplicationService', 'EventService', 'EnvironmentService', 'DisplayService', 'MenuService',
        function (applicationService, eventService, environmentService, displayService, menuService) {
        return {
            template: topbarTemplate,
            replace: true,
            restrict: 'A',
            scope: true,
            link: function (scope, iElement, iAttrs) {
                scope.navActions = menuService.getActions;
                scope.navAction = menuService.getAction;
                scope.envtype = environmentService.environment;
                scope.title = iAttrs.title || '\'' + applicationService.applicationId + '\'';
                scope.description = iAttrs.subtitle || '';
                scope.logoUrl = _config.logoUrl;
                scope.brandFixedWidth = true;
                if (_config.brand) {
                    scope.brandFixedWidth = _config.brand.fixedWidth === false ? _config.brand.fixedWidth : true;
                    scope.brandBackgroundColor = _config.brand.backgroundColor ?  _config.brand.backgroundColor : undefined;
                    scope.brandTextColor = _config.brand.textColor ?  _config.brand.textColor : undefined;
                }

                scope.showTopbar = function () {
                    return showTopbar;
                };

                scope.toggleSidebar = function() {
                    eventService.emit('SidebarToggleEvent');
                };

                displayService.registerContentShiftCallback(function () {
                    return [showTopbar ? 50 : 0, 0, 0, 0];
                });
            }
        };
    }]);

    w20BusinessTheme.directive('w20Sidebar', ['EventService', 'DisplayService', 'NavigationService', 'MenuService', '$location',
        function (eventService, displayService, navigationService, menuService, $location) {
            return {
                template: sidebarTemplate,
                replace: true,
                restrict: 'A',
                scope: true,
                link: function (scope, element) {

                    if (_config.sidebar) {
                        scope.sideBarWidth = _config.sidebar.width ? _config.sidebar.width : undefined;
                    }

                    scope.menuSections = menuService.getSections;
                    scope.menuActiveSectionName = scope.menuSections()[0];

                    scope.showSidebar = function () {
                        return showSidebar;
                    };

                    scope.menuSection = function (name) {
                        return name ? menuService.getSection(name) : null;
                    };

                    scope.goTo = function(path) {
                        $location.path(path);
                    };

                    eventService.on('SidebarToggleEvent', function() {
                        showSidebar = !showSidebar;
                        displayService.computeContentShift();
                    });

                    displayService.registerContentShiftCallback(function () {
                        return [10, 0, 0, showSidebar ? (scope.sideBarWidth || 270) : 0];
                    });
                }
            };
    }]);

    w20BusinessTheme.filter('routeFilter', ['CultureService', 'SecurityExpressionService', function(cultureService, securityExpressionService) {
        function isRouteVisible(route) {
            return !route.hidden && (typeof route.security === 'undefined' || securityExpressionService.evaluate(route.security));
        }
        return function(routes, expected) {
            if (!expected) {
                return;
            }
            return _.filter(routes, function(route) {
                if(isRouteVisible(route) && cultureService.displayName(route).toLowerCase().indexOf(expected.toLowerCase()) !== -1) {
                    return route;
                }
            });
        };
    }]);

    w20BusinessTheme.controller('W20btViewsController', ['$scope', 'NavigationService', 'CultureService', '$route', '$location',
        function ($scope, navigationService, cultureService, $route, $location) {

            var openedCategories = navigationService.expandedRouteCategories();

            function recursiveOpen(tree) {
                openedCategories.push(tree.categoryName);
                for (var key in tree) {
                    if (tree.hasOwnProperty(key)) {
                        var subTree = tree[key];
                        if (subTree instanceof Array) {
                            recursiveOpen(subTree);
                        }
                    }
                }
            }

            $scope.routes = $route.routes;
            $scope.filteredRoutes = [];
            $scope.menuTree = navigationService.routeTree;
            $scope.subMenuTree = navigationService.computeSubTree;
            $scope.topLevelCategories = navigationService.topLevelRouteCategories;
            $scope.topLevelRoutes = navigationService.topLevelRoutes;
            $scope.routesFromCategory = navigationService.routesFromCategory;
            $scope.displayName = cultureService.displayName;

            if (_config.brand) {
                $scope.brandColor =  _config.brand.backgroundColor ? _config.brand.backgroundColor : undefined;
            }

            $scope.activeRoutePath = function() {
               return $location.path();
            };

            $scope.localizeCategory = function (categoryName) {
                var lastPartIndex = categoryName.lastIndexOf('.');
                if (lastPartIndex !== -1) {
                    return cultureService.localize('application.viewcategory.' + categoryName, undefined, null) || cultureService.localize('application.viewcategory.' + categoryName.substring(lastPartIndex + 1));
                } else {
                    return cultureService.localize('application.viewcategory.' + categoryName);
                }
            };

            $scope.toggleTree = function (tree) {
                if ($scope.isOpened(tree.categoryName)) {
                    openedCategories.splice(openedCategories.indexOf(tree.categoryName), 1);
                } else {
                    openedCategories.push(tree.categoryName);
                }
            };

            $scope.isOpened = function (categoryName) {
                return _.contains(openedCategories, categoryName);
            };

            $scope.routeSortKey = function (route) {
                return route.sortKey || route.path;
            };
        }]);

    w20BusinessTheme.run(['$rootScope', 'EventService', 'DisplayService', 'MenuService',
        function ($rootScope, eventService, displayService, menuService) {

            $rootScope.$on('$routeChangeSuccess', function (event, routeInfo) {

                if (routeInfo && routeInfo.$$route) {
                    switch (routeInfo.$$route.navigation) {
                        case 'none':
                            showSidebar = false;
                            showTopbar = false;
                            break;
                        case 'sidebar':
                            showSidebar = true;
                            showTopbar = false;
                            break;
                        case 'topbar':
                            showSidebar = false;
                            showTopbar = true;
                            break;
                        case 'full':
                        /* falls through */
                        default:
                            break;
                    }

                    displayService.computeContentShift();
                }
            });

            if (!_config.hideSecurity) {
                if (!_config.profileChooser) {
                    menuService.addAction('login', 'w20-login', {
                        sortKey: 100
                    });
                } else {
                    menuService.addAction('profile', 'w20-profile', {
                        sortKey: 100
                    });
                }
            }

            if (!_config.hideConnectivity) {
                menuService.addAction('connectivity', 'w20-connectivity', {
                    sortKey: 200
                });
            }

            if (!_config.hideCulture) {
                menuService.addAction('culture', 'w20-culture', {
                sortKey: 300
            });
            }

            _.each(_config.links, function (link, idx) {
                if (idx < 10) {
                    menuService.addAction('link-' + idx, 'w20-link', _.extend(link, {
                        sortKey: 400 + idx
                    }));
                }
            });

            if (!_config.hideSecurity && !_config.profileChooser) {
                menuService.addAction('logout', 'w20-logout', {
                    sortKey: 1000
                });
            }

            menuService.addSection('views', 'w20-views', {
                templateUrl: '{w20-business-theme}/templates/sidebar-views.html'
            });

            eventService.on('w20.security.authenticated', function () {
                displayService.computeContentShift();
            });

            eventService.on('w20.security.deauthenticated', function () {
                displayService.computeContentShift();
            });

            eventService.on('w20.security.refreshed', function () {
                displayService.computeContentShift();
            });
        }]);

    return {
        angularModules: ['w20BusinessTheme'],
        lifecycle: {
            pre: function (modules, fragments, callback) {
                angular.element('body').addClass('w20-top-shift-padding w20-right-shift-padding w20-bottom-shift-padding w20-left-shift-padding');
                callback(module);
            }
        }
    };
});<|endoftext|>


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

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

function Err(msg, err){
  var err_str = 'build error\n'
    + (msg ? msg + '\n' : '')
    + (err ? err.message + '\n' : '');

  throw new Error(err_str);
}

/**
 * Lets do this synchronous
 */

function getCppDirs(cb){

  var lib_dir = __dirname + '/lib';
  fs.readdir(lib_dir, function (err, libs){
    if(err) return cb('Could not read ' + lib_dir, err);
        var cpp_dirs = [];

    var lib_count = libs.length,
        lib_i = 0;

    libs.forEach(function (dir){
      var module_dir = lib_dir + '/' + dir

      fs.readdir(module_dir, function (err, dirs){
        lib_i++;

        if(err) return cb('Could not read ', err);

        dirs.forEach(function (dir, i){
          if(dir == 'cpp')
            cpp_dirs.push(module_dir + '/' + dir);
        });

        if(lib_i == lib_count)
          cb(null, cpp_dirs);
      });
    });
  });

}

getCppDirs(function (err, dirs){
  if(err) return Err(err);

  (function build(i){
    if(i == dirs.length) return;

    var commands = 'cd ' + dirs[i] + ' && npm install';

    console.log(commands);

    exec(commands, function (err, stdout, stderr){
      if(err)
        console.log('--- exec error ' + i + ' ---\n'
          + err + '--- end exec error ---');

      console.log('--- stdout ' + i + ' ---\n'
        + stdout + '--- end stdout ' + i + ' ---');
      console.log('--- stderr ' + i + ' ---\n'
        + stderr + '--- end stderr ' + i + ' ---');

      build(i+=1);
    });

  }(0));

});

/*
function build(dir){

  var commands = 'cd ' + dir + ' && npm install nan && npm install bindings'
      + ' && node-gyp configure && node-gyp build';

  console.log(commands);

  exec(commands, function (err, stdout, stderr) {
    if(err)
      console.log('--- exec error ---\n' + err + '--- end exec error ---');

    console.log('--- stdout ---\n' + stdout + '--- end stdout ---');
    console.log('--- stderr ---\n' + stderr + '--- end stderr ---');
  });
}

var lib_dir = __dirname + '/lib';
fs.readdir(lib_dir, function (err, dirs){
  if(err) return Err('Could not read ' + lib_dir, err);

  dirs.forEach(function (dir){
    var module_dir = lib_dir + '/' + dir

    fs.readdir(module_dir, function (err, dirs){
      if(err) return Err('Could not read ', err);

      dirs.forEach(function (dir){
        if(dir == 'cpp')
          build(module_dir + '/' + dir);
      });
    });
  });
});
*/<commit_msg>stderr logging now finishes with 2 newlines<commit_after>var fs = require('fs');

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

function Err(msg, err){
  var err_str = 'build error\n'
    + (msg ? msg + '\n' : '')
    + (err ? err.message + '\n' : '');

  throw new Error(err_str);
}

/**
 * Lets do this synchronous
 */

function getCppDirs(cb){

  var lib_dir = __dirname + '/lib';
  fs.readdir(lib_dir, function (err, libs){
    if(err) return cb('Could not read ' + lib_dir, err);
        var cpp_dirs = [];

    var lib_count = libs.length,
        lib_i = 0;

    libs.forEach(function (dir){
      var module_dir = lib_dir + '/' + dir

      fs.readdir(module_dir, function (err, dirs){
        lib_i++;

        if(err) return cb('Could not read ', err);

        dirs.forEach(function (dir, i){
          if(dir == 'cpp')
            cpp_dirs.push(module_dir + '/' + dir);
        });

        if(lib_i == lib_count)
          cb(null, cpp_dirs);
      });
    });
  });

}

getCppDirs(function (err, dirs){
  if(err) return Err(err);

  (function build(i){
    if(i == dirs.length) return;

    var commands = 'cd ' + dirs[i] + ' && npm install';

    console.log(commands);

    exec(commands, function (err, stdout, stderr){
      if(err)
        console.log('--- exec error ' + i + ' ---\n'
          + err + '--- end exec error ---');

      console.log('--- stdout ' + i + ' ---\n'
        + stdout + '--- end stdout ' + i + ' ---');
      console.log('--- stderr ' + i + ' ---\n'
        + stderr + '--- end stderr ' + i + ' ---\n\n');

      build(i+=1);
    });

  }(0));

});

/*
function build(dir){

  var commands = 'cd ' + dir + ' && npm install nan && npm install bindings'
      + ' && node-gyp configure && node-gyp build';

  console.log(commands);

  exec(commands, function (err, stdout, stderr) {
    if(err)
      console.log('--- exec error ---\n' + err + '--- end exec error ---');

    console.log('--- stdout ---\n' + stdout + '--- end stdout ---');
    console.log('--- stderr ---\n' + stderr + '--- end stderr ---');
  });
}

var lib_dir = __dirname + '/lib';
fs.readdir(lib_dir, function (err, dirs){
  if(err) return Err('Could not read ' + lib_dir, err);

  dirs.forEach(function (dir){
    var module_dir = lib_dir + '/' + dir

    fs.readdir(module_dir, function (err, dirs){
      if(err) return Err('Could not read ', err);

      dirs.forEach(function (dir){
        if(dir == 'cpp')
          build(module_dir + '/' + dir);
      });
    });
  });
});
*/<|endoftext|>


<commit_before>// Copyright 2016, University of Colorado Boulder

/**
 *
 * @author Sam Reid (PhET Interactive Simulations)
 * @author Andrew Adare
 */
define( function( require ) {
  'use strict';

  // modules
  var assertInstanceOf = require( 'PHET_IO/assertions/assertInstanceOf' );
  var phetio = require( 'PHET_IO/phetio' );
  var phetioInherit = require( 'PHET_IO/phetioInherit' );
  var phetioNamespace = require( 'PHET_IO/phetioNamespace' );
  var SimIFrameAPI = require( 'PHET_IO/SimIFrameAPI' );
  var TFunctionWrapper = require( 'PHET_IO/types/TFunctionWrapper' );
  var TObject = require( 'PHET_IO/types/TObject' );
  var toEventOnStatic = require( 'PHET_IO/events/toEventOnStatic' );
  var TString = require( 'PHET_IO/types/TString' );
  var TVoid = require( 'PHET_IO/types/TVoid' );
  var TBarrierRectangle = require( 'PHET_IO/types/scenery/nodes/TBarrierRectangle' );
  var TBoolean = require( 'PHET_IO/types/TBoolean' );
  var TNumber = require( 'PHET_IO/types/TNumber' );
  var TProperty = require( 'PHET_IO/types/axon/TProperty' );

  var TSim = phetioInherit( TObject, 'TSim', function( sim, phetioID ) {
    TObject.call( this, sim, phetioID );
    assertInstanceOf( sim, phet.joist.Sim );

    toEventOnStatic( sim, 'SimConstructor', 'model', phetioID, TSim, 'simStarted', function( value ) {
      return {
        sessionID: value.sessionID,
        simName: value.simName,
        simVersion: value.simVersion,
        url: value.url,
        userAgent: window.navigator.userAgent,
        randomSeed: value.randomSeed,
        provider: 'PhET Interactive Simulations, University of Colorado Boulder' // See #137
      };
    } );

    // Store a reference to the sim so that subsequent calls will be simpler.  PhET-iO only works with a single sim.
    phetio.sim = sim;
    SimIFrameAPI.triggerSimInitialized();
    sim.onStatic( 'simulationStarted', function() {
      phetio.simulationStarted();
    } );
  }, {
    disableRequestAnimationFrame: {
      returnType: TVoid,
      parameterTypes: [],
      implementation: function() {
        this.instance.disableRequestAnimationFrame();
      },
      documentation: 'Prevents the simulation from animating/updating'
    },
    addEventListener: {
      returnType: TVoid,
      parameterTypes: [ TString, TFunctionWrapper( TVoid, [ TString, TFunctionWrapper( TVoid, [] ) ] ) ],
      implementation: function( eventName, listener ) {
        this.instance.onStatic( eventName, listener );
      },
      documentation: 'Add an event listener to the sim instance'
    },
    getScreenshotDataURL: {
      returnType: TString,
      parameterTypes: [],
      implementation: function() {
        return window.phet.joist.ScreenshotGenerator.generateScreenshot( this.instance );
      },
      documentation: 'Gets a base64 representation of a screenshot of the simulation as a data url'
    }
  }, {
    api: {
      activeProperty: TProperty( TBoolean ),
      barrierRectangle: TBarrierRectangle,
      screenIndexProperty: TProperty( TNumber( 'unitless' ) ),
      showHomeScreenProperty: TProperty( TBoolean )
    },
    documentation: 'The type for the simulation instance',
    events: [
      'simStarted',

      // The entire state for the sim, for the first frame and for keyframes
      'state',

      // not necessarily a stateChanged because the delta might be empty
      'stateDelta',

      // For addEventListener, not emitted at every frame into the data stream
      'frameCompleted',

      'stepSimulation',

      'inputEvent'
    ]
  } );

  phetioNamespace.register( 'TSim', TSim );

  return TSim;
} );

<commit_msg>Send messages from phetio instead of sim, see #44<commit_after>// Copyright 2016, University of Colorado Boulder

/**
 *
 * @author Sam Reid (PhET Interactive Simulations)
 * @author Andrew Adare
 */
define( function( require ) {
  'use strict';

  // modules
  var assertInstanceOf = require( 'PHET_IO/assertions/assertInstanceOf' );
  var phetio = require( 'PHET_IO/phetio' );
  var phetioInherit = require( 'PHET_IO/phetioInherit' );
  var phetioNamespace = require( 'PHET_IO/phetioNamespace' );
  var SimIFrameAPI = require( 'PHET_IO/SimIFrameAPI' );
  var TFunctionWrapper = require( 'PHET_IO/types/TFunctionWrapper' );
  var TObject = require( 'PHET_IO/types/TObject' );
  var toEventOnStatic = require( 'PHET_IO/events/toEventOnStatic' );
  var TString = require( 'PHET_IO/types/TString' );
  var TVoid = require( 'PHET_IO/types/TVoid' );
  var TBarrierRectangle = require( 'PHET_IO/types/scenery/nodes/TBarrierRectangle' );
  var TBoolean = require( 'PHET_IO/types/TBoolean' );
  var TNumber = require( 'PHET_IO/types/TNumber' );
  var TProperty = require( 'PHET_IO/types/axon/TProperty' );

  var TSim = phetioInherit( TObject, 'TSim', function( sim, phetioID ) {
    TObject.call( this, sim, phetioID );
    assertInstanceOf( sim, phet.joist.Sim );

    toEventOnStatic( sim, 'SimConstructor', 'model', phetioID, TSim, 'simStarted', function( value ) {
      return {
        sessionID: value.sessionID,
        simName: value.simName,
        simVersion: value.simVersion,
        url: value.url,
        userAgent: window.navigator.userAgent,
        randomSeed: value.randomSeed,
        provider: 'PhET Interactive Simulations, University of Colorado Boulder' // See #137
      };
    } );

    // Store a reference to the sim so that subsequent calls will be simpler.  PhET-iO only works with a single sim.
    phetio.sim = sim;
    SimIFrameAPI.triggerSimInitialized();
    sim.onStatic( 'simulationStarted', function() {
      phetio.simulationStarted();
    } );
  }, {
    disableRequestAnimationFrame: {
      returnType: TVoid,
      parameterTypes: [],
      implementation: function() {
        this.instance.disableRequestAnimationFrame();
      },
      documentation: 'Prevents the simulation from animating/updating'
    },
    addEventListener: {
      returnType: TVoid,
      parameterTypes: [ TString, TFunctionWrapper( TVoid, [ TString, TFunctionWrapper( TVoid, [] ) ] ) ],
      implementation: function( eventName, listener ) {
        this.instance.onStatic( eventName, listener );
      },
      documentation: 'Add an event listener to the sim instance'
    },
    getScreenshotDataURL: {
      returnType: TString,
      parameterTypes: [],
      implementation: function() {
        return window.phet.joist.ScreenshotGenerator.generateScreenshot( this.instance );
      },
      documentation: 'Gets a base64 representation of a screenshot of the simulation as a data url'
    }
  }, {
    api: {
      activeProperty: TProperty( TBoolean ),
      barrierRectangle: TBarrierRectangle,
      screenIndexProperty: TProperty( TNumber( 'unitless' ) ),
      showHomeScreenProperty: TProperty( TBoolean )
    },
    documentation: 'The type for the simulation instance',
    events: [
      'simStarted'
    ]
  } );

  phetioNamespace.register( 'TSim', TSim );

  return TSim;
} );

<|endoftext|>


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

const fs = require('fs')
const _ = require('lodash')

const structure = {
  features: {
    support: {
      driver: 'my driver',
      env: 'my env',
      hook: 'my hook',
      world: 'my world'
    },
    step_definitions: {
      example_steps: ''
    },
    example_feature: ''
  }
}

function generate (dir, node) {
  const keys = Object.keys(node)
  console.log(keys)
  keys.forEach((id) => {
    console.log(`Processing: ${id}`)
    if (_.isString(node[id])) {
      const filename = `${dir}/${id}.js`
      console.log(`saving ${filename}`)
      fs.writeFileSync(filename, node[id])
    } else {
      dir += `/${id}`
      if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir)
      }
      generate(dir, node[id])
    }
  })
}

generate(process.cwd(), structure)
<commit_msg>auto gen<commit_after>#!/usr/bin/env node

const fs = require('fs')
const _ = require('lodash')

const structure = {
  features: {
    support: {
      driver: 'my driver',
      env: 'my env',
      hook: 'my hook',
      world: 'my world'
    },
    step_definitions: {
      example_steps: ''
    },
    example_feature: ''
  }
}

function generate (dir, node) {
  const keys = Object.keys(node)
  keys.forEach((id) => {
    console.log(`Processing: ${id}`)
    if (_.isString(node[id])) {
      const filename = `${dir}/${id}.js`
      console.log(`saving ${filename}`)
      fs.writeFileSync(filename, node[id])
    } else {
      dir += `/${id}`
      if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir)
      }
      generate(dir, node[id])
    }
  })
}

generate(process.cwd(), structure)
<|endoftext|>


<commit_before>var fs = require('fs'),
    exec = require('child_process').exec;

var buildArgs = process.argv.slice(2),
    buildArgsAsObject = { },
    rootPath = process.cwd(),

buildArgs.forEach(function(arg) {
  var key = arg.split('=')[0],
      value = arg.split('=')[1];

  buildArgsAsObject[key] = value;
});

var modulesToInclude = buildArgsAsObject.modules ? buildArgsAsObject.modules.split(',') : [ ];
var modulesToExclude = buildArgsAsObject.exclude ? buildArgsAsObject.exclude.split(',') : [ ];

var distributionPath = buildArgsAsObject.dest || 'dist/';
var minifier = buildArgsAsObject.minifier || 'uglifyjs';
var mininfierCmd;

var noStrict = 'no-strict' in buildArgsAsObject;
var noSVGExport = 'no-svg-export' in buildArgsAsObject;
var noES5Compat = 'no-es5-compat' in buildArgsAsObject;
var requirejs = 'requirejs' in buildArgsAsObject ? 'requirejs' : false;
var sourceMap = 'sourcemap' in buildArgsAsObject;

// set amdLib var to encourage later support of other AMD systems
var amdLib = requirejs;

// if we want requirejs AMD support, use uglify
var amdUglifyFlags = '';
if (amdLib === 'requirejs' && minifier !== 'uglifyjs') {
  console.log('[notice]: require.js support requires uglifyjs as minifier; changed minifier to uglifyjs.');
  minifier = 'uglifyjs';
  amdUglifyFlags = " -r 'require,exports,window,fabric' -e window:window,undefined ";
}

// if we want sourceMap support, uglify or google closure compiler are supported
var sourceMapFlags = '';
if (sourceMap) {
  if (minifier !== 'uglifyjs' && minifier !== 'closure') {
    console.log('[notice]: sourceMap support requires uglifyjs or google closure compiler as minifier; changed minifier to uglifyjs.');
    minifier = 'uglifyjs';
  }
  sourceMapFlags = minifier === 'uglifyjs' ? ' --source-map all.min.js.map' : ' --create_source_map all.min.js.map --source_map_format=V3';
}

if (minifier === 'yui') {
  mininfierCmd = 'java -jar ' + rootPath + '/lib/yuicompressor-2.4.6.jar all.js -o all.min.js';
}
else if (minifier === 'closure') {
  mininfierCmd = 'java -jar ' + rootPath + '/lib/google_closure_compiler.jar --js all.js --js_output_file all.min.js' + sourceMapFlags;
}
else if (minifier === 'uglifyjs') {
  mininfierCmd = 'uglifyjs ' + amdUglifyFlags  + ' --output all.min.js all.js' + sourceMapFlags;
}

var buildSh = 'build-sh' in buildArgsAsObject;
var buildMinified = 'build-minified' in buildArgsAsObject;

var includeAllModules = (modulesToInclude.length === 1 && modulesToInclude[0] === 'ALL') || buildMinified;

var noSVGImport = (modulesToInclude.indexOf('parser') === -1 && !includeAllModules) || modulesToExclude.indexOf('parser') > -1;

var distFileContents =
  '/* build: `node build.js modules=' +
    modulesToInclude.join(',') +
    (modulesToExclude.length ? (' exclude=' + modulesToExclude.join(',')) : '') +
    (noStrict ? ' no-strict' : '') +
    (noSVGExport ? ' no-svg-export' : '') +
    (noES5Compat ? ' no-es5-compat' : '') +
    (requirejs ? ' requirejs' : '') +
    (sourceMap ? ' sourcemap' : '') +
    ' minifier=' + minifier +
  '` */';

function appendFileContents(fileNames, callback) {

  (function readNextFile() {

    if (fileNames.length <= 0) {
      return callback();
    }

    var fileName = fileNames.shift();

    if (!fileName) {
      return readNextFile();
    }

    fs.readFile(__dirname + '/' + fileName, function (err, data) {
      if (err) throw err;
      var strData = String(data);
      if (noStrict) {
        strData = strData.replace(/"use strict";?\n?/, '');
      }
      if (noSVGExport) {
        strData = strData.replace(/\/\* _TO_SVG_START_ \*\/[\s\S]*?\/\* _TO_SVG_END_ \*\//g, '');
      }
      if (noES5Compat) {
        strData = strData.replace(/\/\* _ES5_COMPAT_START_ \*\/[\s\S]*?\/\* _ES5_COMPAT_END_ \*\//g, '');
      }
      if (noSVGImport) {
        strData = strData.replace(/\/\* _FROM_SVG_START_ \*\/[\s\S]*?\/\* _FROM_SVG_END_ \*\//g, '');
      }
      distFileContents += ('\n' + strData + '\n');
      readNextFile();
    });

  })();
}

function ifSpecifiedInclude(moduleName, fileName) {
  var isInIncludedList = modulesToInclude.indexOf(moduleName) > -1;
  var isInExcludedList = modulesToExclude.indexOf(moduleName) > -1;

  // excluded list takes precedence over modules=ALL
  return ((isInIncludedList || includeAllModules) && !isInExcludedList) ? fileName : '';
}

function ifSpecifiedDependencyInclude(included, excluded, fileName) {
  return (
    (
      (modulesToInclude.indexOf(included) > -1 || includeAllModules) &&
      (modulesToExclude.indexOf(excluded) == -1))
    ? fileName
    : ''
  );
}

function ifSpecifiedAMDInclude(amdLib) {
  var supportedLibraries = ['requirejs'];
  if (supportedLibraries.indexOf(amdLib) > -1) {
    return 'src/amd/' + amdLib + '.js';
  }
  return '';
}

var filesToInclude = [
  'HEADER.js',

  ifSpecifiedDependencyInclude('text', 'cufon', 'lib/cufon.js'),
  ifSpecifiedDependencyInclude('serialization', 'json', 'lib/json2.js'),
  ifSpecifiedInclude('gestures', 'lib/event.js'),

  'src/mixins/observable.mixin.js',
  'src/mixins/collection.mixin.js',

  'src/util/misc.js',
  'src/util/arc.js',
  'src/util/lang_array.js',
  'src/util/lang_object.js',
  'src/util/lang_string.js',
  'src/util/lang_function.js',
  'src/util/lang_class.js',
  'src/util/dom_event.js',
  'src/util/dom_style.js',
  'src/util/dom_misc.js',
  'src/util/dom_request.js',

  'src/log.js',

  ifSpecifiedInclude('animation', 'src/util/animate.js'),
  //'src/util/animate.js',
  ifSpecifiedInclude('easing', 'src/util/anim_ease.js'),

  ifSpecifiedInclude('parser', 'src/parser.js'),
  ifSpecifiedInclude('parser', 'src/elements_parser.js'),

  'src/point.class.js',
  'src/intersection.class.js',
  'src/color.class.js',

  ifSpecifiedInclude('gradient', 'src/gradient.class.js'),
  ifSpecifiedInclude('pattern', 'src/pattern.class.js'),
  ifSpecifiedInclude('shadow', 'src/shadow.class.js'),

  'src/static_canvas.class.js',

  ifSpecifiedInclude('freedrawing', 'src/brushes/base_brush.class.js'),

  ifSpecifiedInclude('freedrawing', 'src/brushes/pencil_brush.class.js'),
  ifSpecifiedInclude('freedrawing', 'src/brushes/circle_brush.class.js'),
  ifSpecifiedInclude('freedrawing', 'src/brushes/spray_brush.class.js'),
  ifSpecifiedInclude('freedrawing', 'src/brushes/pattern_brush.class.js'),

  ifSpecifiedInclude('interaction', 'src/canvas.class.js'),
  ifSpecifiedInclude('interaction', 'src/mixins/canvas_events.mixin.js'),
  ifSpecifiedInclude('interaction', 'src/mixins/canvas_grouping.mixin.js'),

  'src/mixins/canvas_dataurl_exporter.mixin.js',

  ifSpecifiedInclude('serialization', 'src/mixins/canvas_serialization.mixin.js'),
  ifSpecifiedInclude('gestures', 'src/mixins/canvas_gestures.mixin.js'),

  'src/shapes/object.class.js',
  'src/mixins/object_origin.mixin.js',
  'src/mixins/object_geometry.mixin.js',
  'src/mixins/object_stacking.mixin.js',
  'src/mixins/object.svg_export.js',
  'src/mixins/stateful.mixin.js',

  ifSpecifiedInclude('interaction', 'src/mixins/object_interactivity.mixin.js'),

  ifSpecifiedInclude('animation', 'src/mixins/animation.mixin.js'),
  //'src/mixins/animation.mixin.js',

  'src/shapes/line.class.js',
  'src/shapes/circle.class.js',
  'src/shapes/triangle.class.js',
  'src/shapes/ellipse.class.js',
  'src/shapes/rect.class.js',
  'src/shapes/polyline.class.js',
  'src/shapes/polygon.class.js',
  'src/shapes/path.class.js',
  'src/shapes/path_group.class.js',
  'src/shapes/group.class.js',
  'src/shapes/image.class.js',

  ifSpecifiedInclude('object_straightening', 'src/mixins/object_straightening.mixin.js'),

  ifSpecifiedInclude('image_filters', 'src/filters/base_filter.class.js'),
  ifSpecifiedInclude('image_filters', 'src/filters/brightness_filter.class.js'),
  ifSpecifiedInclude('image_filters', 'src/filters/convolute_filter.class.js'),
  ifSpecifiedInclude('image_filters', 'src/filters/gradienttransparency_filter.class.js'),
  ifSpecifiedInclude('image_filters', 'src/filters/grayscale_filter.class.js'),
  ifSpecifiedInclude('image_filters', 'src/filters/invert_filter.class.js'),
  ifSpecifiedInclude('image_filters', 'src/filters/mask_filter.class.js'),
  ifSpecifiedInclude('image_filters', 'src/filters/noise_filter.class.js'),
  ifSpecifiedInclude('image_filters', 'src/filters/pixelate_filter.class.js'),
  ifSpecifiedInclude('image_filters', 'src/filters/removewhite_filter.class.js'),
  ifSpecifiedInclude('image_filters', 'src/filters/sepia_filter.class.js'),
  ifSpecifiedInclude('image_filters', 'src/filters/sepia2_filter.class.js'),
  ifSpecifiedInclude('image_filters', 'src/filters/tint_filter.class.js'),

  ifSpecifiedInclude('text', 'src/shapes/text.class.js'),
  ifSpecifiedInclude('cufon', 'src/shapes/text.cufon.js'),

  ifSpecifiedInclude('itext', 'src/shapes/itext.class.js'),
  ifSpecifiedInclude('itext', 'src/mixins/itext_behavior.mixin.js'),
  ifSpecifiedInclude('itext', 'src/mixins/itext_click_behavior.mixin.js'),
  ifSpecifiedInclude('itext', 'src/mixins/itext_key_behavior.mixin.js'),
  ifSpecifiedInclude('itext', 'src/mixins/itext.svg_export.js'),

  ifSpecifiedInclude('node', 'src/node.js'),

  ifSpecifiedAMDInclude(amdLib)
];

if (buildMinified) {
  for (var i = 0; i < filesToInclude.length; i++) {
    if (!filesToInclude[i]) continue;
    var fileNameWithoutSlashes = filesToInclude[i].replace(/\//g, '^');
    exec('uglifyjs -nc ' + amdUglifyFlags + filesToInclude[i] + ' > tmp/' + fileNameWithoutSlashes);
  }
}
else if (buildSh) {

  var filesStr = filesToInclude.join(' ');
  var isBasicBuild = modulesToInclude.length === 0;

  var minFilesStr = filesToInclude
    .filter(function(f) { return f !== '' })
    .map(function(fileName) {
      return 'tmp/' + fileName.replace(/\//g, '^');
    })
    .join(' ');

  var fileName = isBasicBuild ? 'fabric' : modulesToInclude.join(',');

  var escapedHeader = distFileContents.replace(/`/g, '\\`');
  var path = '../fabricjs.com/build/files/' + fileName + '.js';
  fs.appendFile('build.sh',
    'echo "' + escapedHeader + '" > ' + path + ' && cat ' +
    filesStr + ' >> ' + path + '\n');

  path = '../fabricjs.com/build/files/' + fileName + '.min.js';
  fs.appendFile('build.sh',
    'echo "' + escapedHeader + '" > ' + path + ' && cat ' +
    minFilesStr + ' >> ' + path + '\n')
}
else {
  // Change the current working directory
  process.chdir(distributionPath);

  appendFileContents(filesToInclude, function() {
    fs.writeFile('all.js', distFileContents, function (err) {
      if (err) {
        console.log(err);
        throw err;
      }

      // add js wrapping in AMD closure for requirejs if necessary
      if (amdLib !== false) {
        exec('uglifyjs all.js ' + amdUglifyFlags + ' -b --output all.js');
      }

      if (amdLib !== false) {
        console.log('Built distribution to ' + distributionPath + 'all.js (' + amdLib + '-compatible)');
      } else {
        console.log('Built distribution to ' + distributionPath + 'all.js');
      }

      exec(mininfierCmd, function (error, output) {
        if (error) {
          console.error('Minification failed using', minifier, 'with', mininfierCmd);
          process.exit(1);
        }
        console.log('Minified using', minifier, 'to ' + distributionPath + 'all.min.js');

        if (sourceMapFlags) {
          console.log('Built sourceMap to ' + distributionPath + 'all.min.js.map');
        }

        exec('gzip -c all.min.js > all.min.js.gz', function (error, output) {
          console.log('Gzipped to ' + distributionPath + 'all.min.js.gz');
        });
      });

      // Always build requirejs AMD module in all.require.js
      // add necessary requirejs footer code to filesToInclude if we haven't before
      if (amdLib === false) {
        amdLib = "requirejs";
        filesToInclude[filesToInclude.length] = ifSpecifiedAMDInclude(amdLib);
      }

      appendFileContents(filesToInclude, function() {
        fs.writeFile('all.require.js', distFileContents, function (err) {
          if (err) {
            console.log(err);
            throw err;
          }
          exec('uglifyjs all.require.js ' + amdUglifyFlags + ' -b --output all.require.js');
          console.log('Built distribution to ' + distributionPath + 'all.require.js (requirejs-compatible)');
        });
      });

    });
  });
}
<commit_msg>build.js with argument 'dest' to specify a path other than 'dist/' - ; (2)<commit_after>var fs = require('fs'),
    exec = require('child_process').exec;

var buildArgs = process.argv.slice(2),
    buildArgsAsObject = { },
    rootPath = process.cwd();

buildArgs.forEach(function(arg) {
  var key = arg.split('=')[0],
      value = arg.split('=')[1];

  buildArgsAsObject[key] = value;
});

var modulesToInclude = buildArgsAsObject.modules ? buildArgsAsObject.modules.split(',') : [ ];
var modulesToExclude = buildArgsAsObject.exclude ? buildArgsAsObject.exclude.split(',') : [ ];

var distributionPath = buildArgsAsObject.dest || 'dist/';
var minifier = buildArgsAsObject.minifier || 'uglifyjs';
var mininfierCmd;

var noStrict = 'no-strict' in buildArgsAsObject;
var noSVGExport = 'no-svg-export' in buildArgsAsObject;
var noES5Compat = 'no-es5-compat' in buildArgsAsObject;
var requirejs = 'requirejs' in buildArgsAsObject ? 'requirejs' : false;
var sourceMap = 'sourcemap' in buildArgsAsObject;

// set amdLib var to encourage later support of other AMD systems
var amdLib = requirejs;

// if we want requirejs AMD support, use uglify
var amdUglifyFlags = '';
if (amdLib === 'requirejs' && minifier !== 'uglifyjs') {
  console.log('[notice]: require.js support requires uglifyjs as minifier; changed minifier to uglifyjs.');
  minifier = 'uglifyjs';
  amdUglifyFlags = " -r 'require,exports,window,fabric' -e window:window,undefined ";
}

// if we want sourceMap support, uglify or google closure compiler are supported
var sourceMapFlags = '';
if (sourceMap) {
  if (minifier !== 'uglifyjs' && minifier !== 'closure') {
    console.log('[notice]: sourceMap support requires uglifyjs or google closure compiler as minifier; changed minifier to uglifyjs.');
    minifier = 'uglifyjs';
  }
  sourceMapFlags = minifier === 'uglifyjs' ? ' --source-map all.min.js.map' : ' --create_source_map all.min.js.map --source_map_format=V3';
}

if (minifier === 'yui') {
  mininfierCmd = 'java -jar ' + rootPath + '/lib/yuicompressor-2.4.6.jar all.js -o all.min.js';
}
else if (minifier === 'closure') {
  mininfierCmd = 'java -jar ' + rootPath + '/lib/google_closure_compiler.jar --js all.js --js_output_file all.min.js' + sourceMapFlags;
}
else if (minifier === 'uglifyjs') {
  mininfierCmd = 'uglifyjs ' + amdUglifyFlags  + ' --output all.min.js all.js' + sourceMapFlags;
}

var buildSh = 'build-sh' in buildArgsAsObject;
var buildMinified = 'build-minified' in buildArgsAsObject;

var includeAllModules = (modulesToInclude.length === 1 && modulesToInclude[0] === 'ALL') || buildMinified;

var noSVGImport = (modulesToInclude.indexOf('parser') === -1 && !includeAllModules) || modulesToExclude.indexOf('parser') > -1;

var distFileContents =
  '/* build: `node build.js modules=' +
    modulesToInclude.join(',') +
    (modulesToExclude.length ? (' exclude=' + modulesToExclude.join(',')) : '') +
    (noStrict ? ' no-strict' : '') +
    (noSVGExport ? ' no-svg-export' : '') +
    (noES5Compat ? ' no-es5-compat' : '') +
    (requirejs ? ' requirejs' : '') +
    (sourceMap ? ' sourcemap' : '') +
    ' minifier=' + minifier +
  '` */';

function appendFileContents(fileNames, callback) {

  (function readNextFile() {

    if (fileNames.length <= 0) {
      return callback();
    }

    var fileName = fileNames.shift();

    if (!fileName) {
      return readNextFile();
    }

    fs.readFile(__dirname + '/' + fileName, function (err, data) {
      if (err) throw err;
      var strData = String(data);
      if (noStrict) {
        strData = strData.replace(/"use strict";?\n?/, '');
      }
      if (noSVGExport) {
        strData = strData.replace(/\/\* _TO_SVG_START_ \*\/[\s\S]*?\/\* _TO_SVG_END_ \*\//g, '');
      }
      if (noES5Compat) {
        strData = strData.replace(/\/\* _ES5_COMPAT_START_ \*\/[\s\S]*?\/\* _ES5_COMPAT_END_ \*\//g, '');
      }
      if (noSVGImport) {
        strData = strData.replace(/\/\* _FROM_SVG_START_ \*\/[\s\S]*?\/\* _FROM_SVG_END_ \*\//g, '');
      }
      distFileContents += ('\n' + strData + '\n');
      readNextFile();
    });

  })();
}

function ifSpecifiedInclude(moduleName, fileName) {
  var isInIncludedList = modulesToInclude.indexOf(moduleName) > -1;
  var isInExcludedList = modulesToExclude.indexOf(moduleName) > -1;

  // excluded list takes precedence over modules=ALL
  return ((isInIncludedList || includeAllModules) && !isInExcludedList) ? fileName : '';
}

function ifSpecifiedDependencyInclude(included, excluded, fileName) {
  return (
    (
      (modulesToInclude.indexOf(included) > -1 || includeAllModules) &&
      (modulesToExclude.indexOf(excluded) == -1))
    ? fileName
    : ''
  );
}

function ifSpecifiedAMDInclude(amdLib) {
  var supportedLibraries = ['requirejs'];
  if (supportedLibraries.indexOf(amdLib) > -1) {
    return 'src/amd/' + amdLib + '.js';
  }
  return '';
}

var filesToInclude = [
  'HEADER.js',

  ifSpecifiedDependencyInclude('text', 'cufon', 'lib/cufon.js'),
  ifSpecifiedDependencyInclude('serialization', 'json', 'lib/json2.js'),
  ifSpecifiedInclude('gestures', 'lib/event.js'),

  'src/mixins/observable.mixin.js',
  'src/mixins/collection.mixin.js',

  'src/util/misc.js',
  'src/util/arc.js',
  'src/util/lang_array.js',
  'src/util/lang_object.js',
  'src/util/lang_string.js',
  'src/util/lang_function.js',
  'src/util/lang_class.js',
  'src/util/dom_event.js',
  'src/util/dom_style.js',
  'src/util/dom_misc.js',
  'src/util/dom_request.js',

  'src/log.js',

  ifSpecifiedInclude('animation', 'src/util/animate.js'),
  //'src/util/animate.js',
  ifSpecifiedInclude('easing', 'src/util/anim_ease.js'),

  ifSpecifiedInclude('parser', 'src/parser.js'),
  ifSpecifiedInclude('parser', 'src/elements_parser.js'),

  'src/point.class.js',
  'src/intersection.class.js',
  'src/color.class.js',

  ifSpecifiedInclude('gradient', 'src/gradient.class.js'),
  ifSpecifiedInclude('pattern', 'src/pattern.class.js'),
  ifSpecifiedInclude('shadow', 'src/shadow.class.js'),

  'src/static_canvas.class.js',

  ifSpecifiedInclude('freedrawing', 'src/brushes/base_brush.class.js'),

  ifSpecifiedInclude('freedrawing', 'src/brushes/pencil_brush.class.js'),
  ifSpecifiedInclude('freedrawing', 'src/brushes/circle_brush.class.js'),
  ifSpecifiedInclude('freedrawing', 'src/brushes/spray_brush.class.js'),
  ifSpecifiedInclude('freedrawing', 'src/brushes/pattern_brush.class.js'),

  ifSpecifiedInclude('interaction', 'src/canvas.class.js'),
  ifSpecifiedInclude('interaction', 'src/mixins/canvas_events.mixin.js'),
  ifSpecifiedInclude('interaction', 'src/mixins/canvas_grouping.mixin.js'),

  'src/mixins/canvas_dataurl_exporter.mixin.js',

  ifSpecifiedInclude('serialization', 'src/mixins/canvas_serialization.mixin.js'),
  ifSpecifiedInclude('gestures', 'src/mixins/canvas_gestures.mixin.js'),

  'src/shapes/object.class.js',
  'src/mixins/object_origin.mixin.js',
  'src/mixins/object_geometry.mixin.js',
  'src/mixins/object_stacking.mixin.js',
  'src/mixins/object.svg_export.js',
  'src/mixins/stateful.mixin.js',

  ifSpecifiedInclude('interaction', 'src/mixins/object_interactivity.mixin.js'),

  ifSpecifiedInclude('animation', 'src/mixins/animation.mixin.js'),
  //'src/mixins/animation.mixin.js',

  'src/shapes/line.class.js',
  'src/shapes/circle.class.js',
  'src/shapes/triangle.class.js',
  'src/shapes/ellipse.class.js',
  'src/shapes/rect.class.js',
  'src/shapes/polyline.class.js',
  'src/shapes/polygon.class.js',
  'src/shapes/path.class.js',
  'src/shapes/path_group.class.js',
  'src/shapes/group.class.js',
  'src/shapes/image.class.js',

  ifSpecifiedInclude('object_straightening', 'src/mixins/object_straightening.mixin.js'),

  ifSpecifiedInclude('image_filters', 'src/filters/base_filter.class.js'),
  ifSpecifiedInclude('image_filters', 'src/filters/brightness_filter.class.js'),
  ifSpecifiedInclude('image_filters', 'src/filters/convolute_filter.class.js'),
  ifSpecifiedInclude('image_filters', 'src/filters/gradienttransparency_filter.class.js'),
  ifSpecifiedInclude('image_filters', 'src/filters/grayscale_filter.class.js'),
  ifSpecifiedInclude('image_filters', 'src/filters/invert_filter.class.js'),
  ifSpecifiedInclude('image_filters', 'src/filters/mask_filter.class.js'),
  ifSpecifiedInclude('image_filters', 'src/filters/noise_filter.class.js'),
  ifSpecifiedInclude('image_filters', 'src/filters/pixelate_filter.class.js'),
  ifSpecifiedInclude('image_filters', 'src/filters/removewhite_filter.class.js'),
  ifSpecifiedInclude('image_filters', 'src/filters/sepia_filter.class.js'),
  ifSpecifiedInclude('image_filters', 'src/filters/sepia2_filter.class.js'),
  ifSpecifiedInclude('image_filters', 'src/filters/tint_filter.class.js'),

  ifSpecifiedInclude('text', 'src/shapes/text.class.js'),
  ifSpecifiedInclude('cufon', 'src/shapes/text.cufon.js'),

  ifSpecifiedInclude('itext', 'src/shapes/itext.class.js'),
  ifSpecifiedInclude('itext', 'src/mixins/itext_behavior.mixin.js'),
  ifSpecifiedInclude('itext', 'src/mixins/itext_click_behavior.mixin.js'),
  ifSpecifiedInclude('itext', 'src/mixins/itext_key_behavior.mixin.js'),
  ifSpecifiedInclude('itext', 'src/mixins/itext.svg_export.js'),

  ifSpecifiedInclude('node', 'src/node.js'),

  ifSpecifiedAMDInclude(amdLib)
];

if (buildMinified) {
  for (var i = 0; i < filesToInclude.length; i++) {
    if (!filesToInclude[i]) continue;
    var fileNameWithoutSlashes = filesToInclude[i].replace(/\//g, '^');
    exec('uglifyjs -nc ' + amdUglifyFlags + filesToInclude[i] + ' > tmp/' + fileNameWithoutSlashes);
  }
}
else if (buildSh) {

  var filesStr = filesToInclude.join(' ');
  var isBasicBuild = modulesToInclude.length === 0;

  var minFilesStr = filesToInclude
    .filter(function(f) { return f !== '' })
    .map(function(fileName) {
      return 'tmp/' + fileName.replace(/\//g, '^');
    })
    .join(' ');

  var fileName = isBasicBuild ? 'fabric' : modulesToInclude.join(',');

  var escapedHeader = distFileContents.replace(/`/g, '\\`');
  var path = '../fabricjs.com/build/files/' + fileName + '.js';
  fs.appendFile('build.sh',
    'echo "' + escapedHeader + '" > ' + path + ' && cat ' +
    filesStr + ' >> ' + path + '\n');

  path = '../fabricjs.com/build/files/' + fileName + '.min.js';
  fs.appendFile('build.sh',
    'echo "' + escapedHeader + '" > ' + path + ' && cat ' +
    minFilesStr + ' >> ' + path + '\n')
}
else {
  // Change the current working directory
  process.chdir(distributionPath);

  appendFileContents(filesToInclude, function() {
    fs.writeFile('all.js', distFileContents, function (err) {
      if (err) {
        console.log(err);
        throw err;
      }

      // add js wrapping in AMD closure for requirejs if necessary
      if (amdLib !== false) {
        exec('uglifyjs all.js ' + amdUglifyFlags + ' -b --output all.js');
      }

      if (amdLib !== false) {
        console.log('Built distribution to ' + distributionPath + 'all.js (' + amdLib + '-compatible)');
      } else {
        console.log('Built distribution to ' + distributionPath + 'all.js');
      }

      exec(mininfierCmd, function (error, output) {
        if (error) {
          console.error('Minification failed using', minifier, 'with', mininfierCmd);
          process.exit(1);
        }
        console.log('Minified using', minifier, 'to ' + distributionPath + 'all.min.js');

        if (sourceMapFlags) {
          console.log('Built sourceMap to ' + distributionPath + 'all.min.js.map');
        }

        exec('gzip -c all.min.js > all.min.js.gz', function (error, output) {
          console.log('Gzipped to ' + distributionPath + 'all.min.js.gz');
        });
      });

      // Always build requirejs AMD module in all.require.js
      // add necessary requirejs footer code to filesToInclude if we haven't before
      if (amdLib === false) {
        amdLib = "requirejs";
        filesToInclude[filesToInclude.length] = ifSpecifiedAMDInclude(amdLib);
      }

      appendFileContents(filesToInclude, function() {
        fs.writeFile('all.require.js', distFileContents, function (err) {
          if (err) {
            console.log(err);
            throw err;
          }
          exec('uglifyjs all.require.js ' + amdUglifyFlags + ' -b --output all.require.js');
          console.log('Built distribution to ' + distributionPath + 'all.require.js (requirejs-compatible)');
        });
      });

    });
  });
}
<|endoftext|>


<commit_before>MapSearchApp.Views.MarkerView = Backbone.View.extend({

    initialize: function (params) {
        var that = this;
        //events on model
        this.model.on("change:selected", function (ob1) {
            this.render();
        }, this);
    },

    //use for events on this.$el
    events: {
        "click": "onClick"
    },

    onClick: function () {
        //console.log(this);
        this.model.toggleSelected();
    },

    template: MapSearchApp.Services.templates.get("#marker-template"),

    render: function () {
        var json = this.model.toJSON();
        var m1 = {x: json.lat * 6,
            y: json.lng * 4};
        var html = this.template(m1);
        this.$el.html(html);
        if (this.model.isSelected()) {
            this.$el.find('.marker').addClass("highlighted");
        }

        return this;
    }

});

// CSS class: "highlighted"
// $obj.addClass("css-class")
// $obj.removeClass("css-class")
<commit_msg>click with closure<commit_after>MapSearchApp.Views.MarkerView = Backbone.View.extend({

    initialize: function (params) {
        var that = this;
        //events on model
        this.model.on("change:selected", function (ob1) {
            that.render();
        });
    },

    //use for events on this.$el
    events: {
        "click": "onClick"
    },

    onClick: function () {
        //console.log(this);
        this.model.toggleSelected();
    },

    template: MapSearchApp.Services.templates.get("#marker-template"),

    render: function () {
        var json = this.model.toJSON();
        var m1 = {x: json.lat * 6,
            y: json.lng * 4};
        var html = this.template(m1);
        this.$el.html(html);
        if (this.model.isSelected()) {
            this.$el.find('.marker').addClass("highlighted");
        }

        return this;
    }

});

// CSS class: "highlighted"
// $obj.addClass("css-class")
// $obj.removeClass("css-class")
<|endoftext|>