<commit_before>//whole class that manages timers
//not an entity, just an object
game.GameTimerManager = Object.extend({
	//uses same functions as usual
	//constructor function
	init: function(x, y, settings){
		//setting key variables
		this.now = new Date().getTime();
		//keeps track of the last creep that spawned
		this.lastCreep = new Date().getTime();
		//new paused function
		this.paused = false;
		//keeps program updating
		this.alwaysUpdate = true;
	},
	//updates at the end
	update: function(){
		//keeps track of timer
		this.now = new Date().getTime();
		//call to the goldTimerCheck function
		this.goldTimerCheck();
		//call to the creepTimerCheck function
		this.creepTimerCheck();

		return true;
	},

	//new goldTimerCheck function
	goldTimerCheck: function(){
		//keeps track of the amount of gold you get per creep
		//rounds to 20 on one second interval
		//makes sure creeps dont spawn within a second
		if(Math.round(this.now/1000)%20 ===0 && (this.now - this.lastCreep >= 1000)){
			//gives exp1 + 1 gold
			game.data.gold += (game.data.exp1+1);
			console.log("Current gold: " + game.data.gold);
		}
	},

	//new creepTimerCheck function
	creepTimerCheck: function(){
		//keeps track of if it needs to make a new creep
		//rounds to 10 on one second interval
		//makes sure creeps dont spawn within a second
		if(Math.round(this.now/1000)%10 ===0 && (this.now - this.lastCreep >= 1000)){
			//updates timer to this.now
			this.lastCreep = this.now;
			//builds creep
			var creepe = me.pool.pull("EnemyCreep", 1000, 0, {});
			//adds creep into the world
			me.game.world.addChild(creepe, 5);
		}
	}
});

//HeroDeathManager class being created
game.HeroDeathManager = Object.extend({
	//new init function
	//parameters are x, y, and settings
	init: function(x, y, settings){
		//always updates function
		this.alwaysUpdate = true;
	},

	//new update function
	update: function(){
		//if player dies...
		if(game.data.player.dead){
			//removes character from the map
			me.game.world.removeChild(game.data.player);
			//respawns player at (10, 0)
			me.state.current().resetPlayer(10, 0);
		}
		//tells update to actually do stuff
		return true;
	}
});

//ExperienceManager class being created
game.ExperienceManager = Object.extend({
	//new init function
	init: function(x, y, settings){
		//always updates function
		this.alwaysUpdate = true;
		//game is not over initially
		this.gameover = false;
	},

	//new update function
	update: function(){
		//if I win...
		//and game isnt over
		if(game.data.win === true && !this.gameover){
			//call to gameOver function
			//passes true
			this.gameOver(true);
		}
		//if I lose...
		//and game isnt over
		else if(game.data.win === false && !this.gameover){
			//call to gameOver function
			//passes false
			this.gameOver(false);
		}

		//tells update to actually do stuff
		return true;

	},

	//new gameOver function
	//passes win
	gameOver: function(win){
		//if player wins
		if(win){
			//adds 10 experience
			game.data.exp += 10;
		}
		else{
			//adds 1 experience
			game.data.exp += 1;
		}

		//game is over if player wins
		this.gameOver = true;
		//saves current game variable of experience into save variable
		me.save.exp =  game.data.exp;
		//only for testing purposes
		me.save.exp2 = 4;
	}

});

//new SpendGold object
game.SpendGold = Object.extend({
	//new init function
	init: function(x, y, settings){
		//sets game to current time
		this.now = new Date().getTime();
		//keeps track of last time u bought something
		this.lastBuy = new Date().getTime();
		//game isnt paused
		this.paused = false;
		//awlays updates game
		this.alwaysUpdate = true;
		//updates when paused
		this.updateWhenPaused = true;
		//are not currently buying
		this.buying = false;
	},

	//new update function
	update: function(){
		//updates timers
		this.now = new Date().getTime();
		//if buy button is pressed...
		//and its been one second since last buy...
		if(me.input.isKeyPressed("buy") && this.now-this.lastBuy >=1000){
			//last buy was now
			this.lastBuy = this.now;
			//if you are not currently buying...
			if(!this.buying){
				//calls startBuying function
				this.startBuying();
			}
			else{
				//calls stopBuying
				this.stopBuying();
			}
		}
		return true;
	},

	//new startBuying function
	startBuying: function(){
		this.buying = true;
		//when you start buying, game will pause
		me.state.pause(me.state.PLAY);
		//sets pausePos to current location
		game.data.pausePos = me.game.viewport.localToWorld(0, 0);
		//makes screen a new sprite
		//sets x and y position
		//gets image
		game.data.buyscreen = new me.Sprite(game.data.pausePos.x, game.data.pausePos.y, me.loader.getImage('gold-screen'));
		//updates when screen is up
		game.data.buyscreen.updateWhenPaused = true;
		//makes buy screen opague
		game.data.buyscreen.setOpacity(0.8);
		//adds screen to the game
		me.game.world.addChild(game.data.buyscreen, 34)
		//makes sure player doesnt move when game is paused
		game.data.player.body.setVelocity(0, 0);
		me.state.pause(me.state.PLAY);
		//setting up keys
		//binding f1-f6 keys
		me.input.bindKey(me.input.KEY.F1, "F1", true);
		me.input.bindKey(me.input.KEY.F2, "F2", true);
		me.input.bindKey(me.input.KEY.F3, "F3", true);
		me.input.bindKey(me.input.KEY.F4, "F4", true);
		me.input.bindKey(me.input.KEY.F5, "F5", true);
		me.input.bindKey(me.input.KEY.F6, "F6", true);
		//calls setBuyText function
		this.setBuyText();
	},

	//new setBuyText function
	setBuyText: function(){
		//making something stored in buytext
		game.data.buytext = new (me.Renderable.extend({
			//new init function
			init: function(){
				//call to super class
				//passes in info
				//sets text location
				this._super(me.Renderable, 'init', [game.data.pausePos.x, game.data.pausePos.y, 300, 50]);
				//font settings
				this.font = new me.Font("Arial", 26, "white");
				//updates when game is paused
				this.updateWhenPaused = true;
				//always updates game
				this.alwaysUpdate = true;
			},

			//renderable uses draw function
			//passes renderer
			draw: function(renderer){
				//draws what you want to write on the screen and the coordinates of it
				//adding new coords for text
				this.font.draw(renderer.getContext(), "PRESS F1-F6 TO BUY, B TO EXIT.  Current Gold: " + game.data.gold, this.pos.x, this.pos.y);
				this.font.draw(renderer.getContext(), "Skill 1: Increase Damage. Current Level: " + game.data.skill1 + "Cost: " + ((game.data.skill1+1)*10), this.pos.x, this.pos.y + 40);
				this.font.draw(renderer.getContext(), "Skill 2: Run Faster.  Current Level: " + game.data.skill2 + "Cost: " + ((game.data.skill2+1)*10), this.pos.x, this.pos.y + 80);
				this.font.draw(renderer.getContext(), "Skill 3: Increase Health.  Current Level: " + game.data.skill3 + "Cost: " + ((game.data.skill3+1)*10), this.pos.x, this.pos.y + 120);
				this.font.draw(renderer.getContext(), "Q Ability: Speed Burst.  Current Level: " + game.data.ability1 + "Cost: " + ((game.data.ability1+1)*10), this.pos.x, this.pos.y + 160);
				this.font.draw(renderer.getContext(), "W Ability: Eat Your Creep For Health: " + game.data.ability2 + "Cost: " + ((game.data.ability2+1)*10), this.pos.x, this.pos.y + 200);
				this.font.draw(renderer.getContext(), "E Ability: Throw Your Spear: " + game.data.ability3 + "Cost: " + ((game.data.ability3+1)*10), this.pos.x, this.pos.y + 240);
			}

		}));
		//adds buytext variable to game
		me.game.world.addChild(game.data.buytext, 35);
	},

	//new stopBuying function
	stopBuying: function(){
		this.buying = false;
		//when you stop buying, game will start
		me.state.resume(me.state.PLAY);
		//returns normal speed to player when unpaused
		game.data.player.body.setVelocity(game.data.playerMoveSpeed, 20);
		//removes buy screen when game is unpaused
		me.game.removeChild(game.data.buyscreen);
		//unbinding f1-f6 keys
		me.input.unbindKey(me.input.KEY.F1, "F1", true);
		me.input.unbindKey(me.input.KEY.F2, "F2", true);
		me.input.unbindKey(me.input.KEY.F3, "F3", true);
		me.input.unbindKey(me.input.KEY.F4, "F4", true);
		me.input.unbindKey(me.input.KEY.F5, "F5", true);
		me.input.unbindKey(me.input.KEY.F6, "F6", true);
		//removes buytext from game
		me.game.world.removeChild(game.data.buytext);
	}
});<commit_msg>vid 49 comments<commit_after>//whole class that manages timers
//not an entity, just an object
game.GameTimerManager = Object.extend({
	//uses same functions as usual
	//constructor function
	init: function(x, y, settings){
		//setting key variables
		this.now = new Date().getTime();
		//keeps track of the last creep that spawned
		this.lastCreep = new Date().getTime();
		//new paused function
		this.paused = false;
		//keeps program updating
		this.alwaysUpdate = true;
	},
	//updates at the end
	update: function(){
		//keeps track of timer
		this.now = new Date().getTime();
		//call to the goldTimerCheck function
		this.goldTimerCheck();
		//call to the creepTimerCheck function
		this.creepTimerCheck();

		return true;
	},

	//new goldTimerCheck function
	goldTimerCheck: function(){
		//keeps track of the amount of gold you get per creep
		//rounds to 20 on one second interval
		//makes sure creeps dont spawn within a second
		if(Math.round(this.now/1000)%20 ===0 && (this.now - this.lastCreep >= 1000)){
			//gives exp1 + 1 gold
			game.data.gold += (game.data.exp1+1);
			console.log("Current gold: " + game.data.gold);
		}
	},

	//new creepTimerCheck function
	creepTimerCheck: function(){
		//keeps track of if it needs to make a new creep
		//rounds to 10 on one second interval
		//makes sure creeps dont spawn within a second
		if(Math.round(this.now/1000)%10 ===0 && (this.now - this.lastCreep >= 1000)){
			//updates timer to this.now
			this.lastCreep = this.now;
			//builds creep
			var creepe = me.pool.pull("EnemyCreep", 1000, 0, {});
			//adds creep into the world
			me.game.world.addChild(creepe, 5);
		}
	}
});

//HeroDeathManager class being created
game.HeroDeathManager = Object.extend({
	//new init function
	//parameters are x, y, and settings
	init: function(x, y, settings){
		//always updates function
		this.alwaysUpdate = true;
	},

	//new update function
	update: function(){
		//if player dies...
		if(game.data.player.dead){
			//removes character from the map
			me.game.world.removeChild(game.data.player);
			//respawns player at (10, 0)
			me.state.current().resetPlayer(10, 0);
		}
		//tells update to actually do stuff
		return true;
	}
});

//ExperienceManager class being created
game.ExperienceManager = Object.extend({
	//new init function
	init: function(x, y, settings){
		//always updates function
		this.alwaysUpdate = true;
		//game is not over initially
		this.gameover = false;
	},

	//new update function
	update: function(){
		//if I win...
		//and game isnt over
		if(game.data.win === true && !this.gameover){
			//call to gameOver function
			//passes true
			this.gameOver(true);
		}
		//if I lose...
		//and game isnt over
		else if(game.data.win === false && !this.gameover){
			//call to gameOver function
			//passes false
			this.gameOver(false);
		}

		//tells update to actually do stuff
		return true;

	},

	//new gameOver function
	//passes win
	gameOver: function(win){
		//if player wins
		if(win){
			//adds 10 experience
			game.data.exp += 10;
		}
		else{
			//adds 1 experience
			game.data.exp += 1;
		}

		//game is over if player wins
		this.gameOver = true;
		//saves current game variable of experience into save variable
		me.save.exp =  game.data.exp;
		//only for testing purposes
		me.save.exp2 = 4;
	}

});

