<commit_before>// ==UserScript==
// @name         no-refresh
// @namespace   https://github.com/EFox2413
// @version      0.1.1
// @updateURL    https://raw.githubusercontent.com/EFox2413/initiumGrease/master/no-refresh.js
// @downloadURL    https://raw.githubusercontent.com/EFox2413/initiumGrease/master/no-refresh.js
// @supportURL      https://github.com/EFox2413/initiumGrease/issues
// @match       https://www.playinitium.com/*
// @match       http://www.playinitium.com/*
// @grant        none
// ==/UserScript==
/* jshint -W097 */
'use strict';

var $ = window.jQuery;

var buttonRight = $( '.main-button' ).first();
var buttonLeft = $( '.main-button' ).first().next();

var linkArr = [];
linkArr.push(buttonRight.attr( "href"));
linkArr.push(buttonLeft.attr( "href" ));

// disables href redirect for first 2 buttons
buttonRight.removeAttr( "href" );
buttonLeft.removeAttr( "href" );

// on click calls the get data function
buttonRight.click( function() {
    getData(linkArr[0]);
});

buttonLeft.click( function() {
    getData(linkArr[1]);
});

// gets the data from the actionURL
function getData(actionURL) {
    $.get(actionURL)
        .done(function(data) {
            processData(data);
            }
         );
}

console.log($( '.main-page' ).last().children().html());
// Gets the hp values and the battle description from the returned data
function processData(data) {
    var $data = $(data);
    var $mainPageDiv = $data.filter( '.main-page' ).last();
    var $hpObj = $mainPageDiv.find( '.character-display-box' ).children( 'div' ).children( 'div' ).children( 'p' );

    // gets the new hps
    var playerHP = $hpObj.first().text();
    var enemyHP = $hpObj.last().text();

    // gets the new combat text
    var combatHTML = parseCombatHTML($mainPageDiv.html());

    // if either the player or the enemy is dead call for refresh
    //   because of the way the HTML works if the enemy HP div is missing
    //   it will use the same div for both objects
    if( playerHP === enemyHP ) { fullpageRefresh(); }

    // data is processed, now update the relevant divs
    updateCombat(playerHP, enemyHP, combatHTML);

    // TODO REMOVE
    console.log(playerHP + ", " + enemyHP + "\n html: " + combatHTML);
}

// TODO smarter way of updating the hpObjects
/*
// this gets the player hp div
html = html.slice(html.indexOf( "
",
                  html.indexOf( "<div class=\"buff-pane hint"));

// this gets the enemy div
html = html.slice(html.indexOf( "<div class=\"character-display-box\"\ style=\"float:right",
                  html.indexOf( "<div calss=\"chat_box"));
 */

// parses HTML and gets the combat related HTML
function parseCombatHTML( html ){
    html = html.slice(html.indexOf( "<p" ));

    console.log( html );
    return html;
}

// updates the HTML elements on the current page with the values
function updateCombat(newPlayerHP, newEnemyHP, combatHTML) {
    var $hpObj = $( '.character-display-box' ).children( 'div' ).children( 'div' ).children( 'p' );
    var playerHP = $hpObj.first();
    var enemyHP = $hpObj.last();

    playerHP.text( newPlayerHP );
    enemyHP.text( newEnemyHP );
    $( '.main-page' ).last().append( '

' );
    $( '.combat-text' ).html( combatHTML );
}
<commit_msg>HP bars now update on attack<commit_after>// ==UserScript==
// @name         no-refresh
// @namespace   https://github.com/EFox2413
// @version      0.1.1
// @updateURL    https://raw.githubusercontent.com/EFox2413/initiumGrease/master/no-refresh.js
// @downloadURL    https://raw.githubusercontent.com/EFox2413/initiumGrease/master/no-refresh.js
// @supportURL      https://github.com/EFox2413/initiumGrease/issues
// @match       https://www.playinitium.com/*
// @match       http://www.playinitium.com/*
// @grant        none
// ==/UserScript==
/* jshint -W097 */
'use strict';

var $ = window.jQuery;

$( '.main-page' ).last().append( '

' );

var buttonRight = $( '.main-button' ).first();
var buttonLeft = $( '.main-button' ).first().next();

var linkArr = [];
linkArr.push(buttonRight.attr( "href"));
linkArr.push(buttonLeft.attr( "href" ));

// disables href redirect for first 2 buttons
buttonRight.removeAttr( "href" );
buttonLeft.removeAttr( "href" );

// on click calls the get data function
buttonRight.click( function() {
    getData(linkArr[0]);
});

buttonLeft.click( function() {
    getData(linkArr[1]);
});

// gets the data from the actionURL
function getData(actionURL) {
    $.get(actionURL)
        .done(function(data) {
            processData(data);
            }
         );
}

console.log($( '.main-page' ).last().children().html());
// Gets the hp values and the battle description from the returned data
function processData(data) {
    var $data = $(data);
    var $mainPageDiv = $data.filter( '.main-page' ).last();
    var $hpObj = $mainPageDiv.find( '.character-display-box' ).children( 'div' ).children( 'div' ).children( 'p' );

    // gets the new hps
    var playerHP = $hpObj.first().text();
    var enemyHP = $hpObj.last().text();

    // gets the new combat text
    var combatHTML = parseCombatHTML($mainPageDiv.html());

    // if either the player or the enemy is dead call for refresh
    //   because of the way the HTML works if the enemy HP div is missing
    //   it will use the same div for both objects
    if( playerHP === enemyHP ) { fullpageRefresh(); }

    // data is processed, now update the relevant divs
    updateCombat(playerHP, enemyHP, combatHTML);
}

// parses HTML and gets the combat related HTML
function parseCombatHTML( html ){
    html = html.slice(html.indexOf( "
\n\t" ));
    return html;
}

// updates the HTML elements on the current page with the values
function updateCombat(newPlayerHP, newEnemyHP, combatHTML) {
    var $hpObj = $( '.character-display-box' ).children( 'div' ).children( 'div' );
    var playerHP = $hpObj.children( 'p' ).first();
    var enemyHP = $hpObj.children( 'p' ).last();
    var newPlayerHPBarWidth = parseInt(parseFloat(newPlayerHP) / parseFloat( newPlayerHP.slice(newPlayerHP.indexOf("/") + 1)) * 100);
    var newEnemyHPBarWidth = parseInt(parseFloat(newEnemyHP) / parseFloat( newEnemyHP.slice(newEnemyHP.indexOf("/") + 1)) * 100);

    $hpObj.children().first().width( newPlayerHPBarWidth + "px" );
    $hpObj.children().last().prev().width( newEnemyHPBarWidth + "px" );

    playerHP.text( newPlayerHP );
    enemyHP.text( newEnemyHP );
    $( '.combat-text' ).html( combatHTML );
}
<|endoftext|>


<commit_before>var wrench, fs, path, createStringReader, createTokenizer, vanillaCompiler;

wrench = require('wrench');
fs = require('fs');
path = require('path');
vanillaCompiler = require('../../../index');
createStringReader = require('../../stringreader').createStringReader;
createTokenizer = require('./tokenizer').createTokenizer;

/////////
// API //
/////////

// compile(file, mode, options, callback)
// compile(file, mode, options, child, callback)
exports.compile = function (file, mode, options, child, callback) {
  'use strict';
  var outputfilename;

  if (typeof child === 'function') {
    callback = child;
    child = null;
  }

  file = path.resolve(file);

  // TODO: Use child to reference its blocks and meta data (if child is defined).
  parseIncludes(file, mode, options, function (error, text) {
    if (error) {
      callback(error);
    } else {
      if (options.html.including) {
        callback(null, text);
      } else {
        outputfilename = path.join(options.html.output, path.basename(file, '.html') + '.html');
        wrench.mkdirSyncRecursive(options.html.output, parseInt('777', 8));
        fs.writeFile(outputfilename, text, function (error) {
          if (error) {
            callback(error);
          } else {
            callback(null, outputfilename);
          }
        });
      }
    }
    // TODO: Handle extends tokens.
      // - enumerate blocks
      // - apply child blocks (if child is defined)
      // - compile parent as template
    // TODO: If no extends then blocks are simply rendered as-is
  });
};

//////////////////////
// Helper Functions //
//////////////////////

function parseIncludes(file, mode, options, callback) {
  getIncludes(file, function (error, text, includes) {
    if (error) {
      callback(error);
    } else {
      expandIncludes(text, includes, mode, options, function (error, text) {
        if (error) {
          callback(error);
        } else {
          callback(null, text);
        }
      });
    }
  });
}

function getIncludes(filename, callback) {
  'use strict';
  var includes, types, typeExt;

  includes = [];
  types = ['include','stylesheet','script'];

  fs.readFile(filename, 'utf8', function (error, text) {
    var stringReader, tokenizer, token, includedFilename, ext;

    if (error) {
      callback(error);
      return;
    }

    stringReader = createStringReader(text);
    tokenizer = createTokenizer(stringReader);

    token = tokenizer.next();

    while (token.name) {
      if (types.indexOf(token.name) >= 0) {
        includedFilename = path.resolve(path.dirname(filename), token.attributes.file || token.attributes.src);
        ext = path.extname(includedFilename);

        switch (token.name) {
          case 'include':
            typeExt = '.html';
            break;
          case 'stylesheet':
            typeExt = '.css';
            break;
          case 'script':
            typeExt = '.js';
            break;
        }

        if (ext !== typeExt) {
          includedFilename = path.join(path.dirname(includedFilename), path.basename(includedFilename, ext) + typeExt);
        }

        includes.push({
          filename: includedFilename,
          token: token
        });
      }

      token = tokenizer.next();
    }

    callback(null, text, includes);
  });
}

function expandIncludes(text, includes, mode, options, callback) {
  var text;

  if (!includes.length) {
    callback(null, text);
    return;
  }

  includes = includes.slice();
  options = Object.create(options);
  options.html = Object.create(options.html);
  options.html.including = true;

  function next() {
    var incl, line;

    if (includes.length) {
      incl = includes.pop();
      line = getLineWithIndex(text, incl.token.start);
      vanillaCompiler.compile(incl.filename, mode, options, function (error, result, markup) {
        if (error) {
          callback(error);
        } else {
          switch (incl.token.name) {
            case 'include':
              markup = result;
              break;
            case 'script':
              markup = markup || '<script src="/' + path.relative(options.server.root, incl.filename)+ '" type="text/javascript"></script>';
              break;
            case 'stylesheet':
              markup = markup || '<link href="/' + path.relative(options.server.root, incl.filename) + '" rel="stylesheet" />';
              break;
          }

          text = text.substring(0, line.begin) + markup + '\n' + text.substring(line.end);
          next();
        }
      });
    } else {
      callback(null, text);
    }
  }

  next();
}

function getLineWithIndex(string, index) {
  var c, begin, end, i;

  c = string.charAt(index);
  begin = index;

  while (c) {
    if (c === '\n') {
      begin += 1;
      break;
    } else {
      begin -= 1;
      c = string.charAt(begin);
    }
  }

  c = string.charAt(index);
  end = index;

  while (c) {
    if (c === '\n') {
      break;
    } else {
      end += 1;
      c = string.charAt(end);
    }
  }

  return {
    begin: begin,
    end: end
  };
}<commit_msg>Finish the html compiler implementation of layout templates and blocks<commit_after>var wrench, fs, path, createStringReader, createTokenizer, vanillaCompiler;

wrench = require('wrench');
fs = require('fs');
path = require('path');
vanillaCompiler = require('../../../index');
createStringReader = require('../../stringreader').createStringReader;
createTokenizer = require('./tokenizer').createTokenizer;

/////////
// API //
/////////

// compile(file, mode, options, callback)
// compile(file, mode, options, child, callback)
exports.compile = function (file, mode, options, child, callback) {
  'use strict';
  var outputfilename;

  if (typeof child === 'function') {
    callback = child;
    child = null;
  }

  file = path.resolve(file);

  parseIncludes(file, mode, options, function (error, text) {
    if (error) {
      callback(error);
    } else {
      parseExtends(text, mode, options, child, function (error, result) {
        if (error) {
          callback(error);
        } else if (options.html.including) {
          callback(null, result);
        } else {
          outputfilename = path.join(options.html.output, path.basename(file, '.html') + '.html');
          wrench.mkdirSyncRecursive(options.html.output, parseInt('777', 8));
          fs.writeFile(outputfilename, result, function (error) {
            if (error) {
              callback(error);
            } else {
              callback(null, outputfilename);
            }
          });
        }
      });
    }
  });
};

//////////////////////
// Helper Functions //
//////////////////////

function parseIncludes(file, mode, options, callback) {
  getIncludes(file, function (error, text, includes) {
    if (error) {
      callback(error);
    } else {
      expandIncludes(text, includes, mode, options, function (error, text) {
        if (error) {
          callback(error);
        } else {
          callback(null, text);
        }
      });
    }
  });
}

function getIncludes(filename, callback) {
  'use strict';
  var includes, types, typeExt;

  includes = [];
  types = ['include','stylesheet','script'];

  fs.readFile(filename, 'utf8', function (error, text) {
    var stringReader, tokenizer, token, includedFilename, ext;

    if (error) {
      callback(error);
      return;
    }

    stringReader = createStringReader(text);
    tokenizer = createTokenizer(stringReader);

    token = tokenizer.next();

    while (token.name) {
      if (types.indexOf(token.name) >= 0) {
        includedFilename = path.resolve(path.dirname(filename), token.attributes.file || token.attributes.src);
        ext = path.extname(includedFilename);

        switch (token.name) {
          case 'include':
            typeExt = '.html';
            break;
          case 'stylesheet':
            typeExt = '.css';
            break;
          case 'script':
            typeExt = '.js';
            break;
        }

        if (ext !== typeExt) {
          includedFilename = path.join(path.dirname(includedFilename), path.basename(includedFilename, ext) + typeExt);
        }

        includes.push({
          filename: includedFilename,
          token: token
        });
      }

      token = tokenizer.next();
    }

    callback(null, text, includes);
  });
}

function expandIncludes(text, includes, mode, options, callback) {
  var text;

  if (!includes.length) {
    callback(null, text);
    return;
  }

  includes = includes.slice();
  options = extendOptions(options);
  options.html.including = true;

  function next() {
    var incl, line;

    if (includes.length) {
      incl = includes.pop();
      line = getLineWithIndex(text, incl.token.start);
      vanillaCompiler.compile(incl.filename, mode, options, function (error, result, markup) {
        if (error) {
          callback(error);
        } else {
          switch (incl.token.name) {
            case 'include':
              markup = result;
              break;
            case 'script':
              markup = markup || '<script src="/' + path.relative(options.server.root, incl.filename)+ '" type="text/javascript"></script>';
              break;
            case 'stylesheet':
              markup = markup || '<link href="/' + path.relative(options.server.root, incl.filename) + '" rel="stylesheet" />';
              break;
          }

          text = replaceLine(text, line, markup);
          next();
        }
      });
    } else {
      callback(null, text);
    }
  }

  next();
}

function extendOptions(options) {
  options = Object.create(options);
  options.html = Object.create(options.html);
  return options;
}

function getLineWithIndex(string, index) {
  var c, begin, end, i;

  c = string.charAt(index);
  begin = index;

  while (c) {
    if (c === '\n') {
      begin += 1;
      break;
    } else {
      begin -= 1;
      c = string.charAt(begin);
    }
  }

  c = string.charAt(index);
  end = index;

  while (c) {
    if (c === '\n') {
      break;
    } else {
      end += 1;
      c = string.charAt(end);
    }
  }

  return {
    begin: begin,
    end: end
  };
}

function replaceLine(text, line, replacement) {
  return text.substring(0, line.begin) + (replacement || '') + '\n' + text.substring(line.end);
}

function enumerateBlocks(text) {
  var stringReader, tokenizer, token, blocks, block;

  blocks = {};
  stringReader = createStringReader(text);
  tokenizer = createTokenizer(stringReader);

  token = tokenizer.next();

  while (token.name) {
    if (token.name === 'block') {
      // </v:block> encountered.
      if (token.closing) {
        if (block) {
          block.endLine = getLineWithIndex(token.begin);
          block.bodyEnd = token.begin;
          block.body = text.substring(block.bodyBegin, block.bodyEnd);
          blocks[block.name] = block;
          block = null;
        } else {
          throw new Error('Unbalanced <v:block></v:block> tokens.');
        }
      // <v:block> encountered.
      } else {
        if (block) {
          throw new Error('Unbalanced <v:block></v:block> tokens.');
        } else if (token.attributes.name) {
          block = {
            name: token.attributes.name,
            beginLine: getLineWithIndex(token.begin),
            bodyBegin: token.end
          };
        } else {
          throw new Error('Malformed <v:block> token: Expected name attribute.');
        }
      }
    }
  }

  return blocks;
}

function parseExtends(text, mode, options, child, callback) {
  var extendsTokens, extendsToken, blocks;

  extendsTokens = getExtendsTokens(text);

  if (extendsTokens.length === 1) {
    extendsToken = extendsTokens[0];
    text = replaceLine(text, getLineWithIndex(extendsToken.begin));
    blocks = enumerateBlocks(text);
    applyChildBlocks(blocks, child);

    options = extendOptions(options);
    options.html.including = true;

    exports.compile(layoutFilename, mode, options, blocks, callback);
  } else if (extendsTokens.length > 1) {
    callback(new Error('HTML templates only support one <v:extends> token.'));
  } else {
    blocks = enumerateBlocks(text);
    applyChildBlocks(blocks, child);
    text = replaceBlocks(blocks, text);
    callback(null, text);
  }
}

function getExtendsTokens(text) {
  var stringReader, tokenizer, token, tokens;

  stringReader = createStringReader(text);
  tokenizer = createTokenizer(stringReader);
  tokens = [];
  token = tokenizer.next();

  while (token.name) {
    if (token.name === 'extends') {
      tokens.push(token);
    }
    token = tokenizer.next();
  }

  return tokens;
}

function applyChildBlocks(blocks, child) {
  if (!child) return blocks;
  for (var name in child) {
    if (blocks[name]) {
      blocks[name].body = child[name].body;
    }
  }
  return blocks;
}

function replaceBlocks(blocks, text) {
  var name, block;
  Object.keys(blocks).reverse().forEach(function (name) {
    var block = blocks[name];
    text = text.substring(0, block.beginLine.begin) + block.body + text.substring(block.endLine.begin);
  });
  return text;
}<|endoftext|>


<commit_before>var express = require("express"),
    app     = express(),
    dbWorker = require('./db.js');
var path = require('path');
var appDir = path.resolve('./');
var bodyParser = require('body-parser')
app.use(bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
}));

var port = process.env.PORT || 8080;
var server = app.listen(port, function() {
  console.log(this.address());
});

app.use(express.static('build'));
app.use(express.static(appDir));

app.post('/data/addArticle', function(req, res) {
    var name = req.body;
    dbWorker.entities['articles'].create(req.body, res);
});
app.post('/data/updateArticle', function(req, res) {
    var name = req.body;
    dbWorker.entities['articles'].update(req.body, res);
});
app.get('/data/articles', function(req,res) {
    var result = dbWorker.entities['articles'].get(res);
});
app.get('/', function(req,res) {
  res.sendFile(appDir + '/app/index.html');
})

<commit_msg>Update<commit_after>var express = require("express"),
    app     = express(),
    dbWorker = require('./db.js');
var path = require('path');
var appDir = path.resolve('./');
var bodyParser = require('body-parser')
app.use(bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
}));