//new SpendGold object
game.SpendGold = Object.extend({
	//new init function
	init: function(x, y, settings){
		//sets game to current time
		this.now = new Date().getTime();
		//keeps track of last time u bought something
		this.lastBuy = new Date().getTime();
		//game isnt paused
		this.paused = false;
		//awlays updates game
		this.alwaysUpdate = true;
		//updates when paused
		this.updateWhenPaused = true;
		//are not currently buying
		this.buying = false;
	},

	//new update function
	update: function(){
		//updates timers
		this.now = new Date().getTime();
		//if buy button is pressed...
		//and its been one second since last buy...
		if(me.input.isKeyPressed("buy") && this.now-this.lastBuy >=1000){
			//last buy was now
			this.lastBuy = this.now;
			//if you are not currently buying...
			if(!this.buying){
				//calls startBuying function
				this.startBuying();
			}
			else{
				//calls stopBuying
				this.stopBuying();
			}
		}
		return true;
	},

	//new startBuying function
	startBuying: function(){
		this.buying = true;
		//when you start buying, game will pause
		me.state.pause(me.state.PLAY);
		//sets pausePos to current location
		game.data.pausePos = me.game.viewport.localToWorld(0, 0);
		//makes screen a new sprite
		//sets x and y position
		//gets image
		game.data.buyscreen = new me.Sprite(game.data.pausePos.x, game.data.pausePos.y, me.loader.getImage('gold-screen'));
		//updates when screen is up
		game.data.buyscreen.updateWhenPaused = true;
		//makes buy screen opague
		game.data.buyscreen.setOpacity(0.8);
		//adds screen to the game
		me.game.world.addChild(game.data.buyscreen, 34)
		//makes sure player doesnt move when game is paused
		game.data.player.body.setVelocity(0, 0);
		me.state.pause(me.state.PLAY);
		//setting up keys
		//binding f1-f6 keys
		me.input.bindKey(me.input.KEY.F1, "F1", true);
		me.input.bindKey(me.input.KEY.F2, "F2", true);
		me.input.bindKey(me.input.KEY.F3, "F3", true);
		me.input.bindKey(me.input.KEY.F4, "F4", true);
		me.input.bindKey(me.input.KEY.F5, "F5", true);
		me.input.bindKey(me.input.KEY.F6, "F6", true);
		//calls setBuyText function
		this.setBuyText();
	},

	//new setBuyText function
	setBuyText: function(){
		//making something stored in buytext
		game.data.buytext = new (me.Renderable.extend({
			//new init function
			init: function(){
				//call to super class
				//passes in info
				//sets text location
				this._super(me.Renderable, 'init', [game.data.pausePos.x, game.data.pausePos.y, 300, 50]);
				//font settings
				this.font = new me.Font("Arial", 26, "white");
				//updates when game is paused
				this.updateWhenPaused = true;
				//always updates game
				this.alwaysUpdate = true;
			},

			//renderable uses draw function
			//passes renderer
			draw: function(renderer){
				//draws what you want to write on the screen and the coordinates of it
				//adding new coords for text
				//spaces out text by 40s
				this.font.draw(renderer.getContext(), "PRESS F1-F6 TO BUY, B TO EXIT.  Current Gold: " + game.data.gold, this.pos.x, this.pos.y);
				//skill 1 text
				this.font.draw(renderer.getContext(), "Skill 1: Increase Damage. Current Level: " + game.data.skill1 + "Cost: " + ((game.data.skill1+1)*10), this.pos.x, this.pos.y + 40);
				//skill 2 text
				this.font.draw(renderer.getContext(), "Skill 2: Run Faster.  Current Level: " + game.data.skill2 + "Cost: " + ((game.data.skill2+1)*10), this.pos.x, this.pos.y + 80);
				//skill 3 text
				this.font.draw(renderer.getContext(), "Skill 3: Increase Health.  Current Level: " + game.data.skill3 + "Cost: " + ((game.data.skill3+1)*10), this.pos.x, this.pos.y + 120);
				//ability 1 text
				this.font.draw(renderer.getContext(), "Q Ability: Speed Burst.  Current Level: " + game.data.ability1 + "Cost: " + ((game.data.ability1+1)*10), this.pos.x, this.pos.y + 160);
				//ability 2 text
				this.font.draw(renderer.getContext(), "W Ability: Eat Your Creep For Health: " + game.data.ability2 + "Cost: " + ((game.data.ability2+1)*10), this.pos.x, this.pos.y + 200);
				//ability 3 text
				this.font.draw(renderer.getContext(), "E Ability: Throw Your Spear: " + game.data.ability3 + "Cost: " + ((game.data.ability3+1)*10), this.pos.x, this.pos.y + 240);
			}

		}));
		//adds buytext variable to game
		me.game.world.addChild(game.data.buytext, 35);
	},

	//new stopBuying function
	stopBuying: function(){
		this.buying = false;
		//when you stop buying, game will start
		me.state.resume(me.state.PLAY);
		//returns normal speed to player when unpaused
		game.data.player.body.setVelocity(game.data.playerMoveSpeed, 20);
		//removes buy screen when game is unpaused
		me.game.removeChild(game.data.buyscreen);
		//unbinding f1-f6 keys
		me.input.unbindKey(me.input.KEY.F1, "F1", true);
		me.input.unbindKey(me.input.KEY.F2, "F2", true);
		me.input.unbindKey(me.input.KEY.F3, "F3", true);
		me.input.unbindKey(me.input.KEY.F4, "F4", true);
		me.input.unbindKey(me.input.KEY.F5, "F5", true);
		me.input.unbindKey(me.input.KEY.F6, "F6", true);
		//removes buytext from game
		me.game.world.removeChild(game.data.buytext);
	}
});<|endoftext|>


<commit_before>'use strict'

var util = require('util')
var path = require('path')

var color = require('bash-color')
var mongojs = require('mongojs')

var startup = (new Date()).toISOString()
var requestID = 0
var lastMessage = (new Date()).toISOString()
var messageID = 0

module.exports = makeConsole
module.exports.output = output
module.exports.redirect = redirect
module.exports.console = makeConsole
module.exports.root = root
module.exports.rootPath = process.cwd()

module.exports.requests = requests
module.exports.errors = errors
module.exports.handleGlobalErrors = handleGlobalErrors

function makeConsole(filename, startTime) {
  var csl = {}
  csl.log = logger(filename, startTime, 'log')
  csl.info = logger(filename, startTime, 'info')
  csl.warn = logger(filename, startTime, 'warn')
  csl.error = logger(filename, startTime, 'error')
  csl.time = function () {
    return makeConsole(filename, new Date())
  }
  return csl
}

function logger(filename, start, level) {
  return function (type, obj) {
    var result = {type: type, timestamp: new Date()}
    if (type === 'server/request') {
      obj = obj.req
      obj.__chronicle_id__ = startup + '-' + (requestID++)
      obj.__chronicle_start__ = new Date()
      result.requestID = obj.__chronicle_id__
      result.httpVersion = obj.httpVersion
      result.headers = obj.headers
      result.method = obj.method
      result.url = obj.url
    } else if (type === 'server/response') {
      result.requestID = obj.req.__chronicle_id__
      result.statusCode = obj.res.statusCode
      result.duration = ((new Date()) - obj.req.__chronicle_start__)
    } else if (obj instanceof Error) {
      result.message = obj.stack || obj.message
      result.raw = true
    } else if (typeof obj === 'string') {
      result.message = obj
      result.raw = true
    } else {
      obj = clone(obj)
      for (var key in obj) {
        result[key] = obj[key]
      }
    }
    if (obj.req && obj.req.__chronicle_id__) {
      result.requestID = obj.req.__chronicle_id__
      if ('req' in result) delete result.req
    }
    if (start) {
      result.duration = ((new Date()) - start)
    }
    if (filename) {
      result.filename = filename
    }
    if (level) {
      result.level = level
    }
    module.exports.output(result)
  }
}

var loggingRequests = {}
function output(message, indent, callback) {
  indent = indent || ''
  if (message.requestID && message.type === 'server/request') {
    loggingRequests[message.requestID] = {
      req: message,
      logs: [],
      res: null,
      timeout: setTimeout(function () {
        loggingRequests[message.requestID].res = {type: 'server/timeout', level: 'warn', timestamp: new Date()}
        outputRequest(message.requestID)
      }, 60000)
    }
    return
  } else if (message.requestID && message.type === 'server/response' && loggingRequests[message.requestID]) {
    clearTimeout(loggingRequests[message.requestID].timeout)
    loggingRequests[message.requestID].res = message
    outputRequest(message.requestID)
    return
  } else if (message.requestID && loggingRequests[message.requestID]) {
    loggingRequests[message.requestID].logs.push(message)
    return
  }

  var _log = console[message.level] || console.log
  function log(str) {
    _log(str.toString().replace(/^/gm, indent))
  }
  var duration = message.duration ? color.purple(' (' + message.duration + 'ms)') : ''
  var type = color.cyan(message.type) + ' '
  switch (message.type) {
    case 'db/call':
      log(type + message.name + '(' + message.args.map(formatInline).join(', ') + ')' + duration)
      break
    case 'db/update':
      var index = 0
      log(type + message.statement.replace(/\?/g, function () {
        return formatInline(message.values[index++])
      }) + duration)
      break
    case 'cache/invalidate':
    case 'cache/get':
    case 'cache/set':
      log(type + formatInline(message.partition) + ' ' + formatInline(message.row))
      break
    case 'email/sent':
      log(type + formatInline(message.subject) + ' to ' + formatInline(message.to))
      break
    case 'email/batch':
      log(type + ' size: ' + formatInline(message.size))
      break
    default:
      log(type + duration)
      indent += '  '
      log(message.raw ? message.message : util.inspect(message, false, 10, true))
  }
  if (typeof callback === 'function') {
    setTimeout(callback, 0)
  }
}
function outputRequest(requestID) {
  if (!loggingRequests[requestID]) return
  clearTimeout(loggingRequests[requestID].timeout)
  var msg = loggingRequests[requestID]
  loggingRequests[requestID] = null

  var log = console[msg.res.level] || console.log
  var c = 'green'
  if (msg.res.statusCode >= 300 && msg.res.statusCode < 400) {
    c = 'purple'
  } else if (msg.res.statusCode >= 400 && msg.res.statusCode < 500) {
    c = 'yellow'
  } else if (msg.res.statusCode >= 500 || !msg.res.statusCode) {
    c = 'red'
  }
  console.log(msg.req.method.toUpperCase() + ' ' + color[c](msg.res.statusCode || 'TIMEOUT') + ' ' + msg.req.url
    + color.purple(' (' + (msg.res.duration || (msg.res.timestamp - msg.req.timestamp)) + 'ms)'))
  for (var i = 0; i < msg.logs.length; i++) {
    output(msg.logs[i], '  ')
  }
}

function formatInline(arg) {
  return util.inspect(arg, false, 3, true).replace(/^ */gm, '').replace(/ *$/gm, ' ').replace(/\n/g, '').trim()
}