var port = process.env.PORT || 80;
var server = app.listen(port, function() {
  console.log(this.address());
});

app.use(express.static('build'));
app.use(express.static(appDir));

app.post('/data/addArticle', function(req, res) {
    var name = req.body;
    dbWorker.entities['articles'].create(req.body, res);
});
app.post('/data/updateArticle', function(req, res) {
    var name = req.body;
    dbWorker.entities['articles'].update(req.body, res);
});
app.get('/data/articles', function(req,res) {
    var result = dbWorker.entities['articles'].get(res);
});
app.get('/', function(req,res) {
  res.sendFile(appDir + '/app/index.html');
})

<|endoftext|>


<commit_before>/** @preserve nodehelper
 *  @copyright 2014 Kevin von Flotow <vonflow@gmail.com>
 *  @license MIT License <http://opensource.org/licenses/MIT>
 */

;(function() {
	function nh() {
		this.logging = true;
	}

	nh.prototype = {
		set: function ( key, val ) {
			if ( this.hasOwnProperty( key ) )
				this[ key ] = val;
			else
				this.nhLog( 'set: invalid property' );
		},

		nhLog: function ( msg ) {
			return this.logging ? console.log( 'nodehelper: ' + msg.toString() ) : false;
		},

		isString: function ( str ) {
			return typeof str === 'string' || str instanceof String;
		},

		// http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric
		isNumber: function ( num ) {
			return !isNaN( parseFloat( num ) ) && isFinite( num );
		},

		isObject: function ( obj ) {
			return obj === Object( obj ) && Object.prototype.toString.call( obj ) !== '[object Array]';
		},

		isFunction: function () {

		},

		each: function ( obj, callback ) {
			if ( !obj )
				return this.nhLog( 'each: obj is required' );

			if ( !callback )
				return this.nhLog( 'each: callback is required' );
			else if ( !this.isFunction( callback ) )
				return this.nhLog( 'each: callback must be a function' );

			if ( Array.isArray( obj ) ) {
				// loops a normal array - []

				for ( var i = 0, l = obj.length; i < l; i++ )
					callback.call( obj, i, obj[ i ] );

			} else if ( obj === Object( obj ) ) {
				// loops an object - {}

				for ( var key in obj )
					callback.call( obj, key, obj[ key ] );

			} else if ( this.isNumber( obj ) ) {
				// loops a number - 23

				for ( var i = 0; i < obj; i++ )
					callback.call( obj, i );

			} else if ( this.isString( obj ) ) {
				// loops a string - 'foo'

				for ( var i = 0, l = obj.length; i < l; i++ )
					callback.call( obj, i, obj.charAt( i ) );

			} else {
				this.nhLog( 'each: invalid type' );
			}
		},

		// provide some bitwise math alternatives
		bitFloor: function ( num ) {
			return num | 0;
		},

		bitCeil: function ( num ) {
			return ( num + 1 ) | 0;
		},

		bitRound: function ( num ) {
			return ( num + 0.5 ) | 0;
		},

		// http://en.wikipedia.org/wiki/Lerp_(computing)
		// not 100% sure this is useful for nodejs - possibly smoothing out test results
		lerp: function ( fromNum, toNum, t ) {
			return fromNum + ( toNum - fromNum ) * t;
		},

		// example: nh.getPointInRange( 0.2, 0, 523 ) returns 104.6
		getPointInRange: function ( targetPoint, rangeMin, rangeMax ) {
			return ( ( rangeMax - rangeMin ) * targetPoint ) + rangeMin;
		},

		// Fisher-Yates shuffle
		// http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
		shuffle: function ( arr ) {
			if ( !arr || !Array.isArray( arr ) )
				return false;

			var n = arr.slice( 0 ),
				i = n.length,
				j, t;

			while ( --i > 0 ) {
				j = this.bitFloor( Math.random() * ( i + 1 ) );
				t = n[ j ];
				n[ j ] = n[ i ];
				n[ i ] = t;
			}

			return n;
		},

		// setting shuffleOverride to true disables the shuffle - useful for one-off randoms where performance is a concern
		randomFromArray: function ( arr, shuffleOverride ) {
			if ( !arr || !Array.isArray( arr ) )
				return false;

			// make a temporary copy of the array
			var n = arr.slice( 0 );

			// shuffle the array before returning to make it really random
			if ( !shuffleOverride )
				n = this.shuffle( n );

			return n[ this.bitFloor( Math.random() * n.length ) ];
		},

		// using with one argument should just make a clone of the object
		extend: function () {
			var a = arguments;

			if ( a.length === 0 )
				return this.nhLog( 'extend requires at least 1 argument' );

			for ( var i = 0, l = a.length, n = Object.create( a[ 0 ] ); i < l; i++ )
				for ( var obj in a[ i ] )
					n[ obj ] = a[ i ][ obj ];

			return n;
		}
	};

	module.exports = new nh();
})();
<commit_msg>added isFunction check<commit_after>/** @preserve nodehelper
 *  @copyright 2014 Kevin von Flotow <vonflow@gmail.com>
 *  @license MIT License <http://opensource.org/licenses/MIT>
 */