function redirect(db, collection) {
  if (db !== undefined) {
    db = mongojs(db, [collection || 'chronicle'])
    module.exports.output = function (message, indent, callback) {
      var timestamp = (new Date()).toISOString()
      if (timestamp !== lastMessage) {
        lastMessage = timestamp
        messageID++
      }
      message._id = timestamp + '-' + (messageID++)
      if (message.filename) {
        message.filename = path.relative(module.exports.rootPath, message.filename)
      }
      db[collection || 'chronicle'].insert(message, function (err) {
        if (err) console.error(err.stack || err.message || err)
        if (typeof callback === 'function') {
          callback(err)
        }
      })
    }
  }
  return module.exports
}
function root(path) {
  module.exports.rootPath = path
  return module.exports
}
function requests(filename) {
  return function (req, res, next) {
    logger(filename, null, 'log')('server/request', {req: req})
    var end = res.end;
    res.end = function(chunk, encoding){
      res.end = end;
      res.end(chunk, encoding);
      logger(filename, null, res.statusCode >= 400 ? 'error' : 'log')('server/response', {
        req: req,
        res: res
      })
    };
    next()
  }
}
function errors(filename, options) {
  return function (err, req, res, next) {
    logger(filename, null, 'error')('server/error', {
      message: err.stack || err.message || err,
      raw: true,
      req: req
    })
    if (!(options && options.last)) next(err)
  }
}

function handleGlobalErrors() {
  process.once('uncaughtException', onUncaughtException);
  module.exports.handleGlobalErrors = function () {}
  return module.exports
}

function onUncaughtException(err) {
  output({
    type: 'application/crash',
    level: 'error',
    message: err.stack || err.message || err,
    raw: true,
    timestamp: new Date()
  }, '', function () {
    throw err
  })
}

function clone(obj, circular) {
  circular = circular || []
  if (typeof obj !== 'object') {
    return obj
  }
  if (Array.isArray(obj)) {
    obj = obj.map(function (v) {
      if (circular.indexOf(v) != -1) return undefined
      circular.push(v)
      return v
    })
    for (var i = 0; i < obj.length; i++) {
      obj[i] = clone(obj[i], circular)
    }
    return obj
  } else if (obj) {
    var res = {}
    for (var key in obj) {
      if (circular.indexOf(obj[key]) != -1) {
        res[key] = undefined
      } else {
        circular.push(obj[key])
        res[key] = obj[key]
      }
    }
    for (var key in res) {
      res[key] = clone(res[key], circular)
    }
    return res
  } else {
    return obj
  }
}<commit_msg>Fix bug in removing circular references<commit_after>'use strict'

var util = require('util')
var path = require('path')

var color = require('bash-color')
var mongojs = require('mongojs')

var startup = (new Date()).toISOString()
var requestID = 0
var lastMessage = (new Date()).toISOString()
var messageID = 0

module.exports = makeConsole
module.exports.output = output
module.exports.redirect = redirect
module.exports.console = makeConsole
module.exports.root = root
module.exports.rootPath = process.cwd()

module.exports.requests = requests
module.exports.errors = errors
module.exports.handleGlobalErrors = handleGlobalErrors

function makeConsole(filename, startTime) {
  var csl = {}
  csl.log = logger(filename, startTime, 'log')
  csl.info = logger(filename, startTime, 'info')
  csl.warn = logger(filename, startTime, 'warn')
  csl.error = logger(filename, startTime, 'error')
  csl.time = function () {
    return makeConsole(filename, new Date())
  }
  return csl
}

function logger(filename, start, level) {
  return function (type, obj) {
    var result = {type: type, timestamp: new Date()}
    if (type === 'server/request') {
      obj = obj.req
      obj.__chronicle_id__ = startup + '-' + (requestID++)
      obj.__chronicle_start__ = new Date()
      result.requestID = obj.__chronicle_id__
      result.httpVersion = obj.httpVersion
      result.headers = obj.headers
      result.method = obj.method
      result.url = obj.url
    } else if (type === 'server/response') {
      result.requestID = obj.req.__chronicle_id__
      result.statusCode = obj.res.statusCode
      result.duration = ((new Date()) - obj.req.__chronicle_start__)
    } else if (obj instanceof Error) {
      result.message = obj.stack || obj.message
      result.raw = true
    } else if (typeof obj === 'string') {
      result.message = obj
      result.raw = true
    } else {
      obj = clone(obj)
      for (var key in obj) {
        result[key] = obj[key]
      }
    }
    if (obj.req && obj.req.__chronicle_id__) {
      result.requestID = obj.req.__chronicle_id__
      if ('req' in result) delete result.req
    }
    if (start) {
      result.duration = ((new Date()) - start)
    }
    if (filename) {
      result.filename = filename
    }
    if (level) {
      result.level = level
    }
    module.exports.output(result)
  }
}

var loggingRequests = {}
function output(message, indent, callback) {
  indent = indent || ''
  if (message.requestID && message.type === 'server/request') {
    loggingRequests[message.requestID] = {
      req: message,
      logs: [],
      res: null,
      timeout: setTimeout(function () {
        loggingRequests[message.requestID].res = {type: 'server/timeout', level: 'warn', timestamp: new Date()}
        outputRequest(message.requestID)
      }, 60000)
    }
    return
  } else if (message.requestID && message.type === 'server/response' && loggingRequests[message.requestID]) {
    clearTimeout(loggingRequests[message.requestID].timeout)
    loggingRequests[message.requestID].res = message
    outputRequest(message.requestID)
    return
  } else if (message.requestID && loggingRequests[message.requestID]) {
    loggingRequests[message.requestID].logs.push(message)
    return
  }

  var _log = console[message.level] || console.log
  function log(str) {
    _log(str.toString().replace(/^/gm, indent))
  }
  var duration = message.duration ? color.purple(' (' + message.duration + 'ms)') : ''
  var type = color.cyan(message.type) + ' '
  switch (message.type) {
    case 'db/call':
      log(type + message.name + '(' + message.args.map(formatInline).join(', ') + ')' + duration)
      break
    case 'db/update':
      var index = 0
      log(type + message.statement.replace(/\?/g, function () {
        return formatInline(message.values[index++])
      }) + duration)
      break
    case 'cache/invalidate':
    case 'cache/get':
    case 'cache/set':
      log(type + formatInline(message.partition) + ' ' + formatInline(message.row))
      break
    case 'email/sent':
      log(type + formatInline(message.subject) + ' to ' + formatInline(message.to))
      break
    case 'email/batch':
      log(type + ' size: ' + formatInline(message.size))
      break
    default:
      log(type + duration)
      indent += '  '
      log(message.raw ? message.message : util.inspect(message, false, 10, true))
  }
  if (typeof callback === 'function') {
    setTimeout(callback, 0)
  }
}
function outputRequest(requestID) {
  if (!loggingRequests[requestID]) return
  clearTimeout(loggingRequests[requestID].timeout)
  var msg = loggingRequests[requestID]
  loggingRequests[requestID] = null

  var log = console[msg.res.level] || console.log
  var c = 'green'
  if (msg.res.statusCode >= 300 && msg.res.statusCode < 400) {
    c = 'purple'
  } else if (msg.res.statusCode >= 400 && msg.res.statusCode < 500) {
    c = 'yellow'
  } else if (msg.res.statusCode >= 500 || !msg.res.statusCode) {
    c = 'red'
  }
  console.log(msg.req.method.toUpperCase() + ' ' + color[c](msg.res.statusCode || 'TIMEOUT') + ' ' + msg.req.url
    + color.purple(' (' + (msg.res.duration || (msg.res.timestamp - msg.req.timestamp)) + 'ms)'))
  for (var i = 0; i < msg.logs.length; i++) {
    output(msg.logs[i], '  ')
  }
}

function formatInline(arg) {
  return util.inspect(arg, false, 3, true).replace(/^ */gm, '').replace(/ *$/gm, ' ').replace(/\n/g, '').trim()
}

function redirect(db, collection) {
  if (db !== undefined) {
    db = mongojs(db, [collection || 'chronicle'])
    module.exports.output = function (message, indent, callback) {
      var timestamp = (new Date()).toISOString()
      if (timestamp !== lastMessage) {
        lastMessage = timestamp
        messageID++
      }
      message._id = timestamp + '-' + (messageID++)
      if (message.filename) {
        message.filename = path.relative(module.exports.rootPath, message.filename)
      }
      db[collection || 'chronicle'].insert(message, function (err) {
        if (err) console.error(err.stack || err.message || err)
        if (typeof callback === 'function') {
          callback(err)
        }
      })
    }
  }
  return module.exports
}
function root(path) {
  module.exports.rootPath = path
  return module.exports
}
function requests(filename) {
  return function (req, res, next) {
    logger(filename, null, 'log')('server/request', {req: req})
    var end = res.end;
    res.end = function(chunk, encoding){
      res.end = end;
      res.end(chunk, encoding);
      logger(filename, null, res.statusCode >= 400 ? 'error' : 'log')('server/response', {
        req: req,
        res: res
      })
    };
    next()
  }
}
function errors(filename, options) {
  return function (err, req, res, next) {
    logger(filename, null, 'error')('server/error', {
      message: err.stack || err.message || err,
      raw: true,
      req: req
    })
    if (!(options && options.last)) next(err)
  }
}

function handleGlobalErrors() {
  process.once('uncaughtException', onUncaughtException);
  module.exports.handleGlobalErrors = function () {}
  return module.exports
}

function onUncaughtException(err) {
  output({
    type: 'application/crash',
    level: 'error',
    message: err.stack || err.message || err,
    raw: true,
    timestamp: new Date()
  }, '', function () {
    throw err
  })
}

function clone(obj, circular) {
  circular = circular || []
  if (typeof obj !== 'object') {
    return obj
  }
  if (Array.isArray(obj)) {
    obj = obj.map(function (v) {
      if (typeof v !== 'object') return v
      if (circular.indexOf(v) != -1) return undefined
      circular.push(v)
      return v
    })
    for (var i = 0; i < obj.length; i++) {
      obj[i] = clone(obj[i], circular)
    }
    return obj
  } else if (obj) {
    var res = {}
    for (var key in obj) {
      if (typeof v !== 'object') {
        res[key] = obj[key]
      } else if (circular.indexOf(obj[key]) != -1) {
        res[key] = undefined
      } else {
        circular.push(obj[key])
        res[key] = obj[key]
      }
    }
    for (var key in res) {
      res[key] = clone(res[key], circular)
    }
    return res
  } else {
    return obj
  }
}<|endoftext|>


<commit_before>var NormalDistribution = require('../NormalDistribution');
var Penalties = require('../Penalties');
var random = require('seeded-random');

/*
 * Class which generates a football match score.
 */
function Match(teamA, teamB, options) {
    options = options || {};

    this.period = {
        PRE_KICK_OFF: 0,
        FIRST_HALF: 1,
        HALF_TIME: 2,
        SECOND_HALF: 3,
        PRE_EXTRA_TIME: 4,
        EXTRA_TIME_FIRST_HALF: 5,
        EXTRA_TIME_HALF_TIME: 6,
        EXTRA_TIME_SECOND_HALF: 7,
        PRE_PENALTIES: 8,
        PENALTIES: 9,
        FULL_TIME: 10
    };
    this.team = [teamA, teamB];
    this.winner;
    this.ratingDifference = teamA.rating - teamB.rating;

    this.mean = 1.58;
    this.sd = 1.23;
    this.constant = 0.00245;

    this.extraTimeEnabled = options.extraTime || false;
    this.penaltiesEnabled = options.penalties || false;

    this.seed = options.seed || Math.random() + '';
    this.goals = [[], []];
    // 0 = team A win, 0.5 = draw, 1 = team B win.
    this.result;
    this.text;

    this.graph = [
        new NormalDistribution(this.mean + (this.ratingDifference * this.constant), this.sd),
        new NormalDistribution(this.mean - (this.ratingDifference * this.constant), this.sd)
    ];
    this.penalties = new Penalties(this.seed);
}

(function (static_, proto_) {

    /*
     * Generates a match score from the given seed.
     */
    proto_.simulate = function () {
        var extraTime = false;

        this.penalties.simulate();

        // Loop through all of the teams and set
        // their goals scored.
        for (var i = 0; i < 2; i += 1) {
            this.goals[i][this.period.FIRST_HALF] = this._goalsScored(i, 0, 45);
            this.goals[i][this.period.SECOND_HALF] = this._goalsScored(i, 45, 90);
            this.goals[i][this.period.PENALTIES] = this.penalties.goals[i];
            this.goals[i][this.period.FULL_TIME] = this.goals[i][this.period.FIRST_HALF] + this.goals[i][this.period.SECOND_HALF];

            // If the match is a draw and extra time is enabled.
            if (this.extraTimeEnabled && this.goals[0][this.period.FULL_TIME] === this.goals[1][this.period.FULL_TIME]) {
                extraTime = true;

                this.goals[i][this.period.EXTRA_TIME_FIRST_HALF] = this._goalsScored(i, 90, 105);
                this.goals[i][this.period.EXTRA_TIME_SECOND_HALF] = this._goalsScored(i, 105, 120);
                this.goals[i][this.period.FULL_TIME += this.goals[i][this.period.EXTRA_TIME_FIRST_HALF] + this.goals[i][this.period.EXTRA_TIME_SECOND_HALF]];
            }
        }

        // Calculate result. 1 = win, 0.5 = draw,
        // 0 = loss.
        if (this.goals[0][this.period.FULL_TIME] > this.goals[1][this.period.FULL_TIME]) {
            this.result = 0;
        }
        else if (this.goals[0][this.period.FULL_TIME] === this.goals[1][this.period.FULL_TIME]) {
            this.result = 0.5;
        }
        else {
            this.result = 1;
        }

        // If it's still a draw and penalties are enabled.
        if (this.penaltiesEnabled && this.goals[0][this.period.FULL_TIME] === this.goals[1][this.period.FULL_TIME]) {
            if (this.goals[0][this.period.PENALTIES] > this.goals[1][this.period.PENALTIES]) {
                this.result = 0;
            }
            else {
                this.result = 1;
            }
        }
        else {
            delete this.goals[0][this.period.PENALTIES];
            delete this.goals[1][this.period.PENALTIES];
        }

        this.winner = this._getWinner();

        // Create the output text
        this.text = this._outputText(extraTime);
    };

    /*
     * Finds the number of goals scored by a team.
     */
    proto_._goalsScored = function (team, startTime, endTime) {
        rand = random.decimal(this.seed + ' ' + team + ' ' + startTime + ' ' + endTime);
        time = endTime - startTime || 90;

        var graph = this.graph[team];
        var goals = 0;
        var mean = graph.mean;
        var xValue = -10 + mean;
        var standardDeviation = graph.standardDeviation;

        graph.mean = mean * (time / 90);
        graph.standardDeviation = standardDeviation * (time / 90);

        while (rand > graph.trapeziumRule(xValue, goals + 0.5, 0.1)) {
            goals += 1;
        }

        graph.mean = mean;
        graph.standardDeviation = standardDeviation;

        return goals;
    };

    /*
     * Gets winner.
     */
    proto_._getWinner = function () {
        if (this.result !== 0.5) {
            return this.team[this.result];
        }

        return null;
    };

    /*
     * Method which generates the output string.
     */
    proto_._outputText = function (extraTime) {
        var text = this.team[0].stringName + ' ' + this.goals[0][this.period.FULL_TIME] + '-' + this.goals[1][this.period.FULL_TIME] + ' ' + this.team[1].stringName;

        if (extraTime) {
            text += ' (aet)';
        }

        if (this.penaltiesEnabled && this.goals[0][this.period.FULL_TIME] === this.goals[1][this.period.FULL_TIME]) {
            text += ' (' + this.goals[0][this.period.PENALTIES] + '-' + this.goals[1][this.period.PENALTIES] + ')';
        }

        return text;
    };

}(Match, Match.prototype));

module.exports = Match;
<commit_msg>Fixes extra time undefined goals bug<commit_after>var NormalDistribution = require('../NormalDistribution');
var Penalties = require('../Penalties');
var random = require('seeded-random');

/*
 * Class which generates a football match score.
 */
function Match(teamA, teamB, options) {
    options = options || {};

    this.period = {
        PRE_KICK_OFF: 0,
        FIRST_HALF: 1,
        HALF_TIME: 2,
        SECOND_HALF: 3,
        PRE_EXTRA_TIME: 4,
        EXTRA_TIME_FIRST_HALF: 5,
        EXTRA_TIME_HALF_TIME: 6,
        EXTRA_TIME_SECOND_HALF: 7,
        PRE_PENALTIES: 8,
        PENALTIES: 9,
        FULL_TIME: 10
    };
    this.team = [teamA, teamB];
    this.winner;
    this.ratingDifference = teamA.rating - teamB.rating;

    this.mean = 1.58;
    this.sd = 1.23;
    this.constant = 0.00245;

    this.extraTimeEnabled = options.extraTime || false;
    this.penaltiesEnabled = options.penalties || false;

    this.seed = options.seed || Math.random() + '';
    this.goals = [[], []];
    // 0 = team A win, 0.5 = draw, 1 = team B win.
    this.result;
    this.text;

    this.graph = [
        new NormalDistribution(this.mean + (this.ratingDifference * this.constant), this.sd),
        new NormalDistribution(this.mean - (this.ratingDifference * this.constant), this.sd)
    ];
    this.penalties = new Penalties(this.seed);
}

(function (static_, proto_) {

    /*
     * Generates a match score from the given seed.
     */
    proto_.simulate = function () {
        var extraTime = false;

        this.penalties.simulate();

        // Loop through all of the teams and set
        // their goals scored.
        for (var i = 0; i < 2; i += 1) {
            this.goals[i][this.period.FIRST_HALF] = this._goalsScored(i, 0, 45);
            this.goals[i][this.period.SECOND_HALF] = this._goalsScored(i, 45, 90);
            this.goals[i][this.period.PENALTIES] = this.penalties.goals[i];
            this.goals[i][this.period.FULL_TIME] = this.goals[i][this.period.FIRST_HALF] + this.goals[i][this.period.SECOND_HALF];
        }
        // If the match is a draw and extra time is enabled.
        if (this.extraTimeEnabled && this.goals[0][this.period.FULL_TIME] === this.goals[1][this.period.FULL_TIME]) {
            extraTime = true;

            for (var i = 0; i < 2; i += 1) {
                this.goals[i][this.period.EXTRA_TIME_FIRST_HALF] = this._goalsScored(i, 90, 105);
                this.goals[i][this.period.EXTRA_TIME_SECOND_HALF] = this._goalsScored(i, 105, 120);
                this.period.FULL_TIME += this.goals[i][this.period.EXTRA_TIME_FIRST_HALF] + this.goals[i][this.period.EXTRA_TIME_SECOND_HALF];
            }
        }

        // Calculate result. 1 = win, 0.5 = draw,
        // 0 = loss.
        if (this.goals[0][this.period.FULL_TIME] > this.goals[1][this.period.FULL_TIME]) {
            this.result = 0;
        }
        else if (this.goals[0][this.period.FULL_TIME] === this.goals[1][this.period.FULL_TIME]) {
            this.result = 0.5;
        }
        else {
            this.result = 1;
        }

        // If it's still a draw and penalties are enabled.
        if (this.penaltiesEnabled && this.goals[0][this.period.FULL_TIME] === this.goals[1][this.period.FULL_TIME]) {
            if (this.goals[0][this.period.PENALTIES] > this.goals[1][this.period.PENALTIES]) {
                this.result = 0;
            }
            else {
                this.result = 1;
            }
        }
        else {
            delete this.goals[0][this.period.PENALTIES];
            delete this.goals[1][this.period.PENALTIES];
        }

        this.winner = this._getWinner();

        // Create the output text
        this.text = this._outputText(extraTime);
    };

    /*
     * Finds the number of goals scored by a team.
     */
    proto_._goalsScored = function (team, startTime, endTime) {
        rand = random.decimal(this.seed + ' ' + team + ' ' + startTime + ' ' + endTime);
        time = endTime - startTime || 90;

        var graph = this.graph[team];
        var goals = 0;
        var mean = graph.mean;
        var xValue = -10 + mean;
        var standardDeviation = graph.standardDeviation;

        graph.mean = mean * (time / 90);
        graph.standardDeviation = standardDeviation * (time / 90);

        while (rand > graph.trapeziumRule(xValue, goals + 0.5, 0.1)) {
            goals += 1;
        }

        graph.mean = mean;
        graph.standardDeviation = standardDeviation;

        return goals;
    };

    /*
     * Gets winner.
     */
    proto_._getWinner = function () {
        if (this.result !== 0.5) {
            return this.team[this.result];
        }

        return null;
    };

    /*
     * Method which generates the output string.
     */
    proto_._outputText = function (extraTime) {
        var text = this.team[0].stringName + ' ' + this.goals[0][this.period.FULL_TIME] + '-' + this.goals[1][this.period.FULL_TIME] + ' ' + this.team[1].stringName;

        if (extraTime) {
            text += ' (aet)';
        }

        if (this.penaltiesEnabled && this.goals[0][this.period.FULL_TIME] === this.goals[1][this.period.FULL_TIME]) {
            text += ' (' + this.goals[0][this.period.PENALTIES] + '-' + this.goals[1][this.period.PENALTIES] + ')';
        }

        return text;
    };

}(Match, Match.prototype));

module.exports = Match;
<|endoftext|>


<commit_before>require('proof')(2, prove)

function prove (okay, callback) {
    var Destructible = require('destructible')
    var destructible = new Destructible('t/olio.bin.t')

    destructible.completed.wait(callback)

    var bin = require('../olio.bin')
    var fs = require('fs')

    try {
        fs.unlinkSync('t/socket')
    } catch (e) {
        if (e.code != 'ENOENT') {
            throw e
        }
    }

    var UserAgent = require('vizsla')
    var ua = new UserAgent

    var cadence = require('cadence')

    var relative = cadence(function (async, destructible) {
        var program = bin([ '--configuration', './t/configuration.js' ], destructible.monitor('bin'))
        async(function () {
            async(function () {
                program.ready.wait(async())
            }, function () {
                setTimeout(async(), 250)
            }, function () {
                okay('relative')
                program.emit('SIGINT')
            })
        })
    })

    var path = require('path')
    var absolute = cadence(function (async, destructible) {
        var program = bin([
            '--configuration', path.resolve(__dirname, './configuration.js')
        ], destructible.monitor('bin'))
        async(function () {
            async(function () {
                program.ready.wait(async())
            }, function () {
                setTimeout(async(), 250)
            }, function () {
                okay('absolute')
                program.emit('SIGINT')
            })
        })
    })

    cadence(function (async) {
        async(function () {
            destructible.monitor('relative', true, relative, async())
        }, function () {
            setTimeout(async(), 250)
        }, function () {
            destructible.monitor('absolute', true, absolute, async())
        })
    })(destructible.monitor('test'))
}
<commit_msg>More time to start for Travis CI.<commit_after>require('proof')(2, prove)