;(function() {
	function nh() {
		this.logging = true;
	}

	nh.prototype = {
		set: function ( key, val ) {
			if ( this.hasOwnProperty( key ) )
				this[ key ] = val;
			else
				this.nhLog( 'set: invalid property' );
		},

		nhLog: function ( msg ) {
			return this.logging ? console.log( 'nodehelper: ' + msg.toString() ) : false;
		},

		isString: function ( str ) {
			return typeof str === 'string' || str instanceof String;
		},

		// http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric
		isNumber: function ( num ) {
			return !isNaN( parseFloat( num ) ) && isFinite( num );
		},

		isObject: function ( obj ) {
			return obj === Object( obj ) && Object.prototype.toString.call( obj ) !== '[object Array]';
		},

		isFunction: function ( obj ) {
			return Object.prototype.toString.call( obj ) === '[object Function]';
		},

		each: function ( obj, callback ) {
			if ( !obj )
				return this.nhLog( 'each: obj is required' );

			if ( !callback )
				return this.nhLog( 'each: callback is required' );
			else if ( !this.isFunction( callback ) )
				return this.nhLog( 'each: callback must be a function' );

			if ( Array.isArray( obj ) ) {
				// loops a normal array - []

				for ( var i = 0, l = obj.length; i < l; i++ )
					callback.call( obj, i, obj[ i ] );

			} else if ( obj === Object( obj ) ) {
				// loops an object - {}

				for ( var key in obj )
					callback.call( obj, key, obj[ key ] );

			} else if ( this.isNumber( obj ) ) {
				// loops a number - 23

				for ( var i = 0; i < obj; i++ )
					callback.call( obj, i );

			} else if ( this.isString( obj ) ) {
				// loops a string - 'foo'

				for ( var i = 0, l = obj.length; i < l; i++ )
					callback.call( obj, i, obj.charAt( i ) );

			} else {
				this.nhLog( 'each: invalid type' );
			}
		},

		// provide some bitwise math alternatives
		bitFloor: function ( num ) {
			return num | 0;
		},

		bitCeil: function ( num ) {
			return ( num + 1 ) | 0;
		},

		bitRound: function ( num ) {
			return ( num + 0.5 ) | 0;
		},

		// http://en.wikipedia.org/wiki/Lerp_(computing)
		// not 100% sure this is useful for nodejs - possibly smoothing out test results
		lerp: function ( fromNum, toNum, t ) {
			return fromNum + ( toNum - fromNum ) * t;
		},

		// example: nh.getPointInRange( 0.2, 0, 523 ) returns 104.6
		getPointInRange: function ( targetPoint, rangeMin, rangeMax ) {
			return ( ( rangeMax - rangeMin ) * targetPoint ) + rangeMin;
		},

		// Fisher-Yates shuffle
		// http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
		shuffle: function ( arr ) {
			if ( !arr || !Array.isArray( arr ) )
				return false;

			var n = arr.slice( 0 ),
				i = n.length,
				j, t;

			while ( --i > 0 ) {
				j = this.bitFloor( Math.random() * ( i + 1 ) );
				t = n[ j ];
				n[ j ] = n[ i ];
				n[ i ] = t;
			}

			return n;
		},

		// setting shuffleOverride to true disables the shuffle - useful for one-off randoms where performance is a concern
		randomFromArray: function ( arr, shuffleOverride ) {
			if ( !arr || !Array.isArray( arr ) )
				return false;

			// make a temporary copy of the array
			var n = arr.slice( 0 );

			// shuffle the array before returning to make it really random
			if ( !shuffleOverride )
				n = this.shuffle( n );

			return n[ this.bitFloor( Math.random() * n.length ) ];
		},

		// using with one argument should just make a clone of the object
		extend: function () {
			var a = arguments;

			if ( a.length === 0 )
				return this.nhLog( 'extend requires at least 1 argument' );

			for ( var i = 0, l = a.length, n = Object.create( a[ 0 ] ); i < l; i++ )
				for ( var obj in a[ i ] )
					n[ obj ] = a[ i ][ obj ];

			return n;
		}
	};

	module.exports = new nh();
})();
<|endoftext|>


<commit_before>const os = require("os");
const fs = require('fs');
const path = require('path');
const app = require('express')();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const bodyParser = require('body-parser')
const session = require('express-session');