function prove (okay, callback) {
    var Destructible = require('destructible')
    var destructible = new Destructible('t/olio.bin.t')

    destructible.completed.wait(callback)

    var bin = require('../olio.bin')
    var fs = require('fs')

    try {
        fs.unlinkSync('t/socket')
    } catch (e) {
        if (e.code != 'ENOENT') {
            throw e
        }
    }

    var UserAgent = require('vizsla')
    var ua = new UserAgent

    var cadence = require('cadence')

    var relative = cadence(function (async, destructible) {
        var program = bin([ '--configuration', './t/configuration.js' ], destructible.monitor('bin'))
        async(function () {
            async(function () {
                program.ready.wait(async())
            }, function () {
                setTimeout(async(), 1000)
            }, function () {
                okay('relative')
                program.emit('SIGINT')
            })
        })
    })

    var path = require('path')
    var absolute = cadence(function (async, destructible) {
        var program = bin([
            '--configuration', path.resolve(__dirname, './configuration.js')
        ], destructible.monitor('bin'))
        async(function () {
            async(function () {
                program.ready.wait(async())
            }, function () {
                setTimeout(async(), 1000)
            }, function () {
                okay('absolute')
                program.emit('SIGINT')
            })
        })
    })

    cadence(function (async) {
        async(function () {
            destructible.monitor('relative', true, relative, async())
        }, function () {
            setTimeout(async(), 250)
        }, function () {
            destructible.monitor('absolute', true, absolute, async())
        })
    })(destructible.monitor('test'))
}
<|endoftext|>


<commit_before>module.exports = (function () {
  var Vue = require("Vue");

  var MediumEditorComponent = Vue.extend({
    template: "
<textarea v-model=\"content\"></textarea>
",

    props: ["content"],

    ready: function () {
      var self = this;
      var MediumEditor = require("medium-editor");

      var editorToDataSync = function (data, editable) {
        self.content = editable.innerHTML;
      };

      this.editor = new MediumEditor(this.$el.children[0]);
      this.editor.subscribe("editableInput", editorToDataSync);

      this.$on("data-updated", function () {
        this.editor.setContent(this.content);
      });
    }
  });

  return MediumEditorComponent;
})();
<commit_msg>Fixed component to update editor on changes to data from parent<commit_after>module.exports = (function () {
  var Vue = require("Vue");

  var MediumEditorComponent = Vue.extend({
    template: "
<textarea v-model=\"content\"></textarea>
",

    props: ["content"],

    ready: function () {
      var self = this;
      var MediumEditor = require("medium-editor");

      var editorToDataSync = function (data, editable) {
        self.content = editable.innerHTML;
      };

      this.editor = new MediumEditor(this.$el.children[0]);
      this.editor.subscribe("editableInput", editorToDataSync);

      this.$watch("content", function () {
        this.editor.setContent(this.content);
      });
    }
  });

  return MediumEditorComponent;
})();
<|endoftext|>


<commit_before>// Nick Mai 2015

var mailin = require('mailin')
var fs = require('fs')

// Cleanup
var msgcount = 0

/* Start the Mailin server. The available options are:
 *  options = {
 *     port: 25,
 *     webhook: 'http://mydomain.com/mailin/incoming,
 *     disableWebhook: false,
 *     logFile: '/some/local/path',
 *     logLevel: 'warn', // One of silly, info, debug, warn, error
 *     smtpOptions: { // Set of options directly passed to simplesmtp.createServer(smtpOptions)
 *        SMTPBanner: 'Hi from a custom Mailin instance',
 *        // By default, the DNS validation of the sender and recipient domains is disabled so.
 *        // You can enable it as follows:
 *        disableDNSValidation: false
 *     }
 *  };
 * Here disable the webhook posting so that you can do what you want with the
 * parsed message. */
mailin.start({
  port: 25,
  disableWebhook: true // Disable the webhook posting.
})

/* Event emitted after a message was received and parsed. */
mailin.on('message', function (connection, data, content) {
  // Not interested in 'content' because this is the raw email.
  // 'data' represents the parsed email.

  saveMessage(connection, data)
})

function saveMessage (data) {
  // JS Standard wants each declaration as a separate statement
  var from = connection.from
  var to = connection.to
  var subject = data.subject
  var cc = data.cc
  var body = data.envelopeFrom.text

  console.log('----Received New Message----')
  console.log('From: ' + from.name + '(' + from.address + ')')
  console.log('To: ' + to.name + '(' + to.address + ')')
  console.log('CC: ' + cc)
  console.log('Subject: ' + subject)
  console.log('----')
  console.log(body)
  console.log('----End Message----')

  try {
    fs.writeFile(parseInt(msgCount) + '.json', data, function (){
      console.log('Wrote message #' + parseInt(msgcount) + 'to disk.')
    })
  } catch (err) {
    console.log(err)
  }
}
<commit_msg>Fixed undefined var bugs<commit_after>// Nick Mai 2015

var mailin = require('mailin')
var fs = require('fs')

// Cleanup
var msgcount = 0

/* Start the Mailin server. The available options are:
 *  options = {
 *     port: 25,
 *     webhook: 'http://mydomain.com/mailin/incoming,
 *     disableWebhook: false,
 *     logFile: '/some/local/path',
 *     logLevel: 'warn', // One of silly, info, debug, warn, error
 *     smtpOptions: { // Set of options directly passed to simplesmtp.createServer(smtpOptions)
 *        SMTPBanner: 'Hi from a custom Mailin instance',
 *        // By default, the DNS validation of the sender and recipient domains is disabled so.
 *        // You can enable it as follows:
 *        disableDNSValidation: false
 *     }
 *  };
 * Here disable the webhook posting so that you can do what you want with the
 * parsed message. */
mailin.start({
  port: 25,
  disableWebhook: true // Disable the webhook posting.
})

/* Event emitted after a message was received and parsed. */
mailin.on('message', function (connection, data, content) {
  // Not interested in 'content' because this is the raw email.
  // 'data' represents the parsed email.

  saveMessage(connection, data)
})

function saveMessage (connection, data) {
  // JS Standard wants each declaration as a separate statement
  var from = connection.from
  var to = connection.to
  var subject = data.subject
  var cc = data.cc
  var body = data.envelopeFrom.text

  console.log('----Received New Message----')
  console.log('From: ' + from.name + '(' + from.address + ')')
  console.log('To: ' + to.name + '(' + to.address + ')')
  console.log('CC: ' + cc)
  console.log('Subject: ' + subject)
  console.log('----')
  console.log(body)
  console.log('----End Message----')

  try {
    fs.writeFile(parseInt(msgcount) + '.json', data, function (){
      console.log('Wrote message #' + parseInt(msgcount) + 'to disk.')
    })
  } catch (err) {
    console.log(err)
  }
}
<|endoftext|>


<commit_before>import React from 'react'
import Search from './Search'
import { shallow } from 'enzyme'
import { shallowToJson } from 'enzyme-to-json'

test('Search snapshot test', () => {
  const component = shallow(<Search />)
  const tree = shallowToJson(component)
  expect(tree).toMatchSnapshot()
})<commit_msg>Search should render a ShowCard for each show and render correct number of shows based on search word.<commit_after>import React from 'react'
import { shallow } from 'enzyme'
import { shallowToJson } from 'enzyme-to-json'
import Search from './Search'
import ShowCard from './ShowCard'
import preload from '../public/data.json'

test('Search snapshot test', () => {
  const component = shallow(<Search />)
  const tree = shallowToJson(component)
  expect(tree).toMatchSnapshot()
})

test('Search should render a ShowCard for each show', () => {
  const component = shallow(<Search />)
  expect(component.find(ShowCard).length).toEqual(preload.shows.length)
})

test('Search should render correct number of shows based on search', () => {
  const searchWord = 'house'
  const component = shallow(<Search />)
  component.find('input').simulate('change', {target: {value: searchWord}})
  const showCount = preload.shows.filter((show) => `${show.title} ${show.description}`.toUpperCase().indexOf(searchWord.toUpperCase()) >= 0).length
  expect(component.find(ShowCard).length).toEqual(showCount)
})<|endoftext|>


<commit_before>'use strict';

module.exports = {
  name: require('./package').name
};
<commit_msg>Warn that the disableInputsInitializer configuration can be removed<commit_after>'use strict';

module.exports = {
  name: require('./package').name,

  config(environment, appConfig) {
    const addonConfig = appConfig['emberKeyboard'] || {};

    if ('disableInputsInitializer' in addonConfig) {
      this.ui.writeDeprecateLine(
        '[ember-keyboard] The `emberKeyboard.disableInputsInitializer` option is obsolete. ' +
        'You can remove it from your `config/environment.js` file.', false
      );
    }
  },
};
<|endoftext|>


<commit_before>app = angular.module('editorApp', []);

app.controller("MainController", ['$scope', '$sce', function($scope, $sce) {

	//Modifiable models
	$scope.html = ''+
	'\n\t
Hello World
'+
	'\n';

	$scope.css = 'h1{'+
	'\n\tcolor:#007092;'+
	'\n\ttext-align:center;'+
	'\n\tmargin:60px 0px;'+
	'\n}';

	//Used for wrapping the html and css
	$scope.head_s = '<!DOCTYPE HTML>'+
	'\n'+
	'\n\t'+
	'\n'+
	'\n\t';

	//Resultant model
	$scope.myHTML = $scope.head_s +  $scope.css + $scope.head_e + $scope.html + '\n';
	$scope.myHTMLSafe = $sce.trustAsHtml($scope.myHTML);

	//Updates the result with every change
	$scope.update = function(){
		$scope.myHTML = $scope.head_s +  $scope.css + $scope.head_e + $scope.html + '\n';
		$scope.myHTMLSafe = $sce.trustAsHtml($scope.myHTML);

	};
}]);<commit_msg>Angular code formatting<commit_after>app = angular.module('editorApp', []);
app.controller("MainController", ['$scope', '$sce', function($scope, $sce) {

	//Modifiable models
	$scope.html = ''+
	'\n\t
Hello World
'+
	'\n';

	$scope.css = 'h1{'+
	'\n\tcolor:#007092;'+
	'\n\ttext-align:center;'+
	'\n\tmargin:60px 0px;'+
	'\n}';

	//Used for wrapping the html and css
	$scope.head_s = '<!DOCTYPE HTML>'+
	'\n'+
	'\n\t'+
	'\n'+
	'\n\t';

	//Resultant model
	$scope.myHTML = $scope.head_s +  $scope.css + $scope.head_e + $scope.html + '\n';
	$scope.myHTMLSafe = $sce.trustAsHtml($scope.myHTML);

	//Updates the result with every change
	$scope.update = function(){
		$scope.myHTML = $scope.head_s +  $scope.css + $scope.head_e + $scope.html + '\n';
		$scope.myHTMLSafe = $sce.trustAsHtml($scope.myHTML);

	};
}]);<|endoftext|>


<commit_before>/* eslint no-debugger: 0 */
"use strict";
const resolveId = require('postcss-import/lib/resolve-id.js');
const AtImport = require('postcss-import');
const resolve = require('../import-sub/resolve.js');

function sub(options) {
  /**
   * Support simple mode of rules definition
   */
  let rules;
  if (options instanceof Array) {
    rules = options;
    options = {};
  } else {
    rules = options.sub;
    delete options.sub;
  }

  options.originalResolve = resolveId;
  /**
   * Define real options
   */
  return Object.assign({}, options, {
    resolve: function(id, base, importOptions) {
      return resolve(rules, Object.assign(
        {},
        options,
        {
          base: base,
          request: id,
          importOptions: importOptions || {},
        }
      ));
    }
  });
}

module.exports = function substitute(options) {
  return AtImport(sub(options));
}

module.exports.sub = sub;
module.exports.process = AtImport.process;
module.exports.postcss = AtImport.postcss;
module.exports.AtImport = AtImport;
<commit_msg>no local import-sub<commit_after>/* eslint no-debugger: 0 */
"use strict";
const resolveId = require('postcss-import/lib/resolve-id.js');
const AtImport = require('postcss-import');
const resolve = require('import-sub');

function sub(options) {
  /**
   * Support simple mode of rules definition
   */
  let rules;
  if (options instanceof Array) {
    rules = options;
    options = {};
  } else {
    rules = options.sub;
    delete options.sub;
  }

  options.originalResolve = resolveId;
  /**
   * Define real options
   */
  return Object.assign({}, options, {
    resolve: function(id, base, importOptions) {
      return resolve(rules, Object.assign(
        {},
        options,
        {
          base: base,
          request: id,
          importOptions: importOptions || {},
        }
      ));
    }
  });
}

module.exports = function substitute(options) {
  return AtImport(sub(options));
}

module.exports.sub = sub;
module.exports.process = AtImport.process;
module.exports.postcss = AtImport.postcss;
module.exports.AtImport = AtImport;
<|endoftext|>


<commit_before>import { InteractionManager } from 'react-native'
import _ from 'lodash'
import Parse from 'parse/react-native'
import Store from '../data/Store'
import realm from '../data/Realm'

import { loadForms } from './Forms'

// Attempts to find a survey with a specified id cached in the Store
export function loadCachedSurvey(id) {
  return realm.objects('Survey').filtered(`id = "${id}"`)[0]
}

// Finds and returns the list of all surveys cached in Realm.io
export function loadCachedSurveyList() {
  return realm.objects('Survey')
}

// Queries the connected Parse server for a list of Surveys.
export function loadSurveyList(options, callback) {
  const Survey = Parse.Object.extend("Survey")
  const query = new Parse.Query(Survey)
  query.equalTo("active", true)
  query.find({
    success: function(results) {
      clearSurveyCache(results)
      cacheParseSurveys(results)
      for (var i = 0; i < results.length; i++) {
        loadForms(results[i])
      }
      Store.lastParseUpdate = Date.now()
      if (callback) callback(null, results)
    },
    error: function(error, results) {
      console.warn("Error: " + error.code + " " + error.message)
      if (callback) callback(error, results)
    }
  })
}

// Saves a Survey object from Parse into our Realm.io local database
export function cacheParseSurveys(surveys) {
  try {
    if (!Array.isArray(surveys)) surveys = [surveys]
    let cachedSurveys = realm.objects('Survey')
    for (var i = 0; i < surveys.length; i++) {
      let cachedSurvey = cachedSurveys.filtered(`id = "${surveys[i].id}"`)[0]
      if (true) {
        realm.write(() => {
          realm.create('Survey', {
            id: surveys[i].id,
            active: surveys[i].get('active') ? true : false,
            createdAt: surveys[i].get('createdAt'),
            updatedAt: surveys[i].get('updatedAt'),
            title: surveys[i].get('title'),
            description: surveys[i].get('description'),
            user: 'Test University', // get parse user name
            forms: [],
            title: surveys[i].get('title'),
          }, true)
          getSurveyOwner(surveys[i])
        })
      }
    }
  } catch(e) {
    console.error(e)
  }
}

// Gets the name of the owner of a Survey and saves it to Realm database.
// TODO Get the organization's name
function getSurveyOwner(survey) {
  console.log('owner')
  let owner = survey.get("createdBy")
  owner.fetch({
    success: function(owner) {
      InteractionManager.runAfterInteractions(() => {
        realm.write(() => {
          try {
            realm.create('Survey', {
              id: survey.id,
              user: 'Organization\'s Name',
              // user: owner.get("name"),
            }, true)
          } catch(e) {
            console.error(e)
          }
        })
        console.log('finished surveys')
      })
    }
  })
}

// Erases the current cache of Surveys
function clearSurveyCache(exclusions) {
  try {
    let surveys = realm.objects('Survey')
    let expiredSurveys = []
    let excludedIds = []
    for (var i = 0; i < exclusions.length; i++) {
      excludedIds.push(exclusions[i].id)
    }

    // Standard JS array.filter doesn't work with these Realm objects, so we have to take care of this filtering manually.
    // Current version of Realm.io does not support exclusion queries for strings.
    for (var i = surveys.length - 1; i >= 0; i--) {
      let expired = true
      for (var j = excludedIds.length - 1; j >= 0; j--) {
        if (surveys[i].id === excludedIds[j]) expired = false
      }
      if (expired) expiredSurveys.push(surveys[i])
    }

    realm.write(() => {
      realm.delete(expiredSurveys)
    })
  } catch (e) {
    console.error(e)
  }
}<commit_msg>Disables InteractionManager due to inconsistencies<commit_after>import { InteractionManager } from 'react-native'
import _ from 'lodash'
import Parse from 'parse/react-native'
import Store from '../data/Store'
import realm from '../data/Realm'

import { loadForms } from './Forms'

// Attempts to find a survey with a specified id cached in the Store
export function loadCachedSurvey(id) {
  return realm.objects('Survey').filtered(`id = "${id}"`)[0]
}

// Finds and returns the list of all surveys cached in Realm.io
export function loadCachedSurveyList() {
  return realm.objects('Survey')
}

// Queries the connected Parse server for a list of Surveys.
export function loadSurveyList(options, callback) {
  const Survey = Parse.Object.extend("Survey")
  const query = new Parse.Query(Survey)
  query.equalTo("active", true)
  query.find({
    success: function(results) {
      clearSurveyCache(results)
      cacheParseSurveys(results)
      for (var i = 0; i < results.length; i++) {
        loadForms(results[i])
      }
      Store.lastParseUpdate = Date.now()
      if (callback) callback(null, results)
    },
    error: function(error, results) {
      console.warn("Error: " + error.code + " " + error.message)
      if (callback) callback(error, results)
    }
  })
}

// Saves a Survey object from Parse into our Realm.io local database
export function cacheParseSurveys(surveys) {
  try {
    if (!Array.isArray(surveys)) surveys = [surveys]
    let cachedSurveys = realm.objects('Survey')
    for (var i = 0; i < surveys.length; i++) {
      let cachedSurvey = cachedSurveys.filtered(`id = "${surveys[i].id}"`)[0]
      if (true) {
        realm.write(() => {
          realm.create('Survey', {
            id: surveys[i].id,
            active: surveys[i].get('active') ? true : false,
            createdAt: surveys[i].get('createdAt'),
            updatedAt: surveys[i].get('updatedAt'),
            title: surveys[i].get('title'),
            description: surveys[i].get('description'),
            user: 'Test University', // get parse user name
            forms: [],
            title: surveys[i].get('title'),
          }, true)
          getSurveyOwner(surveys[i])
        })
      }
    }
  } catch(e) {
    console.error(e)
  }
}

// Gets the name of the owner of a Survey and saves it to Realm database.
// TODO Get the organization's name
function getSurveyOwner(survey) {
  console.log('owner')
  let owner = survey.get("createdBy")
  owner.fetch({
    success: function(owner) {
      // InteractionManager.runAfterInteractions(() => {
        realm.write(() => {
          try {
            realm.create('Survey', {
              id: survey.id,
              user: 'Organization\'s Name',
              // user: owner.get("name"),
            }, true)
          } catch(e) {
            console.error(e)
          }
        })
        console.log('finished surveys')
      // })
    }
  })
}

// Erases the current cache of Surveys
function clearSurveyCache(exclusions) {
  try {
    let surveys = realm.objects('Survey')
    let expiredSurveys = []
    let excludedIds = []
    for (var i = 0; i < exclusions.length; i++) {
      excludedIds.push(exclusions[i].id)
    }

    // Standard JS array.filter doesn't work with these Realm objects, so we have to take care of this filtering manually.
    // Current version of Realm.io does not support exclusion queries for strings.
    for (var i = surveys.length - 1; i >= 0; i--) {
      let expired = true
      for (var j = excludedIds.length - 1; j >= 0; j--) {
        if (surveys[i].id === excludedIds[j]) expired = false
      }
      if (expired) expiredSurveys.push(surveys[i])
    }

    realm.write(() => {
      realm.delete(expiredSurveys)
    })
  } catch (e) {
    console.error(e)
  }
}<|endoftext|>


<commit_before>var Twig = require("twig");
var _ = require("underscore");
var path = require("path");
var loaderUtils = require("loader-utils");

Twig.extend(function(Twig) {
    var compiler = Twig.compiler;

    compiler.module['webpack'] = function(id, tokens, pathToTwig) {
        var includes = [];
        var processDependency = function(token) {
            includes.push(token.value);
            token.value = path.resolve(path.dirname(id), token.value);
        };

        var processToken = function(token) {
            if (token.type == "logic" && token.token.type) {
                switch(token.token.type) {
                    case 'Twig.logic.type.block':
                    case 'Twig.logic.type.if':
                    case 'Twig.logic.type.elseif':
                    case 'Twig.logic.type.else':
                    case 'Twig.logic.type.for':
                    case 'Twig.logic.type.spaceless':
                        _.each(token.token.output, processToken);
                        break;
                    case 'Twig.logic.type.extends':
                        _.each(token.token.stack, processDependency);
                        break;
                    case 'Twig.logic.type.import':
                        if (token.token.expression != '_self') {
                            _.each(token.token.stack, processDependency);
                        }
                        break;
                    case 'Twig.logic.type.include':
                        _.each(token.token.stack, processDependency);
                        break;
                }
            }
        };

        var parsedTokens = JSON.parse(tokens);

        _.each(parsedTokens, processToken);

        var output = [
            'var twig = require("' + pathToTwig + '").twig,',
            '    template = twig({id:' + JSON.stringify(id) + ', data:' + JSON.stringify(parsedTokens) + ', allowInlineIncludes: true});\n',
            'module.exports = function(context) { return template.render(context); }'
        ];

        if (includes.length > 0) {
            _.each(includes, function(file) {
                output.unshift("require("+ JSON.stringify("twig!" + file) +");\n");
            });
        }

        return output.join('\n');
    };
});

module.exports = function(source) {
    var id = require.resolve(this.resource),
        tpl;
    this.cacheable && this.cacheable();

    // check if template already exists
    tpl = Twig.twig({ ref: id });
    if (!tpl) {
        tpl = Twig.twig({
            id: id,
            data: source,
            allowInlineIncludes: true
        });
    }

    tpl = tpl.compile({
        module: 'webpack',
        twig: 'twig'
    });

    this.callback(null, tpl);
};
<commit_msg>Rethrow errors when rendering (for better testing)<commit_after>var Twig = require("twig");
var _ = require("underscore");
var path = require("path");
var loaderUtils = require("loader-utils");

Twig.extend(function(Twig) {
    var compiler = Twig.compiler;

    compiler.module['webpack'] = function(id, tokens, pathToTwig) {
        var includes = [];
        var processDependency = function(token) {
            includes.push(token.value);
            token.value = path.resolve(path.dirname(id), token.value);
        };

        var processToken = function(token) {
            if (token.type == "logic" && token.token.type) {
                switch(token.token.type) {
                    case 'Twig.logic.type.block':
                    case 'Twig.logic.type.if':
                    case 'Twig.logic.type.elseif':
                    case 'Twig.logic.type.else':
                    case 'Twig.logic.type.for':
                    case 'Twig.logic.type.spaceless':
                        _.each(token.token.output, processToken);
                        break;
                    case 'Twig.logic.type.extends':
                        _.each(token.token.stack, processDependency);
                        break;
                    case 'Twig.logic.type.import':
                        if (token.token.expression != '_self') {
                            _.each(token.token.stack, processDependency);
                        }
                        break;
                    case 'Twig.logic.type.include':
                        _.each(token.token.stack, processDependency);
                        break;
                }
            }
        };

        var parsedTokens = JSON.parse(tokens);

        _.each(parsedTokens, processToken);

        var output = [
            'var twig = require("' + pathToTwig + '").twig,',
            '    template = twig({id:' + JSON.stringify(id) + ', data:' + JSON.stringify(parsedTokens) + ', allowInlineIncludes: true, rethrow: true});\n',
            'module.exports = function(context) { return template.render(context); }'
        ];

        if (includes.length > 0) {
            _.each(includes, function(file) {
                output.unshift("require("+ JSON.stringify("twig!" + file) +");\n");
            });
        }

        return output.join('\n');
    };
});