app.use(require('express').static(__dirname + '/public'));
app.use(bodyParser.json());       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
    extended: true
}));
app.use(session({ secret: 'freego_2019', cookie: { maxAge: 60000 }}))
server.listen(3000, function(){
  console.log('express listening on *:3000');
});
// Access the session as req.session
app.get('/', function(req, res, next) {
  if (req.session.views) {
    req.session.views++
    res.setHeader('Content-Type', 'text/html')
    res.write('
views: ' + req.session.views + '
')
    res.write('
expires in: ' + (req.session.cookie.maxAge / 1000) + 's
')
    res.end()
  } else {
    req.session.views = 1
    res.end('welcome to the session demo. refresh!')
  }
});
io.on('connection', function (socket) {
  socket.emit('hello', 'I am sock server')
  socket.on('world', (data) => console.log(data));
});

(function start_nginx() {
  const nginx = exec( `nginx` );
  console.log(`start nginx reverse proxy`);
  nginx.stdout.on('data', data => console.log(data));
  nginx.stderr.on('data', data => console.log(data));
  nginx.on('close', (code) => {
      console.log(`nginx exited with code ${code}`);
      // restart nginx
      setTimeout(() => start_nginx(), 2000);
  });
})();<commit_msg>require child_process<commit_after>const os = require("os");
const fs = require('fs');
const { spawn, spawnSync, exec, execSync } = require('child_process');
const path = require('path');
const app = require('express')();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const bodyParser = require('body-parser')
const session = require('express-session');

app.use(require('express').static(__dirname + '/public'));
app.use(bodyParser.json());       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
    extended: true
}));
app.use(session({ secret: 'freego_2019', cookie: { maxAge: 60000 }}))
server.listen(3000, function(){
  console.log('express listening on *:3000');
});
// Access the session as req.session
app.get('/', function(req, res, next) {
  if (req.session.views) {
    req.session.views++
    res.setHeader('Content-Type', 'text/html')
    res.write('
views: ' + req.session.views + '
')
    res.write('
expires in: ' + (req.session.cookie.maxAge / 1000) + 's
')
    res.end()
  } else {
    req.session.views = 1
    res.end('welcome to the session demo. refresh!')
  }
});
io.on('connection', function (socket) {
  socket.emit('hello', 'I am sock server')
  socket.on('world', (data) => console.log(data));
});

(function start_nginx() {
  const nginx = exec( `nginx` );
  console.log(`start nginx reverse proxy`);
  nginx.stdout.on('data', data => console.log(data));
  nginx.stderr.on('data', data => console.log(data));
  nginx.on('close', (code) => {
      console.log(`nginx exited with code ${code}`);
      // restart nginx
      setTimeout(() => start_nginx(), 2000);
  });
})();<|endoftext|>


<commit_before>'use strict';

var utils = require('./utils');

/**
 * Create a new instance of the CompositionHandler for the given app and list of generators.
 *
 * ```js
 * var handler = new CompositionHandler(app, ['a', 'b', 'c']);
 * ```
 * @param {Object} `app` Application instance containing generators.
 * @param {Array} `generators` Array of generators to be iterated over.
 */

function CompositionHandler(app, generators) {
  this.app = app;
  this.generators = utils.arrayify(generators);
}

/**
 * Merge the `cache.data` object from each generator onto the `app.cache.data` object.
 * This method requires the `.data()` method from [templates].
 *
 * ```js
 * a.data({foo: 'a'});
 * b.data({foo: 'b'});
 * c.data({foo: 'c'});
 *
 * app.compose(['a', 'b', 'c'])
 *   .data();
 *
 * console.log(app.cache.data);
 * //=> {foo: 'c'}
 * ```
 * @param {String} `key` Optionally pass a key to merge from the `data` object.
 * @return {Object} Returns `this` for chaining
 * @api public
 */

CompositionHandler.prototype.data = function(key) {
  if (typeof this.app.data !== 'function') {
    throw new Error('.data expects a ".data()" method on "app"');
  }
  var data = {};
  this.iterator(function(gen, app) {
    utils.merge(data, key ? gen.data(key) : gen.cache.data);
  });
  if (key) {
    this.app.data(key, data);
  } else {
    this.app.data(data);
  }
  return this;
};

/**
 * Merge the engines from each generator into the `app` engines.
 * This method requires the `.engine()` methods from [templates].
 *
 * ```js
 * app.compose(['a', 'b', 'c'])
 *   .engines();
 * ```
 *
 * @return {Object} Returns `this` for chaining
 * @api public
 */

CompositionHandler.prototype.engines = function() {
  if (typeof this.app.engine !== 'function') {
    throw new Error('.engines expects an ".engine()" method on "app"');
  }
  var engines = {};
  this.iterator(function(gen, app) {
    utils.merge(engines, gen.engines);
  });
  utils.merge(this.app.engines, engines);
};

/**
 * Merge the helpers from each generator into the `app` helpers.
 * This method requires the `.helper` method from [templates].
 *
 * ```js
 * app.compose(['a', 'b', 'c'])
 *   .helpers();
 * ```
 *
 * @return {Object} Returns `this` for chaining
 * @api public
 */

CompositionHandler.prototype.helpers = function() {
  if (typeof this.app.helper !== 'function') {
    throw new Error('.helpers expects a ".helper()" method on "app"');
  }
  this.iterator(function(gen, app) {
    app.helpers(gen._.helpers.sync);
    app.asyncHelpers(gen._.helpers.async);
  });
  return this;
};

/**
 * Merge the options from each generator into the `app` options.
 * This method requires using the [base-option][base-option] plugin.
 *
 * ```js
 * a.option({foo: 'a'});
 * b.option({foo: 'b'});
 * c.option({foo: 'c'});
 *
 * app.compose(['a', 'b', 'c'])
 *   .options();
 *
 * console.log(app.options);
 * //=> {foo: 'c'}
 * ```
 * @param {String} `key` Optionally pass a key to merge from the `options` object.
 * @return {Object} Returns `this` for chaining
 * @api public
 */

CompositionHandler.prototype.options = function(key) {
  if (typeof this.app.option !== 'function') {
    throw new Error('.options expects an ".option()" method from "base-option" on "app"');
  }
  var options = {};
  this.iterator(function(gen, app) {
    utils.merge(options, key ? gen.option(key) : gen.options);
  });
  if (key) {
    this.app.option(key, options);
  } else {
    this.app.option(options);
  }
  return this;
};

/**
 * Copy the specified tasks from each generator into the `app` tasks.
 * Task dependencies will also be copied.
 * This method requires using the [base-task][base-task] plugin.
 *
 * ```js
 * app.compose(['a', 'b', 'c'])
 *   .tasks(['foo', 'bar', 'default']);
 * ```
 * @return {Object} Returns `this` for chaining
 * @api public
 */

CompositionHandler.prototype.tasks = function(tasks) {
  if (typeof this.app.task !== 'function') {
    throw new Error('.tasks expects a ".task()" method from "base-task" on "app"');
  }
  tasks = utils.arrayify(tasks);
  this.iterator(function(gen, app) {
    tasks.forEach(function(task) {
      utils.copyTask(gen, app, task);
    });
  });
  return this;
};

/**
 * Copy the view collections and loaded views from each generator to the `app`.
 * This method requires using an "app" inherited from [templates].
 *
 * ```js
 * app.compose(['a', 'b', 'c'])
 *   .views();
 * ```
 * @return {Object} Returns `this` for chaining
 * @api public
 */

CompositionHandler.prototype.views = function() {
  if (typeof this.app.create !== 'function') {
    throw new Error('.views expects the "app" to be inherited from "templates"');
  }
  this.iterator(function(gen, app) {
    Object.keys(gen.views).forEach(function(view) {
      if (!app[view]) {
        var collection = gen[view];
        app.create(collection.options.inflection, collection.options);
      }
      var views = gen.views[view];
      app.templates(views);
    });
  });
  return this;
};

/**
 * Iterates over the specified generators and only calls `fn` on existing generators.
 * Function passed into the iterator will be invoked with the current generator being iterated over (`gen`) and the app passed into
 * the original function. No binding is done within the iterator so the function passed in can be safely bound.
 *
 * ```js
 * app.compose(['a', 'b', 'c'])
 *   .iterator(function(gen, app) {
 *     // do work
 *     app.data(gen.cache.data);
 *   });
 *
 * // optionally, a different array of generator names may be passed as the first argument.
 * app.compose(['a', 'b', 'c'])
 *   .iterator(['d', 'e', 'f'], function(gen, app) {
 *     // do work
 *   });
 * ```
 * @name iterator
 * @param  {Array} `generators` Optional array of generator names to be looked up and iterated over.
 * @param  {Function} `fn` Function invoked with generator currently being iterated over and the app.
 * @return {Object} Returns `this` for chaining
 * @api public
 */

CompositionHandler.prototype.iterator = function() {
  return utils.createIterator(this.app, this.generators)
    .apply(this, arguments);
};

/**
 * Expose `CompositionHandler`
 */

module.exports = CompositionHandler;
<commit_msg>allow passing collection names and filter function to `.views` method<commit_after>'use strict';

var utils = require('./utils');

/**
 * Create a new instance of the CompositionHandler for the given app and list of generators.
 *
 * ```js
 * var handler = new CompositionHandler(app, ['a', 'b', 'c']);
 * ```
 * @param {Object} `app` Application instance containing generators.
 * @param {Array} `generators` Array of generators to be iterated over.
 */

function CompositionHandler(app, generators) {
  this.app = app;
  this.generators = utils.arrayify(generators);
}

/**
 * Merge the `cache.data` object from each generator onto the `app.cache.data` object.
 * This method requires the `.data()` method from [templates].
 *
 * ```js
 * a.data({foo: 'a'});
 * b.data({foo: 'b'});
 * c.data({foo: 'c'});
 *
 * app.compose(['a', 'b', 'c'])
 *   .data();
 *
 * console.log(app.cache.data);
 * //=> {foo: 'c'}
 * ```
 * @param {String} `key` Optionally pass a key to merge from the `data` object.
 * @return {Object} Returns `this` for chaining
 * @api public
 */

CompositionHandler.prototype.data = function(key) {
  if (typeof this.app.data !== 'function') {
    throw new Error('.data expects a ".data()" method on "app"');
  }
  var data = {};
  this.iterator(function(gen, app) {
    utils.merge(data, key ? gen.data(key) : gen.cache.data);
  });
  if (key) {
    this.app.data(key, data);
  } else {
    this.app.data(data);
  }
  return this;
};

/**
 * Merge the engines from each generator into the `app` engines.
 * This method requires the `.engine()` methods from [templates].
 *
 * ```js
 * app.compose(['a', 'b', 'c'])
 *   .engines();
 * ```
 *
 * @return {Object} Returns `this` for chaining
 * @api public
 */

CompositionHandler.prototype.engines = function() {
  if (typeof this.app.engine !== 'function') {
    throw new Error('.engines expects an ".engine()" method on "app"');
  }
  var engines = {};
  this.iterator(function(gen, app) {
    utils.merge(engines, gen.engines);
  });
  utils.merge(this.app.engines, engines);
};

/**
 * Merge the helpers from each generator into the `app` helpers.
 * This method requires the `.helper` method from [templates].
 *
 * ```js
 * app.compose(['a', 'b', 'c'])
 *   .helpers();
 * ```
 *
 * @return {Object} Returns `this` for chaining
 * @api public
 */

CompositionHandler.prototype.helpers = function() {
  if (typeof this.app.helper !== 'function') {
    throw new Error('.helpers expects a ".helper()" method on "app"');
  }
  this.iterator(function(gen, app) {
    app.helpers(gen._.helpers.sync);
    app.asyncHelpers(gen._.helpers.async);
  });
  return this;
};

/**
 * Merge the options from each generator into the `app` options.
 * This method requires using the [base-option][base-option] plugin.
 *
 * ```js
 * a.option({foo: 'a'});
 * b.option({foo: 'b'});
 * c.option({foo: 'c'});
 *
 * app.compose(['a', 'b', 'c'])
 *   .options();
 *
 * console.log(app.options);
 * //=> {foo: 'c'}
 * ```
 * @param {String} `key` Optionally pass a key to merge from the `options` object.
 * @return {Object} Returns `this` for chaining
 * @api public
 */

CompositionHandler.prototype.options = function(key) {
  if (typeof this.app.option !== 'function') {
    throw new Error('.options expects an ".option()" method from "base-option" on "app"');
  }
  var options = {};
  this.iterator(function(gen, app) {
    utils.merge(options, key ? gen.option(key) : gen.options);
  });
  if (key) {
    this.app.option(key, options);
  } else {
    this.app.option(options);
  }
  return this;
};

/**
 * Copy the specified tasks from each generator into the `app` tasks.
 * Task dependencies will also be copied.
 * This method requires using the [base-task][base-task] plugin.
 *
 * ```js
 * app.compose(['a', 'b', 'c'])
 *   .tasks(['foo', 'bar', 'default']);
 * ```
 * @return {Object} Returns `this` for chaining
 * @api public
 */

CompositionHandler.prototype.tasks = function(tasks) {
  if (typeof this.app.task !== 'function') {
    throw new Error('.tasks expects a ".task()" method from "base-task" on "app"');
  }
  tasks = utils.arrayify(tasks);
  this.iterator(function(gen, app) {
    tasks.forEach(function(task) {
      utils.copyTask(gen, app, task);
    });
  });
  return this;
};

/**
 * Copy the view collections and loaded views from each generator to the `app`.
 * This method requires using an "app" inherited from [templates].
 *
 * ```js
 * app.compose(['a', 'b', 'c'])
 *   .views();
 * ```
 * @return {Object} Returns `this` for chaining
 * @api public
 */

CompositionHandler.prototype.views = function(names, filter) {
  if (typeof this.app.create !== 'function') {
    throw new Error('.views expects the "app" to be inherited from "templates"');
  }

  if (typeof names === 'function') {
    filter = names;
    names = null;
  }

  names = utils.arrayify(names);

  if (typeof filter !== 'function') {
    filter = function(key, view) {
      return true;
    };
  }

  this.iterator(function(gen, app) {
    var arr = names.length ? names : Object.keys(gen.views);
    arr.forEach(function(name) {
      if (!app[name]) {
        var collection = gen[name];
        app.create(collection.options.inflection, collection.options);
      }

      var views = gen.views[name];
      var keys = Object.keys(views);
      views = keys.reduce(function(acc, key) {
        var view = views[key];
        if (filter(key, view)) {
          acc[key] = view;
        }
        return acc;
      }, {});

      app[name](views);
    });
  });
  return this;
};

/**
 * Iterates over the specified generators and only calls `fn` on existing generators.
 * Function passed into the iterator will be invoked with the current generator being iterated over (`gen`) and the app passed into
 * the original function. No binding is done within the iterator so the function passed in can be safely bound.
 *
 * ```js
 * app.compose(['a', 'b', 'c'])
 *   .iterator(function(gen, app) {
 *     // do work
 *     app.data(gen.cache.data);
 *   });
 *
 * // optionally, a different array of generator names may be passed as the first argument.
 * app.compose(['a', 'b', 'c'])
 *   .iterator(['d', 'e', 'f'], function(gen, app) {
 *     // do work
 *   });
 * ```
 * @name iterator
 * @param  {Array} `generators` Optional array of generator names to be looked up and iterated over.
 * @param  {Function} `fn` Function invoked with generator currently being iterated over and the app.
 * @return {Object} Returns `this` for chaining
 * @api public
 */

CompositionHandler.prototype.iterator = function() {
  return utils.createIterator(this.app, this.generators)
    .apply(this, arguments);
};

/**
 * Expose `CompositionHandler`
 */

module.exports = CompositionHandler;
<|endoftext|>


<commit_before>define(['atum/reference',
        'atum/value/undef'],
function(reference,
        undef) {
//"use strict";

// not functional here!
var copy = function(obj) {
    return Object.keys(obj).reduce(function(p, c) {
        p[c] = obj[c];
        return p;
    }, {});
};

/* Environment Record
 ******************************************************************************/
var EnvironmentRecord = function(bindings) {
    this.bindings = bindings;
};

EnvironmentRecord.prototype.hasBinding = function(n) {
    var bindings = this.bindings;
    return bindings && Object.getOwnPropertyDescriptor(bindings, n);
};

/**
 * Create a new environment contain a new mutable binding for 'n'
 */
EnvironmentRecord.prototype._createBinding = function(n, props) {
    if (this.hasBinding(n)) {
        throw "";
    }
    var bindings = this.bindings;
    return new EnvironmentRecord(Object.create(bindings, props));
};

/**
 * Create a new environment contain a new mutable binding for 'n'
 */
EnvironmentRecord.prototype.createMutableBinding = function(n, d) {
    var configValue = !!d;
    return this._createBinding(n, {
        'value': undefined,
        'writable': true,
        'enumerable': true,
        'configurable': configValue
    });
};

EnvironmentRecord.prototype.setMutableBinding = function(n, v, s) {
    var bindings = this.bindings;
    var current = Object.getOwnPropertyDescriptor(bindings, n) || null;
    var props = Object.defineProperty(copy(bindings), n, {'value': v});
    return new EnvironmentRecord(props);
};

EnvironmentRecord.prototype.getBindingValue = function(n, s) {
    return this.bindings[n];
};

var deleteBinding = function(n) {};

var implicitThisValue = function() {};

var createImmutableBinding = function(env, n) { };

var initializeImmutableBinding = function(n, v) {

};

/* Lexical Environment
 ******************************************************************************/
var LexicalEnvironment = function(outer, record) {
    this.record = record;
    this.outer = outer;
    Object.freeze(this);
};

/**
 *
 */
var getIdentifierReference = function(lex, name, strict) {
    if (lex === null) {
        return null;
        //return new reference.Reference(name, undefined, strict);
    }
    return (lex.record.hasBinding(name) ?
        new reference.Reference(name, lex.record, strict) :
        getIdentifierReference(lex.outer, name, strict));
};

/**
 *
 */
var putIdentifierReference = function(lex, name, value) {
    return new LexicalEnvironment(lex.outer, lex.record.setMutableBinding(name, value));
};

/**
 *
 */
var setIdentifierReference = function(lex, name, value) {
    if (lex === null) {
        return new LexicalEnvironment(null, (new EnvironmentRecord({})).setMutableBinding(name, value))
    }
    return (lex.record.hasBinding(name) ?
        new LexicalEnvironment(null, lex.record.setMutableBinding(name, value)) :
        new LexicalEnvironment(setIdentifierReference(lex.outer, name, value), lex.record));
};

/* Lexical Environment Factories
 ******************************************************************************/
/**
 *
 */
var newDeclarativeEnvironment = function(outer) {
    return new LexicalEnvironment(outer, new EnvironmentRecord({}));
};

/**
 *
 */
var newObjectEnvironment = function(o, outer) {
    return new LexicalEnvironment(outer, new EnvironmentRecord(o));
};

/* Export
 ******************************************************************************/
return {
// Environment Record
    'EnvironmentRecord': EnvironmentRecord,

// Lexical Environment
    'LexicalEnvironment': LexicalEnvironment,

    'getIdentifierReference': getIdentifierReference,
    'putIdentifierReference': putIdentifierReference,
    'setIdentifierReference': setIdentifierReference,

// Lexical Environment Factories
    'newDeclarativeEnvironment': newDeclarativeEnvironment,
    'newObjectEnvironment': newObjectEnvironment
};

});<commit_msg>Fixed issue copying old set bindings.<commit_after>define(['atum/reference',
        'atum/value/undef'],
function(reference,
        undef) {
//"use strict";

// not functional here!
var copy = function(obj) {
    return Object.keys(obj).reduce(function(p, c) {
        p[c] = obj[c];
        return p;
    }, {});
};

/* Environment Record
 ******************************************************************************/
var EnvironmentRecord = function(bindings) {
    this.bindings = bindings;
};

EnvironmentRecord.prototype.hasBinding = function(n) {
    var bindings = this.bindings;
    return bindings && Object.getOwnPropertyDescriptor(bindings, n);
};

/**
 * Create a new environment contain a new mutable binding for 'n'
 */
EnvironmentRecord.prototype._createBinding = function(n, props) {
    if (this.hasBinding(n)) {
        throw "";
    }
    var bindings = this.bindings;
    return new EnvironmentRecord(Object.create(bindings, props));
};

/**
 * Create a new environment contain a new mutable binding for 'n'
 */
EnvironmentRecord.prototype.createMutableBinding = function(n, d) {
    var configValue = !!d;
    return this._createBinding(n, {
        'value': undefined,
        'writable': true,
        'enumerable': true,
        'configurable': configValue
    });
};

EnvironmentRecord.prototype.setMutableBinding = function(n, v, s) {
    var bindings = this.bindings;
    var current = Object.getOwnPropertyDescriptor(bindings, n) || null;
    var props = Object.defineProperty(copy(bindings), n, {'value': v, 'enumerable': true});
    return new EnvironmentRecord(props);
};

EnvironmentRecord.prototype.getBindingValue = function(n, s) {
    return this.bindings[n];
};

var deleteBinding = function(n) {};

var implicitThisValue = function() {};

var createImmutableBinding = function(env, n) { };

var initializeImmutableBinding = function(n, v) {

};

/* Lexical Environment
 ******************************************************************************/
var LexicalEnvironment = function(outer, record) {
    this.record = record;
    this.outer = outer;
    Object.freeze(this);
};

/**
 *
 */
var getIdentifierReference = function(lex, name, strict) {
    if (lex === null) {
        return null;
        //return new reference.Reference(name, undefined, strict);
    }
    return (lex.record.hasBinding(name) ?
        new reference.Reference(name, lex.record, strict) :
        getIdentifierReference(lex.outer, name, strict));
};

/**
 *
 */
var putIdentifierReference = function(lex, name, value) {
    return new LexicalEnvironment(lex.outer, lex.record.setMutableBinding(name, value));
};

/**
 *
 */
var setIdentifierReference = function(lex, name, value) {
    if (lex === null) {
        return new LexicalEnvironment(null, (new EnvironmentRecord({})).setMutableBinding(name, value))
    }
    return (lex.record.hasBinding(name) ?
        new LexicalEnvironment(null, lex.record.setMutableBinding(name, value)) :
        new LexicalEnvironment(setIdentifierReference(lex.outer, name, value), lex.record));
};

/* Lexical Environment Factories
 ******************************************************************************/
/**
 *
 */
var newDeclarativeEnvironment = function(outer) {
    return new LexicalEnvironment(outer, new EnvironmentRecord({}));
};

/**
 *
 */
var newObjectEnvironment = function(o, outer) {
    return new LexicalEnvironment(outer, new EnvironmentRecord(o));
};

/* Export
 ******************************************************************************/
return {
// Environment Record
    'EnvironmentRecord': EnvironmentRecord,

// Lexical Environment
    'LexicalEnvironment': LexicalEnvironment,

    'getIdentifierReference': getIdentifierReference,
    'putIdentifierReference': putIdentifierReference,
    'setIdentifierReference': setIdentifierReference,

// Lexical Environment Factories
    'newDeclarativeEnvironment': newDeclarativeEnvironment,
    'newObjectEnvironment': newObjectEnvironment
};

});<|endoftext|>


<commit_before>'use strict';

var _ = require('underscore');
var ValuesStore = require('../../valuesStore');

var templatesInit = require('./templates');
var blocksInit = require('./blocks');
var conditionsInit = require('./conditions');
var logicalOperatorsInit = require('./logicalOperators');
var modifiersInit = require('./modifiers');

var Dialect = module.exports = function(builder) {
	this.builder = builder;

	this.blocks = new ValuesStore({context: builder});
	this.modifiers = new ValuesStore({context: builder});
	this.conditions = new ValuesStore({context: builder});
	this.logicalOperators = new ValuesStore({context: builder});
	this.templates = new ValuesStore({context: builder});

	templatesInit(this);
	blocksInit(this);
	conditionsInit(this);
	modifiersInit(this);
	logicalOperatorsInit(this);

	this.identifierPartsRegexp = new RegExp(
		'(\\' + this.config.identifierPrefix + '[^\\' + this.config.identifierSuffix + ']*\\' +
			this.config.identifierSuffix + '|[^\\.]+)', 'g'
	);
	this.wrappedIdentifierPartRegexp = new RegExp(
		'^\\' + this.config.identifierPrefix + '.*\\' + this.config.identifierSuffix + '$'
	);
};

Dialect.prototype.config = {
	identifierPrefix: '"',
	identifierSuffix: '"',
	defaultLogicalOperator: '$and',
	defaultModifier: '$set'
};

Dialect.prototype._wrapIdentifier = function(name) {
	if (this.builder.options.wrappedIdentifiers) {
		var self = this;
		var nameParts = name.match(this.identifierPartsRegexp);

		return _(nameParts).map(function(namePart) {
			if (namePart !== '*') {
				if (!self.wrappedIdentifierPartRegexp.test(namePart)) {
					namePart = self.config.identifierPrefix + namePart + self.config.identifierSuffix;
				}
			}

			return namePart;
		}).join('.');
	}

	return name;
};
<commit_msg>small codestyle fix<commit_after>'use strict';

var _ = require('underscore');
var ValuesStore = require('../../valuesStore');

var templatesInit = require('./templates');
var blocksInit = require('./blocks');
var conditionsInit = require('./conditions');
var logicalOperatorsInit = require('./logicalOperators');
var modifiersInit = require('./modifiers');

var Dialect = module.exports = function(builder) {
	this.builder = builder;

	this.blocks = new ValuesStore({context: builder});
	this.modifiers = new ValuesStore({context: builder});
	this.conditions = new ValuesStore({context: builder});
	this.logicalOperators = new ValuesStore({context: builder});
	this.templates = new ValuesStore({context: builder});

	templatesInit(this);
	blocksInit(this);
	conditionsInit(this);
	modifiersInit(this);
	logicalOperatorsInit(this);

	this.identifierPartsRegexp = new RegExp(
		'(\\' + this.config.identifierPrefix + '[^\\' + this.config.identifierSuffix + ']*\\' +
			this.config.identifierSuffix + '|[^\\.]+)', 'g'
	);
	this.wrappedIdentifierPartRegexp = new RegExp(
		'^\\' + this.config.identifierPrefix + '.*\\' + this.config.identifierSuffix + '$'
	);
};

Dialect.prototype.config = {
	identifierPrefix: '"',
	identifierSuffix: '"',
	defaultLogicalOperator: '$and',
	defaultModifier: '$set'
};

Dialect.prototype._wrapIdentifier = function(name) {
	if (this.builder.options.wrappedIdentifiers) {
		var self = this;
		var nameParts = name.match(this.identifierPartsRegexp);

		return _(nameParts).map(function(namePart) {
			if (namePart !== '*' && !self.wrappedIdentifierPartRegexp.test(namePart)) {
				namePart = self.config.identifierPrefix + namePart + self.config.identifierSuffix;
			}

			return namePart;
		}).join('.');
	}

	return name;
};
<|endoftext|>


<commit_before>var themeServer = process.env.THEME_SERVER || 'https://themes.jsonresume.org/theme/';
var registryServer = process.env.REGISTRY_SERVER || 'https://registry.jsonresume.org';
var request = require('superagent');
var http = require('http');
var fs = require('fs');
var path = require('path');
var read = require('read');
var spinner = require("char-spinner");
var chalk = require('chalk');
var puppeteer = require('puppeteer');

var SUPPORTED_FILE_FORMATS = ["html", "pdf"];

module.exports = function exportResume(resumeJson, fileName, program, callback) {
  var theme = program.theme;
  if(!theme.match('jsonresume-theme-.*')){
    theme = 'jsonresume-theme-' + theme;
  }

  if (!fileName) {
    console.error("Please enter a export destination.");
    process.exit(1);
  }

    var fileNameAndFormat = getFileNameAndFormat(fileName, program.format);
    fileName = fileNameAndFormat.fileName;
    var fileFormatToUse = fileNameAndFormat.fileFormatToUse;
    var format = "." + fileFormatToUse;
    if (format === '.html') {
      createHtml(resumeJson, fileName, theme, format, function() {
        callback(null, fileName, format);
      });
    }
    else if (format === '.pdf') {
      createPdf(resumeJson, fileName, theme, format, function (error) {
          console.error(error, "`createPdf` errored out");
          callback(error, fileName, format);
      });
    }

    else {
      console.error(`JSON Resume does not support the ${format} format`);
      process.exit(1);
    }
};

function extractFileFormat(fileName) {
  var dotPos = fileName.lastIndexOf('.');
  if (dotPos === -1) {
    return null;
  }
  return fileName.substring(dotPos + 1).toLowerCase();
}

function createHtml(resumeJson, fileName, theme, format, callback) {
  var html = renderHtml(resumeJson, theme);
  var stream = fs.createWriteStream(path.resolve(process.cwd(), fileName + format));

  stream.write(html, function() {
    stream.close(callback);
  });

}

function renderHtml(resumeJson, theme){
  var contents = '';
  try {
    var themePkg = require(theme);
  } catch (err) {
    // Theme not installed
    console.log('You have to install this theme globally to use it e.g. `npm install -g ' + theme + '`')
    process.exit();
  }
  contents = themePkg.render(resumeJson);
  return contents;
}

function createPdf(resumeJson, fileName, theme, format, callback) {
  (async () => {
    var html = renderHtml(resumeJson, theme);
    const browser = await puppeteer.launch();
    const page = await browser.newPage();

    await page.emulateMedia('screen');
    await page.goto(`data:text/html,${html}`, { waitUntil: 'networkidle0' });
    await page.pdf({path: fileName + format, format: 'Letter', printBackground: true});

    await browser.close();
  })().then(callback).catch(callback);
}

function getFileNameAndFormat(fileName, format) {
  var fileFormatFound = extractFileFormat(fileName);
  var fileFormatToUse = format;
  if (format && fileFormatFound && format === fileFormatFound) {
    fileName = fileName.substring(0, fileName.lastIndexOf('.'));
  } else if (fileFormatFound) {
    fileFormatToUse = fileFormatFound;
    fileName = fileName.substring(0, fileName.lastIndexOf('.'));
  }

  return {
    fileName: fileName,
    fileFormatToUse: fileFormatToUse
  };
}
<commit_msg>`createHtml` should `callback` when it's done.<commit_after>var themeServer = process.env.THEME_SERVER || 'https://themes.jsonresume.org/theme/';
var registryServer = process.env.REGISTRY_SERVER || 'https://registry.jsonresume.org';
var request = require('superagent');
var http = require('http');
var fs = require('fs');
var path = require('path');
var read = require('read');
var spinner = require("char-spinner");
var chalk = require('chalk');
var puppeteer = require('puppeteer');

var SUPPORTED_FILE_FORMATS = ["html", "pdf"];

module.exports = function exportResume(resumeJson, fileName, program, callback) {
  var theme = program.theme;
  if(!theme.match('jsonresume-theme-.*')){
    theme = 'jsonresume-theme-' + theme;
  }

  if (!fileName) {
    console.error("Please enter a export destination.");
    process.exit(1);
  }

    var fileNameAndFormat = getFileNameAndFormat(fileName, program.format);
    fileName = fileNameAndFormat.fileName;
    var fileFormatToUse = fileNameAndFormat.fileFormatToUse;
    var format = "." + fileFormatToUse;
    if (format === '.html') {
      createHtml(resumeJson, fileName, theme, format, function (error) {
        console.error(error, "`createHtml` errored out");
        callback(error, fileName, format);
      });
    }
    else if (format === '.pdf') {
      createPdf(resumeJson, fileName, theme, format, function (error) {
          console.error(error, "`createPdf` errored out");
          callback(error, fileName, format);
      });
    }

    else {
      console.error(`JSON Resume does not support the ${format} format`);
      process.exit(1);
    }
};

function extractFileFormat(fileName) {
  var dotPos = fileName.lastIndexOf('.');
  if (dotPos === -1) {
    return null;
  }
  return fileName.substring(dotPos + 1).toLowerCase();
}

function createHtml(resumeJson, fileName, theme, format, callback) {
  var html = renderHtml(resumeJson, theme);
  var stream = fs.createWriteStream(path.resolve(process.cwd(), fileName + format));

  stream.write(html, function (error) {
    if (error) {
      return callback(error);
    }
    stream.close(callback);
  });

}

function renderHtml(resumeJson, theme){
  var contents = '';
  try {
    var themePkg = require(theme);
  } catch (err) {
    // Theme not installed
    console.log('You have to install this theme globally to use it e.g. `npm install -g ' + theme + '`')
    process.exit();
  }
  contents = themePkg.render(resumeJson);
  return contents;
}

function createPdf(resumeJson, fileName, theme, format, callback) {
  (async () => {
    var html = renderHtml(resumeJson, theme);
    const browser = await puppeteer.launch();
    const page = await browser.newPage();

    await page.emulateMedia('screen');
    await page.goto(`data:text/html,${html}`, { waitUntil: 'networkidle0' });
    await page.pdf({path: fileName + format, format: 'Letter', printBackground: true});

    await browser.close();
  })().then(callback).catch(callback);
}

function getFileNameAndFormat(fileName, format) {
  var fileFormatFound = extractFileFormat(fileName);
  var fileFormatToUse = format;
  if (format && fileFormatFound && format === fileFormatFound) {
    fileName = fileName.substring(0, fileName.lastIndexOf('.'));
  } else if (fileFormatFound) {
    fileFormatToUse = fileFormatFound;
    fileName = fileName.substring(0, fileName.lastIndexOf('.'));
  }

  return {
    fileName: fileName,
    fileFormatToUse: fileFormatToUse
  };
}
<|endoftext|>


<commit_before>(function() {
  var applyExtra;
  var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

  applyExtra = function(Batman) {
    var buildParams, date_re, numericKeys, param, r20, rbracket;
    rbracket = /\[\]$/;
    r20 = /%20/g;
    param = function(a) {
      var add, k, name, s, v, value;
      if (typeof a === 'string') return a;
      s = [];
      add = function(key, value) {
        if (typeof value === 'function') value = value();
        return s[s.length] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
      };
      if (Batman.typeOf(a) === 'Array') {
        for (value in a) {
          name = a[value];
          add(name, value);
        }
      } else {
        for (k in a) {
          if (!__hasProp.call(a, k)) continue;
          v = a[k];
          buildParams(k, v, add);
        }
      }
      return s.join("&").replace(r20, "+");
    };
    buildParams = function(prefix, obj, add) {
      var i, name, v, _len, _results, _results2;
      if (Batman.typeOf(obj) === 'Array') {
        _results = [];
        for (i = 0, _len = obj.length; i < _len; i++) {
          v = obj[i];
          if (rbracket.test(prefix)) {
            _results.push(add(prefix, v));
          } else {
            _results.push(buildParams(prefix + "[]", v, add));
          }
        }
        return _results;
      } else if ((obj != null) && typeof obj === "object") {
        _results2 = [];
        for (name in obj) {
          _results2.push(buildParams(prefix + "[" + name + "]", obj[name], add));
        }
        return _results2;
      } else {
        return add(prefix, obj);
      }
    };
    numericKeys = [1, 2, 3, 4, 5, 6, 7, 10, 11];
    date_re = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/;
    Batman.mixin(Batman.Encoders, {
      railsDate: {
        defaultTimezoneOffset: (new Date()).getTimezoneOffset(),
        encode: function(value) {
          return value;
        },
        decode: function(value) {
          var key, minutesOffset, obj, _i, _len;
          if (value != null) {
            if ((obj = date_re.exec(value))) {
              for (_i = 0, _len = numericKeys.length; _i < _len; _i++) {
                key = numericKeys[_i];
                obj[key] = +obj[key] || 0;
              }
              obj[2] = (+obj[2] || 1) - 1;
              obj[3] = +obj[3] || 1;
              if (obj[8] !== "Z" && obj[9] !== void 0) {
                minutesOffset = obj[10] * 60 + obj[11];
                if (obj[9] === "+") minutesOffset = 0 - minutesOffset;
              } else {
                minutesOffset = Batman.Encoders.railsDate.defaultTimezoneOffset;
              }
              return new Date(Date.UTC(obj[1], obj[2], obj[3], obj[4], obj[5] + minutesOffset, obj[6], obj[7]));
            } else {
              Batman.developer.warn("Unrecognized rails date " + value + "!");
              return Date.parse(value);
            }
          }
        }
      }
    });
    return Batman.RailsStorage = (function() {

      __extends(RailsStorage, Batman.RestStorage);

      function RailsStorage() {
        RailsStorage.__super__.constructor.apply(this, arguments);
      }

      RailsStorage.prototype._serializeToFormData = function(data) {
        return param(data);
      };

      RailsStorage.prototype.urlForRecord = function() {
        return this._addJsonExtension(RailsStorage.__super__.urlForRecord.apply(this, arguments));
      };

      RailsStorage.prototype.urlForCollection = function() {
        return this._addJsonExtension(RailsStorage.__super__.urlForCollection.apply(this, arguments));
      };

      RailsStorage.prototype._addJsonExtension = function(url) {
        if (url.indexOf('?') !== -1 || url.substr(-5, 5) === '.json') return url;
        return url + '.json';
      };

      RailsStorage.prototype._errorsFrom422Response = function(response) {
        return JSON.parse(response);
      };

      RailsStorage.prototype.before('update', 'create', function(env, next) {
        if (this.serializeAsForm && !env.options.formData) {
          env.options.data = this._serializeToFormData(env.options.data);
        }
        return next();
      });

      RailsStorage.prototype.after('update', 'create', function(_arg, next) {
        var env, error, errorsArray, key, record, response, validationError, validationErrors, _i, _len, _ref;
        error = _arg.error, record = _arg.record, response = _arg.response;
        if (error) {
          if (((_ref = error.request) != null ? _ref.get('status') : void 0) === 422) {
            try {
              validationErrors = this._errorsFrom422Response(response);
            } catch (extractionError) {
              env.error = extractionError;
              return next();
            }
            for (key in validationErrors) {
              errorsArray = validationErrors[key];
              for (_i = 0, _len = errorsArray.length; _i < _len; _i++) {
                validationError = errorsArray[_i];
                record.get('errors').add(key, validationError);
              }
            }
            env = arguments[0];
            env.result = record;
            env.error = record.get('errors');
            return next();
          }
        }
        return next();
      });

      return RailsStorage;

    })();
  };

  if ((typeof module !== "undefined" && module !== null) && (typeof require !== "undefined" && require !== null)) {
    module.exports = applyExtra;
  } else {
    applyExtra(Batman);
  }

}).call(this);
<commit_msg>Build pull request changes<commit_after>(function() {
  var applyExtra;
  var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

  applyExtra = function(Batman) {
    var buildParams, date_re, numericKeys, param, r20, rbracket;
    rbracket = /\[\]$/;
    r20 = /%20/g;
    param = function(a) {
      var add, k, name, s, v, value;
      if (typeof a === 'string') return a;
      s = [];
      add = function(key, value) {
        if (typeof value === 'function') value = value();
        return s[s.length] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
      };
      if (Batman.typeOf(a) === 'Array') {
        for (value in a) {
          name = a[value];
          add(name, value);
        }
      } else {
        for (k in a) {
          if (!__hasProp.call(a, k)) continue;
          v = a[k];
          buildParams(k, v, add);
        }
      }
      return s.join("&").replace(r20, "+");
    };
    buildParams = function(prefix, obj, add) {
      var i, name, v, _len, _results, _results2;
      if (Batman.typeOf(obj) === 'Array') {
        _results = [];
        for (i = 0, _len = obj.length; i < _len; i++) {
          v = obj[i];
          if (rbracket.test(prefix)) {
            _results.push(add(prefix, v));
          } else {
            _results.push(buildParams(prefix + "[]", v, add));
          }
        }
        return _results;
      } else if ((obj != null) && typeof obj === "object") {
        _results2 = [];
        for (name in obj) {
          _results2.push(buildParams(prefix + "[" + name + "]", obj[name], add));
        }
        return _results2;
      } else {
        return add(prefix, obj);
      }
    };
    numericKeys = [1, 2, 3, 4, 5, 6, 7, 10, 11];
    date_re = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/;
    Batman.mixin(Batman.Encoders, {
      railsDate: {
        defaultTimezoneOffset: (new Date()).getTimezoneOffset(),
        encode: function(value) {
          return value;
        },
        decode: function(value) {
          var key, minutesOffset, obj, _i, _len;
          if (value != null) {
            if ((obj = date_re.exec(value))) {
              for (_i = 0, _len = numericKeys.length; _i < _len; _i++) {
                key = numericKeys[_i];
                obj[key] = +obj[key] || 0;
              }
              obj[2] = (+obj[2] || 1) - 1;
              obj[3] = +obj[3] || 1;
              if (obj[8] !== "Z" && obj[9] !== void 0) {
                minutesOffset = obj[10] * 60 + obj[11];
                if (obj[9] === "+") minutesOffset = 0 - minutesOffset;
              } else {
                minutesOffset = Batman.Encoders.railsDate.defaultTimezoneOffset;
              }
              return new Date(Date.UTC(obj[1], obj[2], obj[3], obj[4], obj[5] + minutesOffset, obj[6], obj[7]));
            } else {
              Batman.developer.warn("Unrecognized rails date " + value + "!");
              return Date.parse(value);
            }
          }
        }
      }
    });
    return Batman.RailsStorage = (function() {

      __extends(RailsStorage, Batman.RestStorage);

      function RailsStorage() {
        RailsStorage.__super__.constructor.apply(this, arguments);
      }

      RailsStorage.prototype._serializeToFormData = function(data) {
        return param(data);
      };

      RailsStorage.prototype.urlForRecord = function() {
        return this._addJsonExtension(RailsStorage.__super__.urlForRecord.apply(this, arguments));
      };

      RailsStorage.prototype.urlForCollection = function() {
        return this._addJsonExtension(RailsStorage.__super__.urlForCollection.apply(this, arguments));
      };

      RailsStorage.prototype._addJsonExtension = function(url) {
        if (url.indexOf('?') !== -1 || url.substr(-5, 5) === '.json') return url;
        return url + '.json';
      };

      RailsStorage.prototype._errorsFrom422Response = function(response) {
        return JSON.parse(response);
      };

      RailsStorage.prototype.before('update', 'create', function(env, next) {
        if (this.serializeAsForm && !env.options.formData) {
          env.options.data = this._serializeToFormData(env.options.data);
        }
        return next();
      });

      RailsStorage.prototype.after('update', 'create', function(_arg, next) {
        var env, error, errorsArray, key, record, response, validationError, validationErrors, _i, _len, _ref;
        error = _arg.error, record = _arg.record, response = _arg.response;
        env = arguments[0];
        if (error) {
          if (((_ref = error.request) != null ? _ref.get('status') : void 0) === 422) {
            try {
              validationErrors = this._errorsFrom422Response(response);
            } catch (extractionError) {
              env.error = extractionError;
              return next();
            }
            for (key in validationErrors) {
              errorsArray = validationErrors[key];
              for (_i = 0, _len = errorsArray.length; _i < _len; _i++) {
                validationError = errorsArray[_i];
                record.get('errors').add(key, validationError);
              }
            }
            env.result = record;
            env.error = record.get('errors');
            return next();
          }
        }
        return next();
      });

      return RailsStorage;

    })();
  };

  if ((typeof module !== "undefined" && module !== null) && (typeof require !== "undefined" && require !== null)) {
    module.exports = applyExtra;
  } else {
    applyExtra(Batman);
  }

}).call(this);
<|endoftext|>


<commit_before>/*
 * Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U
 *
 * This file is part of fiware-iotagent-lib
 *
 * fiware-iotagent-lib is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * fiware-iotagent-lib is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with fiware-iotagent-lib.
 * If not, seehttp://www.gnu.org/licenses/.
 *
 * For those usages not covered by the GNU Affero General Public License
 * please contact with::daniel.moranjimenez@telefonica.com
 */

'use strict';

var async = require('async'),
    apply = async.apply,
    ngsi = require('./services/ngsi/ngsiService'),
    intoTrans = require('./services/common/domain').intoTrans,
    db = require('./model/dbConn'),
    subscriptions = require('./services/ngsi/subscriptionService'),
    statsRegistry = require('./services/stats/statsRegistry'),
    domainUtils = require('./services/common/domain'),
    deviceService = require('./services/devices/deviceService'),
    groupConfig = require('./services/groups/groupService'),
    iotManager = require('./services/common/iotManagerService'),
    contextServer = require('./services/northBound/northboundServer'),
    errors = require('./errors'),
    logger = require('logops'),
    config = require('./commonConfig'),
    context = {
        op: 'IoTAgentNGSI.Global'
    };

function activateStatLogs(newConfig, callback) {
    if (newConfig.stats && newConfig.stats.interval) {
        async.series([
            apply(statsRegistry.globalLoad, {
                deviceCreationRequests: 0,
                deviceRemovalRequests: 0,
                measureRequests: 0
            }),
            apply(statsRegistry.addTimerAction, statsRegistry.logStats)
        ], callback);
    } else {
        callback();
    }
}

/**
 * Handler for uncaught global errors.
 *
 * @param {Object} err          Global error to be process.
 */
function globalErrorHandler(err) {
    logger.fatal('An unexpected exception has been raised. Ignoring: %s', err);
}

/**
 * Activates the IoT Agent to start listening for NGSI Calls (to act as a Context Provider). It also creates the
 * device registry for the IoT Agent (based on the deviceRegistry.type configuration option).
 *
 * @param {Object} newConfig            Configuration of the Context Server
 */
function doActivate(newConfig, callback) {
    var registry,
        groupRegistry;

    config.setConfig(newConfig);

    logger.format = logger.formatters.pipe;

    logger.getContext = function domainContext() {
        var domainObj = require('domain').active || {};

        return {
            corr: domainObj.corr,
            trans: domainObj.trans,
            op: domainObj.op,
            srv: domainObj.service,
            subsrv: domainObj.subservice,
            msg: domainObj.msg
        };
    };

    if (config.getConfig().logLevel) {
        logger.setLevel(config.getConfig().logLevel);
    }

    logger.info(context, 'Activating IOT Agent NGSI Library.');

    if (newConfig.deviceRegistry &&
        newConfig.deviceRegistry.type &&
        newConfig.deviceRegistry.type === 'mongodb') {
        logger.info(context, 'MongoDB Device registry selected for NGSI Library');

        registry = require('./services/devices/deviceRegistryMongoDB');
        groupRegistry = require('./services/groups/groupRegistryMongoDB');
    } else {
        logger.info(context, 'Falling back to Transient Memory registry for NGSI Library');

        registry = require('./services/devices/deviceRegistryMemory');
        groupRegistry = require('./services/groups/groupRegistryMemory');
    }

    exports.clearAll = function(callback) {
        async.series([
            registry.clear,
            groupRegistry.clear,
            ngsi.resetMiddlewares
        ], callback);
    };

    if (!config.getConfig().dieOnUnexpectedError) {
        process.on('uncaughtException', globalErrorHandler);
    }

    config.setRegistry(registry);
    config.setGroupRegistry(groupRegistry);

    async.series([
        db.configureDb,
        apply(contextServer.start, newConfig),
        apply(activateStatLogs, newConfig)
    ], callback);
}

function checkConfig(newConfig, callback) {
    var mandatory = ['providerUrl', 'types'],
        missing = [];

    for (var i in mandatory) {
        if (!newConfig[mandatory[i]]) {
            missing.push(mandatory[i]);
        }
    }

    if (missing.length === 0) {
        callback();
    } else {
        callback(new errors.MissingConfigParams(missing));
    }
}

function activate(newConfig, callback) {
    async.series([
        apply(checkConfig, newConfig),
        apply(doActivate, newConfig),
        iotManager.register
    ], callback);
}

/**
 * Stops the HTTP server.
 */
function deactivate(callback) {
    process.removeListener('uncaughtException', globalErrorHandler);
    contextServer.stop(callback);
}

exports.activate = intoTrans(context, activate);
exports.deactivate = intoTrans(context, deactivate);
exports.register = deviceService.register;
exports.updateRegister = deviceService.updateRegister;
exports.unregister = deviceService.unregister;
exports.query = ngsi.query;
exports.update = ngsi.update;
exports.setCommandResult = ngsi.setCommandResult;
exports.listDevices = deviceService.listDevices;
exports.getDevice = deviceService.getDevice;
exports.getDeviceByName = deviceService.getDeviceByName;
exports.getDevicesByAttribute = deviceService.getDevicesByAttribute;
exports.getConfiguration = groupConfig.get;
exports.findConfiguration = groupConfig.find;
exports.setDataUpdateHandler = contextServer.setUpdateHandler;
exports.setCommandHandler = contextServer.setCommandHandler;
exports.setDataQueryHandler = contextServer.setQueryHandler;
exports.setConfigurationHandler = contextServer.setConfigurationHandler;
exports.setProvisioningHandler = contextServer.setProvisioningHandler;
exports.setNotificationHandler = contextServer.setNotificationHandler;
exports.addUpdateMiddleware = ngsi.addUpdateMiddleware;
exports.addQueryMiddleware = ngsi.addQueryMiddleware;
exports.resetMiddlewares = ngsi.resetMiddlewares;
exports.statsRegistry = statsRegistry;
exports.clearRegistry = deviceService.clearRegistry;
exports.subscribe = subscriptions.subscribe;
exports.unsubscribe = subscriptions.unsubscribe;

exports.ensureSouthboundDomain = domainUtils.ensureSouthboundDomain;
exports.finishSouthBoundTransaction = domainUtils.finishSouthBoundTransaction;

exports.commandLine = require('./command/commandLine');

exports.dataPlugins = {
    compressTimestamp: require('./plugins/compressTimestamp'),
    attributeAlias: require('./plugins/attributeAlias')
};
<commit_msg>ADD Export for into_trans function<commit_after>/*
 * Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U
 *
 * This file is part of fiware-iotagent-lib
 *
 * fiware-iotagent-lib is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * fiware-iotagent-lib is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with fiware-iotagent-lib.
 * If not, seehttp://www.gnu.org/licenses/.
 *
 * For those usages not covered by the GNU Affero General Public License
 * please contact with::daniel.moranjimenez@telefonica.com
 */

'use strict';

var async = require('async'),
    apply = async.apply,
    ngsi = require('./services/ngsi/ngsiService'),
    intoTrans = require('./services/common/domain').intoTrans,
    db = require('./model/dbConn'),
    subscriptions = require('./services/ngsi/subscriptionService'),
    statsRegistry = require('./services/stats/statsRegistry'),
    domainUtils = require('./services/common/domain'),
    deviceService = require('./services/devices/deviceService'),
    groupConfig = require('./services/groups/groupService'),
    iotManager = require('./services/common/iotManagerService'),
    contextServer = require('./services/northBound/northboundServer'),
    errors = require('./errors'),
    logger = require('logops'),
    config = require('./commonConfig'),
    context = {
        op: 'IoTAgentNGSI.Global'
    };

function activateStatLogs(newConfig, callback) {
    if (newConfig.stats && newConfig.stats.interval) {
        async.series([
            apply(statsRegistry.globalLoad, {
                deviceCreationRequests: 0,
                deviceRemovalRequests: 0,
                measureRequests: 0
            }),
            apply(statsRegistry.addTimerAction, statsRegistry.logStats)
        ], callback);
    } else {
        callback();
    }
}

/**
 * Handler for uncaught global errors.
 *
 * @param {Object} err          Global error to be process.
 */
function globalErrorHandler(err) {
    logger.fatal('An unexpected exception has been raised. Ignoring: %s', err);
}

/**
 * Activates the IoT Agent to start listening for NGSI Calls (to act as a Context Provider). It also creates the
 * device registry for the IoT Agent (based on the deviceRegistry.type configuration option).
 *
 * @param {Object} newConfig            Configuration of the Context Server
 */
function doActivate(newConfig, callback) {
    var registry,
        groupRegistry;

    config.setConfig(newConfig);

    logger.format = logger.formatters.pipe;

    logger.getContext = function domainContext() {
        var domainObj = require('domain').active || {};

        return {
            corr: domainObj.corr,
            trans: domainObj.trans,
            op: domainObj.op,
            srv: domainObj.service,
            subsrv: domainObj.subservice,
            msg: domainObj.msg
        };
    };

    if (config.getConfig().logLevel) {
        logger.setLevel(config.getConfig().logLevel);
    }

    logger.info(context, 'Activating IOT Agent NGSI Library.');

    if (newConfig.deviceRegistry &&
        newConfig.deviceRegistry.type &&
        newConfig.deviceRegistry.type === 'mongodb') {
        logger.info(context, 'MongoDB Device registry selected for NGSI Library');

        registry = require('./services/devices/deviceRegistryMongoDB');
        groupRegistry = require('./services/groups/groupRegistryMongoDB');
    } else {
        logger.info(context, 'Falling back to Transient Memory registry for NGSI Library');

        registry = require('./services/devices/deviceRegistryMemory');
        groupRegistry = require('./services/groups/groupRegistryMemory');
    }

    exports.clearAll = function(callback) {
        async.series([
            registry.clear,
            groupRegistry.clear,
            ngsi.resetMiddlewares
        ], callback);
    };

    if (!config.getConfig().dieOnUnexpectedError) {
        process.on('uncaughtException', globalErrorHandler);
    }

    config.setRegistry(registry);
    config.setGroupRegistry(groupRegistry);

    async.series([
        db.configureDb,
        apply(contextServer.start, newConfig),
        apply(activateStatLogs, newConfig)
    ], callback);
}

function checkConfig(newConfig, callback) {
    var mandatory = ['providerUrl', 'types'],
        missing = [];

    for (var i in mandatory) {
        if (!newConfig[mandatory[i]]) {
            missing.push(mandatory[i]);
        }
    }

    if (missing.length === 0) {
        callback();
    } else {
        callback(new errors.MissingConfigParams(missing));
    }
}

function activate(newConfig, callback) {
    async.series([
        apply(checkConfig, newConfig),
        apply(doActivate, newConfig),
        iotManager.register
    ], callback);
}

/**
 * Stops the HTTP server.
 */
function deactivate(callback) {
    process.removeListener('uncaughtException', globalErrorHandler);
    contextServer.stop(callback);
}

exports.activate = intoTrans(context, activate);
exports.deactivate = intoTrans(context, deactivate);
exports.register = deviceService.register;
exports.updateRegister = deviceService.updateRegister;
exports.unregister = deviceService.unregister;
exports.query = ngsi.query;
exports.update = ngsi.update;
exports.setCommandResult = ngsi.setCommandResult;
exports.listDevices = deviceService.listDevices;
exports.getDevice = deviceService.getDevice;
exports.getDeviceByName = deviceService.getDeviceByName;
exports.getDevicesByAttribute = deviceService.getDevicesByAttribute;
exports.getConfiguration = groupConfig.get;
exports.findConfiguration = groupConfig.find;
exports.setDataUpdateHandler = contextServer.setUpdateHandler;
exports.setCommandHandler = contextServer.setCommandHandler;
exports.setDataQueryHandler = contextServer.setQueryHandler;
exports.setConfigurationHandler = contextServer.setConfigurationHandler;
exports.setProvisioningHandler = contextServer.setProvisioningHandler;
exports.setNotificationHandler = contextServer.setNotificationHandler;
exports.addUpdateMiddleware = ngsi.addUpdateMiddleware;
exports.addQueryMiddleware = ngsi.addQueryMiddleware;
exports.resetMiddlewares = ngsi.resetMiddlewares;
exports.statsRegistry = statsRegistry;
exports.clearRegistry = deviceService.clearRegistry;
exports.subscribe = subscriptions.subscribe;
exports.unsubscribe = subscriptions.unsubscribe;
exports.intoTrans = intoTrans;

exports.ensureSouthboundDomain = domainUtils.ensureSouthboundDomain;
exports.finishSouthBoundTransaction = domainUtils.finishSouthBoundTransaction;

exports.commandLine = require('./command/commandLine');

exports.dataPlugins = {
    compressTimestamp: require('./plugins/compressTimestamp'),
    attributeAlias: require('./plugins/attributeAlias')
};
<|endoftext|>


<commit_before>var Spec02 = require("../../specs/spec_0_2.js");

const spec02 = new Spec02();

function JSONParser(_spec) {
  this.spec = (_spec) ? _spec : new Spec02();
}

/**
 * Level 0 of validation: is that string? is that JSON?
 */
function validate_and_parse_as_json(payload) {
  var json = payload;

  if(payload) {
    if( (typeof payload) == "string"){
      try {
        json = JSON.parse(payload);

      }catch(e) {
        throw {message: "invalid json payload", errors: e};
      }

    } else if( (typeof payload) != "object"){
      // anything else
      throw {message: "invalid payload type, allowed are: string or object"};
    }
  } else {
    throw {message: "null or undefined payload"};
  }

  return json;
}

/*
 * Level 1 of validation: is that follow a spec?
 */
function validate_spec(payload, spec) {

  // is that follow the spec?
  spec.check(payload);

  return payload;
}

JSONParser.prototype.parse = function(payload) {

  // Level 0 of validation: is that string? is that JSON?
  var valid0 = validate_and_parse_as_json(payload);

  // Level 1 of validation: is that follow a spec?
  var valid1 = validate_spec(valid0, this.spec);

  return valid1;
}

module.exports = JSONParser;
<commit_msg>Remove the responsability of spec checking<commit_after>function JSONParser() {

}

/**
 * Level 0 of validation: is that string? is that JSON?
 */
function validate_and_parse_as_json(payload) {
  var json = payload;

  if(payload) {
    if( (typeof payload) == "string"){
      try {
        json = JSON.parse(payload);

      }catch(e) {
        throw {message: "invalid json payload", errors: e};
      }

    } else if( (typeof payload) != "object"){
      // anything else
      throw {message: "invalid payload type, allowed are: string or object"};
    }
  } else {
    throw {message: "null or undefined payload"};
  }

  return json;
}

/*
 * Level 1 of validation: is that follow a spec?
 */
function validate_spec(payload, spec) {

  // is that follow the spec?
  spec.check(payload);

  return payload;
}

JSONParser.prototype.parse = function(payload) {

  //is that string? is that JSON?
  var valid = validate_and_parse_as_json(payload);

  return valid;
}

module.exports = JSONParser;
<|endoftext|>


<commit_before>const { wikidataTimeToISOString, wikidataTimeToEpochTime } = require('./helpers')

const simple = datavalue => datavalue.value
const monolingualtext = (datavalue, options) => {
  return options.keepRichValues ? datavalue.value : datavalue.value.text
}
const item = (datavalue, options) => prefixedId(datavalue, options.entityPrefix)
const property = (datavalue, options) => {
  return prefixedId(datavalue, options.propertyPrefix)
}
const entityLetter = {
  item: 'Q',
  property: 'P'
}
const prefixedId = function (datavalue, prefix) {
  const { value } = datavalue
  const id = value.id || entityLetter[value['entity-type']] + value['numeric-id']
  return typeof prefix === 'string' ? `${prefix}:${id}` : id
}
const quantity = (datavalue, options) => {
  const { value } = datavalue
  const amount = parseFloat(value.amount)
  if (options.keepRichValues) {
    const amount = parseFloat(value.amount)
    const unit = value.unit.replace('http://www.wikidata.org/entity/', '')
    const upperBound = parseFloat(value.upperBound)
    const lowerBound = parseFloat(value.lowerBound)
    return { amount, unit, upperBound, lowerBound }
  } else {
    return amount
  }
}
const coordinate = datavalue => {
  return [ datavalue.value.latitude, datavalue.value.longitude ]
}
const time = (datavalue, options) => {
  return getTimeConverter(options.timeConverter)(datavalue.value.time)
}
const getTimeConverter = (key = 'iso') => timeConverters[key]
const identity = arg => arg

const timeConverters = {
  iso: wikidataTimeToISOString,
  epoch: wikidataTimeToEpochTime,
  none: identity
}

const claimParsers = {
  string: simple,
  commonsMedia: simple,
  url: simple,
  'external-id': simple,
  math: simple,
  monolingualtext,
  'wikibase-item': item,
  'wikibase-property': property,
  time,
  quantity,
  'globe-coordinate': coordinate,
  'geo-shape': simple,
  'tabular-data': simple
}

module.exports = (datatype, datavalue, options) => {
  // If you get an error like 'TypeError: claimParsers[datatype] is not a function'
  // it means that the current datatype isn't supported yet:
  // please report to https://github.com/maxlath/wikidata-sdk/issues
  return claimParsers[datatype](datavalue, options)
}
<commit_msg>parse_claims: cleaning<commit_after>const { wikidataTimeToISOString, wikidataTimeToEpochTime } = require('./helpers')

const simple = datavalue => datavalue.value

const monolingualtext = (datavalue, options) => {
  return options.keepRichValues ? datavalue.value : datavalue.value.text
}

const item = (datavalue, options) => prefixedId(datavalue, options.entityPrefix)

const property = (datavalue, options) => {
  return prefixedId(datavalue, options.propertyPrefix)
}

const entityLetter = { item: 'Q', property: 'P' }
const prefixedId = function (datavalue, prefix) {
  const { value } = datavalue
  const id = value.id || entityLetter[value['entity-type']] + value['numeric-id']
  return typeof prefix === 'string' ? `${prefix}:${id}` : id
}

const quantity = (datavalue, options) => {
  const { value } = datavalue
  const amount = parseFloat(value.amount)
  if (options.keepRichValues) {
    const amount = parseFloat(value.amount)
    const unit = value.unit.replace('http://www.wikidata.org/entity/', '')
    const upperBound = parseFloat(value.upperBound)
    const lowerBound = parseFloat(value.lowerBound)
    return { amount, unit, upperBound, lowerBound }
  } else {
    return amount
  }
}

const coordinate = datavalue => {
  return [ datavalue.value.latitude, datavalue.value.longitude ]
}

const time = (datavalue, options) => {
  return getTimeConverter(options.timeConverter)(datavalue.value.time)
}

const getTimeConverter = (key = 'iso') => timeConverters[key]

const identity = arg => arg

const timeConverters = {
  iso: wikidataTimeToISOString,
  epoch: wikidataTimeToEpochTime,
  none: identity
}

const claimParsers = {
  string: simple,
  commonsMedia: simple,
  url: simple,
  'external-id': simple,
  math: simple,
  monolingualtext,
  'wikibase-item': item,
  'wikibase-property': property,
  time,
  quantity,
  'globe-coordinate': coordinate,
  'geo-shape': simple,
  'tabular-data': simple
}

module.exports = (datatype, datavalue, options) => {
  // If you get an error like 'TypeError: claimParsers[datatype] is not a function'
  // it means that the current datatype isn't supported yet:
  // please report to https://github.com/maxlath/wikidata-sdk/issues
  return claimParsers[datatype](datavalue, options)
}
<|endoftext|>


<commit_before>
var integration = require('../integration')
  , load = require('load-script')
  , user = require('../user');

/**
 * Expose `AdRoll` integration.
 */

var AdRoll = module.exports = integration('AdRoll');

/**
 * Default options.
 */

AdRoll.prototype.defaults = {
  // your adroll advertiser id (required)
  advId: '',
  // your adroll pixel id (required)
  pixId: ''
};

/**
 * Initialize.
 *
 * @param {Object} options
 * @param {Function} ready
 */

AdRoll.prototype._initialize = function (options, ready) {
  window.adroll_adv_id = options.advId;
  window.adroll_pix_id = options.pixId;
  window.adroll_custom_data = user.traits();
  if (user.id()) window.adroll_custom_data.id = user.id();
  window.__adroll_loaded = true;

  load({
    http: 'http://a.adroll.com/j/roundtrip.js',
    https: 'https://s.adroll.com/j/roundtrip.js'
  }, ready);
};

/**
 * Page.
 *
 * @param {String} name (optional)
 * @param {Object} properties (optional)
 * @param {Object} options (optional)
 */

AdRoll.prototype.page = function (name, properties, options) {
  if (!this.initialized) this.page();
};
<commit_msg>adroll: updated for page<commit_after>
var integration = require('../integration');
var load = require('load-script');
var user = require('../user');

/**
 * Expose `AdRoll` integration.
 */

var AdRoll = module.exports = integration('AdRoll');

/**
 * Default options.
 */

AdRoll.prototype.defaults = {
  // your adroll advertiser id (required)
  advId: '',
  // your adroll pixel id (required)
  pixId: ''
};

/**
 * Load the AdRoll script.
 */

AdRoll.prototype.load = function () {
  load({
    http: 'http://a.adroll.com/j/roundtrip.js',
    https: 'https://s.adroll.com/j/roundtrip.js'
  }, this.ready);
};

/**
 * Initialize.
 *
 * @param {Object} options
 * @param {Function} ready
 */

AdRoll.prototype._initialize = function (options, ready) {
  var id = user.id();
  var traits = user.traits();
  if (id) traits.id = id;

  window.adroll_adv_id = options.advId;
  window.adroll_pix_id = options.pixId;
  window.adroll_custom_data = traits;
  window.__adroll_loaded = true;
};

/**
 * Page.
 *
 * @param {String} name (optional)
 * @param {Object} properties (optional)
 * @param {Object} options (optional)
 */

AdRoll.prototype.page = function (name, properties, options) {
  this.load();
};
<|endoftext|>