module.exports = function(source) {
    var id = require.resolve(this.resource),
        tpl;
    this.cacheable && this.cacheable();

    // check if template already exists
    tpl = Twig.twig({ ref: id });
    if (!tpl) {
        tpl = Twig.twig({
            id: id,
            data: source,
            allowInlineIncludes: true
        });
    }

    tpl = tpl.compile({
        module: 'webpack',
        twig: 'twig'
    });

    this.callback(null, tpl);
};
<|endoftext|>


<commit_before>;(function(){
    window.threshold = 20;
    var canvas = document.getElementById('canvas');
    var context = canvas.getContext('2d');
    var original;

    function loadImage(url, callback){
	var image = new Image();
	image.onload = function(){
	    callback(this);
	}
	image.src = url;
    }

    function pointsOf(image, options){
	var options = options || {};
	var gray = new jsfeat.matrix_t(image.width, image.height, jsfeat.U8_t | jsfeat.C1_t);
	jsfeat.imgproc.grayscale(image.data, image.width, image.height, gray, jsfeat.COLOR_RGBA2GRAY);

	var threshold = options.threshold || 20;
	jsfeat.fast_corners.set_threshold(threshold);

	var corners = [], border = 3;

	// you should use preallocated keypoint_t array
	for(var i = 0; i < image.width * image.height; ++i) {
	    corners[i] = new jsfeat.keypoint_t(0,0,0,0);
	}

	// perform detection
	// returns the amount of detected corners
	var count = jsfeat.fast_corners.detect(gray, corners, border);
	return {
	    count: count,
	    corners: corners
	}
    }

    function drawPoints(data, options){
	var options = options || {}
	context.fillStyle = options.color || '#00ff00';
	var count = data.count;
	var corners = data.corners;
	for (var index = 0; index < count; index++){
	    var point = corners[index];
	    context.beginPath();
	    context.arc(point.x, point.y, 5, 0, 2 * Math.PI, false);
	    context.fill();
	}

    }

    function drawPointsOnOriginal(){
	context.drawImage(original, 0, 0);
	var cornerData = pointsOf(context.getImageData(0, 0, canvas.width, canvas.height),{
	    threshold: window.threshold
	});
	drawPoints(cornerData);
    }

    loadImage('/image/sample.jpg', function(image){
	original = image;
	drawPointsOnOriginal();
    });
})()
<commit_msg>Request Animation frame<commit_after>;(function(){
    window.threshold = 20;
    var canvas = document.getElementById('canvas');
    var context = canvas.getContext('2d');
    var original;

    function loadImage(url, callback){
	var image = new Image();
	image.onload = function(){
	    callback(this);
	}
	image.src = url;
    }

    function pointsOf(image, options){
	var options = options || {};
	var gray = new jsfeat.matrix_t(image.width, image.height, jsfeat.U8_t | jsfeat.C1_t);
	jsfeat.imgproc.grayscale(image.data, image.width, image.height, gray, jsfeat.COLOR_RGBA2GRAY);

	var threshold = options.threshold || 20;
	jsfeat.fast_corners.set_threshold(threshold);

	var corners = [], border = 3;

	// you should use preallocated keypoint_t array
	for(var i = 0; i < image.width * image.height; ++i) {
	    corners[i] = new jsfeat.keypoint_t(0,0,0,0);
	}

	// perform detection
	// returns the amount of detected corners
	var count = jsfeat.fast_corners.detect(gray, corners, border);
	return {
	    count: count,
	    corners: corners
	}
    }

    function drawPoints(data, options){
	var options = options || {}
	context.fillStyle = options.color || '#00ff00';
	var count = data.count;
	var corners = data.corners;
	for (var index = 0; index < count; index++){
	    var point = corners[index];
	    context.beginPath();
	    context.arc(point.x, point.y, 5, 0, 2 * Math.PI, false);
	    context.fill();
	}

    }

    function drawPointsOnOriginal(){
	context.drawImage(original, 0, 0);
	var cornerData = pointsOf(context.getImageData(0, 0, canvas.width, canvas.height),{
	    threshold: window.threshold
	});
	drawPoints(cornerData);
	requestAnimationFrame(drawPointsOnOriginal);
    }

    loadImage('/image/sample.jpg', function(image){
	original = image;
	drawPointsOnOriginal();
    });
})()
<|endoftext|>


<commit_before>/** @fileOverview API for application developers. */

/**
 * @constructor
 * @class This is the top-level API for BOPlish applications. It should be the
 * only interface used for interacting with the P2P network.
 * @param bootstrapHost {String} Name and port of the host running the signaling
 * server. The format is 'HOSTNAME[:PORT]'. If this is undefined or null then
 * the host of the serving application is used.
 * @param successCallback {BOPlishClient~onSuccessCallback} Called when a
 * connection to the P2P network has been established.
 * @param errorCallback {BOPlishClient~onErrorCallback} Called when a connection
 * to the P2P network could not be established (e.g. if the WebSocket connection
 * to the bootstrapHost failed.
 */
BOPlishClient = function(bootstrapHost, successCallback, errorCallback) {
    this.id = sha1.hash(Math.random().toString());
    bootstrapHost = bootstrapHost || window.location.host;

    var channel = new WebSocket('ws://' + bootstrapHost + '/ws/' + this.id);
    channel.onerror = function() {
        errorCallback();
    };
    channel.onopen = function() {
        this._connectionManager.bootstrap(this._router, successCallback, errorCallback);
    }.bind(this);

    this._connectionManager = new ConnectionManager();
    this._router = new Router(this.id, channel, this._connectionManager);
};

BOPlishClient.prototype = {
    /**
     * Sends a message to the given peer.
     * @param to {String} Receiver of the message
     * @param protocol {String} Protocol name. On the receiver side a handler
     * has to be installed for this protocol.
     * @param payload {Object} The payload to send.
     */
    send: function(to, protocol, payload) {
        this._router.route(to, protocol, payload);
    },
    /**
     * Installs a handler for the given protocol name.
     * @param protocol {String} The protocol to handle.
     * @param callback {BOPlishClient~onMessageCallback} The function invoked when a message of the
     * given protocol is received through the P2P network.
     */
    setOnMessageHandler: function(protocol, callback) {
        this._router.registerDeliveryCallback(protocol, callback);
    },
    /**
     * Installs a special callback that receives all messages despite their
     * protocol.
     * @param callback {BOPlishClient~monitorCallback} Invoked on reception of a
     * message.
     */
    setMonitorCallback: function(callback) {
        this._router.registerMonitorCallback(callback);
    },
    /**
     * @return {Array} The list of all IDs of peers this peer has an open
     * connection to.
     */
    getConnectedPeers: function() {
        return this._router.getPeerIds();
    }
};

/**
 * Invoked when a message is received.
 * @callback BOPlishClient~onMessageCallback
 * @param from {String} The sender's ID
 * @param payload {Object} The message object in JSON format.
 */

/**
 * Invoked when a connection to the P2P network has been established.
 * @callback BOPlishClient~onSuccessCallback
 */

/**
 * Invoked when a connection to the P2P network could not be established.
 * @callback BOPlishClient~onErrorCallback
 */

/**
 * Invoked when a message has been received. Useful for monitoring the complete
 * traffic passing in/out of this peer.
 * @callback BOPlishClient~monitorCallback
 * @param message {Object} The raw message in router format.
 */
<commit_msg>Pass original error to errorCallback<commit_after>/** @fileOverview API for application developers. */

/**
 * @constructor
 * @class This is the top-level API for BOPlish applications. It should be the
 * only interface used for interacting with the P2P network.
 * @param bootstrapHost {String} Name and port of the host running the signaling
 * server. The format is 'HOSTNAME[:PORT]'. If this is undefined or null then
 * the host of the serving application is used.
 * @param successCallback {BOPlishClient~onSuccessCallback} Called when a
 * connection to the P2P network has been established.
 * @param errorCallback {BOPlishClient~onErrorCallback} Called when a connection
 * to the P2P network could not be established (e.g. if the WebSocket connection
 * to the bootstrapHost failed.
 */
BOPlishClient = function(bootstrapHost, successCallback, errorCallback) {
    this.id = sha1.hash(Math.random().toString());
    bootstrapHost = bootstrapHost || window.location.host;

    var channel = new WebSocket('ws://' + bootstrapHost + '/ws/' + this.id);
    channel.onerror = function(err) {
        errorCallback(err);
    };
    channel.onopen = function() {
        this._connectionManager.bootstrap(this._router, successCallback, errorCallback);
    }.bind(this);

    this._connectionManager = new ConnectionManager();
    this._router = new Router(this.id, channel, this._connectionManager);
};

BOPlishClient.prototype = {
    /**
     * Sends a message to the given peer.
     * @param to {String} Receiver of the message
     * @param protocol {String} Protocol name. On the receiver side a handler
     * has to be installed for this protocol.
     * @param payload {Object} The payload to send.
     */
    send: function(to, protocol, payload) {
        this._router.route(to, protocol, payload);
    },
    /**
     * Installs a handler for the given protocol name.
     * @param protocol {String} The protocol to handle.
     * @param callback {BOPlishClient~onMessageCallback} The function invoked when a message of the
     * given protocol is received through the P2P network.
     */
    setOnMessageHandler: function(protocol, callback) {
        this._router.registerDeliveryCallback(protocol, callback);
    },
    /**
     * Installs a special callback that receives all messages despite their
     * protocol.
     * @param callback {BOPlishClient~monitorCallback} Invoked on reception of a
     * message.
     */
    setMonitorCallback: function(callback) {
        this._router.registerMonitorCallback(callback);
    },
    /**
     * @return {Array} The list of all IDs of peers this peer has an open
     * connection to.
     */
    getConnectedPeers: function() {
        return this._router.getPeerIds();
    }
};

/**
 * Invoked when a message is received.
 * @callback BOPlishClient~onMessageCallback
 * @param from {String} The sender's ID
 * @param payload {Object} The message object in JSON format.
 */

/**
 * Invoked when a connection to the P2P network has been established.
 * @callback BOPlishClient~onSuccessCallback
 */

/**
 * Invoked when a connection to the P2P network could not be established.
 * @callback BOPlishClient~onErrorCallback
 */

/**
 * Invoked when a message has been received. Useful for monitoring the complete
 * traffic passing in/out of this peer.
 * @callback BOPlishClient~monitorCallback
 * @param message {Object} The raw message in router format.
 */
<|endoftext|>


<commit_before>'use strict';

const express = require('express');
const bodyParser = require('body-parser');

const restService = express();
restService.use(bodyParser.json());

restService.get('/test', function (req, res) {
  return res.json({
            speech: "hello speech",
            displayText: "hello text",
            source: 'grafton-soccer-webhook'
        });

});

restService.post('/echo', function(req, res) {
    var speech = req.body.result && req.body.result.parameters && req.body.result.parameters.echoText ? req.body.result.parameters.echoText : "Seems like some problem. Speak again."
    return res.json({
        speech: speech,
        displayText: speech,
        source: 'webhook-echo-sample'
    });
});

restService.post('/hook', function (req, res) {

    console.log('hook request');

    try {
        var speech = 'empty speech';

        if (req.body) {
            var requestBody = req.body;

            if (requestBody.result) {
                speech = '';

                if (requestBody.result.fulfillment) {
                    speech += requestBody.result.fulfillment.speech;
                    speech += ' ';
                }

                if (requestBody.result.action) {
                    speech += 'action: ' + requestBody.result.action;
                }
            }
        }

        console.log('result: ', speech);

        return res.json({
            speech: speech,
            displayText: speech,
            source: 'grafton-soccer-webhook'
        });
    } catch (err) {
        console.error("Can't process request", err);

        return res.status(400).json({
            status: {
                code: 400,
                errorType: err.message
            }
        });
    }
});

restService.post('/game', function(req, res) {
    //req.body.result && req.body.result.parameters && req.body.result.parameters.echoText

    var date1 = new Date( 2017, 6, 15, 16, 20 );
    var startDate = new Date();
    var startTime = +startDate;
    var nearestDate, nearestDiff = Infinity;

    var dates = [date1];

    for( var i = 0, n = dates.length;  i < n;  ++i ) {
        var diff = +dates[i] - startTime;
        if( diff > 0  &&  diff < nearestDiff ) {
            nearestDiff = diff;
            nearestDate = dates[i];
        }
    }

    var options = {
        weekday: "long", year: "numeric", month: "short",
        day: "numeric", hour: "2-digit", minute: "2-digit"
    };

    var outDate = date1.toLocaleTimeString("en-us", options);

    var speech = "Your next game is " + outDate;
    return res.json({
        speech: speech,
        displayText: speech,
        source: 'grafton-soccer-webhook'
    });
});

restService.listen((process.env.PORT || 5000), function () {
    console.log("Server listening");
});<commit_msg>when is next game<commit_after>'use strict';

const express = require('express');
const bodyParser = require('body-parser');

const restService = express();
restService.use(bodyParser.json());

restService.get('/test', function (req, res) {
  return res.json({
            speech: "hello speech",
            displayText: "hello text",
            source: 'grafton-soccer-webhook'
        });

});

restService.post('/echo', function(req, res) {
    var speech = req.body.result && req.body.result.parameters && req.body.result.parameters.echoText ? req.body.result.parameters.echoText : "Seems like some problem. Speak again."
    return res.json({
        speech: speech,
        displayText: speech,
        source: 'webhook-echo-sample'
    });
});

restService.post('/hook', function (req, res) {

    console.log('hook request');

    try {
        var speech = 'empty speech';

        if (req.body) {
            var requestBody = req.body;

            if (requestBody.result) {
                speech = '';

                if (requestBody.result.fulfillment) {
                    speech += requestBody.result.fulfillment.speech;
                    speech += ' ';
                }

                if (requestBody.result.action) {
                    speech += 'action: ' + requestBody.result.action;
                }
            }
        }

        console.log('result: ', speech);

        return res.json({
            speech: speech,
            displayText: speech,
            source: 'grafton-soccer-webhook'
        });
    } catch (err) {
        console.error("Can't process request", err);

        return res.status(400).json({
            status: {
                code: 400,
                errorType: err.message
            }
        });
    }
});

var games = [
    {date: new Date( 2017, 6, 15, 16, 20 ), opponent: 'Shrewsbury', location: 'Lyon\'s field'},
    {date: new Date( 2017, 3, 15, 16, 20 ), opponent: 'Worcester', location: 'Away field'},
];

restService.get('/game', function(req, res) {
    //req.body.result && req.body.result.parameters && req.body.result.parameters.echoText

    if(req.body.result.parameters.action === 'when'){
        var speech = 'You don\'t have any games left';
        var nextGame = getNextGame();
        if(nextGame.date !== undefined){
            var options = {
                weekday: "long", year: "numeric", month: "short",
                day: "numeric", hour: "2-digit", minute: "2-digit"
            };

            var outDate = nextGame.date.toLocaleTimeString("en-us", options);
            speech = "Your next game is " + outDate;
        }
    }
    return res.json({
            speech: speech,
            displayText: speech,
            source: 'grafton-soccer-webhook'
        });
});

function getNextGame(){
    var startDate = new Date();
    var startTime = +startDate;
    var nearestDate, nearestDiff = Infinity;
    var nextGame;
    for( var i = 0, n = games.length;  i < n;  ++i ) {
        var date = games[i].date;
        var diff = +date - startTime;
        if( diff > 0  &&  diff < nearestDiff ) {
            nearestDiff = diff;
            nearestDate = date;
            nextGame = games[i];
        }
    }
    return nextGame;
};

restService.listen((process.env.PORT || 5000), function () {
    console.log("Server listening");
});<|endoftext|>


<commit_before>;(function(lander, undefined){
    var display = document.getElementById('display');
    var horizon = new Array(display.width);
    var horizon_height = 50;
    horizon[0] = horizon_height;
    for (var index = 1; index < display.width; index++){
        horizon[index] = horizon_height;
    }

    var model = {
        "lander": {
            "x": 37, "y": 251,
            "orientation": Math.PI/4,
            "radius": 5,
            "fuel": 10,
            "thrusting": false
        },
        "horizon": horizon
    };

    var pressed = {
    }
    document.body.addEventListener('keydown', function(event){
        var code = event.keyCode;
        pressed[code] = true;

    }, true);
    document.body.addEventListener('keyup', function(event){
        var code = event.keyCode;
        pressed[code] = false;
    }, true);

    function control(commandpanel){
        if (pressed[37]){
            console.log('left');
            commandpanel.do.turnLeft();
        }
        if (pressed[39]){
            console.log('right');
            commandpanel.do.turnRight();
        }
        if (pressed[38]){
            console.log('thrusting');
            commandpanel.do.thruster();
        }
    }

    var world = new lander.simulation.FlatLand(display.width, horizon_height);
    var position = new lander.vector.Vector(37, 251);
    var moonLander = new lander.simulation.Lander(position, control);

    function updateModel() {
        model.lander.x = moonLander.x.x;
        model.lander.y = moonLander.x.y;
        model.lander.orientation = moonLander.o.angle() - Math.PI/2;
        model.lander.radius = simulation.params.landerRadius;
        model.lander.crashed = moonLander.crashed;
        model.lander.landed = moonLander.landed;
        model.lander.fuel = moonLander.fuel;
        model.lander.thrusting = moonLander.thrusting;
    }

    var simulation = new lander.simulation.Simulation(world, moonLander, {
        gravity: new lander.vector.Vector(0, -0.01),
        landerRadius: 10,
        thrusterAcceleration: 0.05,
        turningSpeed: Math.PI/1000,
        landingMaxSpeed: 0.25
    });

    var updateInfo = (function(){
        var x = document.getElementById('x');
        var y = document.getElementById('y');
        var vx = document.getElementById('vx');
        var vy = document.getElementById('vy');
        var orientation = document.getElementById('orientation');
        var angularVelocity = document.getElementById('angularVelocity');
        var gravity = document.getElementById('gravity');
        var thrust = document.getElementById('thrust');
        return function(){
            x.innerHTML = moonLander.x.x.toFixed(2);
            y.innerHTML = moonLander.x.y.toFixed(2);
            vx.innerHTML = moonLander.v.x.toFixed(2);
            vy.innerHTML = moonLander.v.y.toFixed(2);
            orientation.innerHTML = (moonLander.o.angle() - Math.PI/2).toFixed(2);
            angularVelocity.innerHTML = moonLander.w.toFixed(2);
            gravity.innerHTML = simulation.params.gravity.y.toFixed(2);
            thrust.innerHTML = simulation.params.thrusterAcceleration.toFixed(2);
        };
    })();

    var view = new lander.View(model, display);
    function tick(){
        simulation.tick();
        updateModel();
        updateInfo();
        view.update();
        requestAnimationFrame(tick);
    };
    tick();

})(lander);
<commit_msg>Now with robot control<commit_after>;(function(lander, undefined){
    var display = document.getElementById('display');
    var horizon = new Array(display.width);
    var horizon_height = 50;
    horizon[0] = horizon_height;
    for (var index = 1; index < display.width; index++){
        horizon[index] = horizon_height;
    }

    var model = {
        "lander": {
            "x": 37, "y": 251,
            "orientation": Math.PI/4,
            "radius": 5,
            "fuel": 10,
            "thrusting": false
        },
        "horizon": horizon
    };

    var pressed = {
    }
    document.body.addEventListener('keydown', function(event){
        var code = event.keyCode;
        pressed[code] = true;

    }, true);
    document.body.addEventListener('keyup', function(event){
        var code = event.keyCode;
        pressed[code] = false;
    }, true);

    function control(commandpanel){
        if (pressed[37]){
            console.log('left');
            commandpanel.do.turnLeft();
        }
        if (pressed[39]){
            console.log('right');
            commandpanel.do.turnRight();
        }
        if (pressed[38]){
            console.log('thrusting');
            commandpanel.do.thruster();
        }
    }

    var simulationOptions = {
        gravity: new lander.vector.Vector(0, -0.01),
        landerRadius: 10,
        thrusterAcceleration: 0.05,
        turningSpeed: Math.PI/1000,
        landingMaxSpeed: 0.25
    };
    var robotControl = (function(){
        var a = simulationOptions.thrusterAcceleration + simulationOptions.gravity.y
        var shouldThrust = false;
        return function robotControl(commandpanel){
            var x = commandpanel.see.x();
            var h = x.y - horizon_height;
            var v = commandpanel.see.v();
            var s = v.y;
            shouldThrust = shouldThrust || (Math.pow(s,2) >=  13/8 * a * h);
            if (shouldThrust) {
                console.log('thrusting');
                commandpanel.do.thruster();
            } else {
                console.log("skipping");
            }
        }
    })();

    var world = new lander.simulation.FlatLand(display.width, horizon_height);
    var position = new lander.vector.Vector(37, 251);
    var moonLander = new lander.simulation.Lander(position, robotControl);

    function updateModel() {
        model.lander.x = moonLander.x.x;
        model.lander.y = moonLander.x.y;
        model.lander.orientation = moonLander.o.angle() - Math.PI/2;
        model.lander.radius = simulation.params.landerRadius;
        model.lander.crashed = moonLander.crashed;
        model.lander.landed = moonLander.landed;
        model.lander.fuel = moonLander.fuel;
        model.lander.thrusting = moonLander.thrusting;
    }

    var simulation = new lander.simulation.Simulation(world, moonLander, simulationOptions);

    var updateInfo = (function(){
        var x = document.getElementById('x');
        var y = document.getElementById('y');
        var vx = document.getElementById('vx');
        var vy = document.getElementById('vy');
        var orientation = document.getElementById('orientation');
        var angularVelocity = document.getElementById('angularVelocity');
        var gravity = document.getElementById('gravity');
        var thrust = document.getElementById('thrust');
        return function(){
            x.innerHTML = moonLander.x.x.toFixed(2);
            y.innerHTML = moonLander.x.y.toFixed(2);
            vx.innerHTML = moonLander.v.x.toFixed(2);
            vy.innerHTML = moonLander.v.y.toFixed(2);
            orientation.innerHTML = (moonLander.o.angle() - Math.PI/2).toFixed(2);
            angularVelocity.innerHTML = moonLander.w.toFixed(2);
            gravity.innerHTML = simulation.params.gravity.y.toFixed(2);
            thrust.innerHTML = simulation.params.thrusterAcceleration.toFixed(2);
        };
    })();

    var view = new lander.View(model, display);
    function tick(){
        simulation.tick();
        updateModel();
        updateInfo();
        view.update();
        requestAnimationFrame(tick);
    };
    tick();

})(lander);
<|endoftext|>