<commit_before>/**
 * @file Pomegranate
 * @author Jim Bulkowski <jim.b@paperelectron.com>
 * @project Pomegranate
 * @license MIT {@link http://opensource.org/licenses/MIT}
 */

var _ = require('lodash');
var path = require('path');
var http = require('http');
var express = require('express');
var injector = require('magnum-di');
var chalk = require('chalk');
var app = express();
var verifyConfig = require('./Configuration/Config');
var logger = require('./Utilities/LogEmitter');
var VERSION = require(path.join(__dirname,'../','package.json')).version

var mainPath = path.dirname(require.main.filename);
var staticFiles = path.join(mainPath, 'public');
var defaultRoutes = path.join(mainPath, 'routes');
var defaultModels = path.join(mainPath, 'models');

/**
 * @class Pomegranate
 * @extends Logger
 * @listens Logger#log
 */
function Pomegranate(){
  var initialized = false;
  var started = false;
  var maxStartAttemts = 5;
  var startAttempts = 0;
  var dataServices = [];

  var server;
  var instanceOptions;
  var Redis;
  var SQL;
  var Couch;
  var Controllers;
  var expressConfig;
  var applicationRef;

  /**
   * @private
   */
  var attemptStart = function(cb) {
    if(maxStartAttemts >= 1){
      if(_.every(dataServices, 'ready', true)){
        this.log(chalk.green('DataHandlers: Data Service connections successful after ' + startAttempts + ' attempts.'));
        this.log(chalk.inverse.green('Pomegranate v'+ VERSION + ': Starting server on ' + instanceOptions.address + ':' + instanceOptions.port));
        server.listen(instanceOptions.port, instanceOptions.address, cb.bind(null, null));
        started = true;

      } else {
        this.log(chalk.yellow('DataHandlers: Waiting for connections. ' + (maxStartAttemts - 1) + ' Attempts left.'));
        setTimeout(function() {
          maxStartAttemts -= 1;
          startAttempts += 1;
          attemptStart(cb)
        }.bind(this), 200);
      }
    } else {
      this.error(chalk.red('Could not connect to services after 5 attempts.'));
      setImmediate(function() {
        process.exit();
      })

    }
  }.bind(this);

  /**
   * @method init
   * @memberof Pomegranate
   * @instance
   * @description Sets up the Pomegranate framework.
   * @param {Configuration} options - The main config object for Pomegranate.
   *
   * pomegranate.init(options)
   * @returns {Pomegranate} This instance.
   */
  this.init = function(options) {
    instanceOptions = verifyConfig(options);
    initialized = true;
    this.log(chalk.inverse.green('Pomegranate v'+ VERSION + ': Running setup.'));
    injector.service('Logger', logger);
    injector.factory('Router', express.Router);

    /**
     *  Redis
     */
    if(instanceOptions.redis){
      var redisStatus = {ready: false};
      dataServices.push(redisStatus);
      Redis = require('./DataServices/RedisLoader')(injector, instanceOptions, logger);
      Redis.on('ready', function(){
        redisStatus.ready = true
      });
    }
    /**
     * SQL
     */
    if(instanceOptions.sql) {
      var sqlStatus = {ready: false};
      dataServices.push(sqlStatus);
      SQL = require('./DataServices/SQLoader')(injector, instanceOptions, logger);
      SQL.on('ready', function() {
        sqlStatus.ready = true
      });
    }
    /**
     * Couch
     */
    if(instanceOptions.couch){
      var couchStatus = {ready: false}
      dataServices.push(couchStatus);
      Couch = require('./DataServices/CouchLoader')(injector, instanceOptions, logger);
      Couch.on('ready', function(){
        couchStatus.ready = true
      });
    }
    expressConfig = require('./Server/ExpressConfig')(app, instanceOptions, injector,  logger);

    return this
  };
  /**
   * Starts the Pomegranate server instance.
   * @method start
   * @memberof Pomegranate
   * @instance
   * @param {Pomegranate~startupCallback} callback
   * @returns {Pomegranate} this instance
   */

  /**
   * error will be encountered error if server failed to start.
   *
   * @callback Pomegranate~startupCallback
   * @param {Error} error
   */
  this.start = function(callback) {

    if(!_.isFunction(callback)){
      callback = function(){};
    }

    started = true;
    if(initialized && instanceOptions) {
      Controllers = require('./DataServices/ControllerLoader')(injector, instanceOptions, logger)
      Controllers.on('error', function(err){
        logger.error(err);
      });
      Controllers.on('ready', function() {
        /**
         *  Run this in a new stack so we can return from this function and attach
         *  any needed handlers before any log or error events happen.
         */
        var Deps = require('./DataServices/DependencyLoader')(injector, instanceOptions, logger);
        Deps.on('ready', function(){
          /**
           * Attach pre route middleware first, including user defined middleware.
           */
          var loadedApp = expressConfig.mountFirstMiddleware();

          /**
           * Load routes.
           */
          loadedApp = require('./Server/RouteLoader')(instanceOptions.routes, loadedApp, injector);
          /**
           * Attach post route middleware, including error handlers.
           */
          loadedApp = expressConfig.mountLastMiddleware();

          loadedApp = expressConfig.configureExpress();
          applicationRef = loadedApp;
          server = http.createServer(loadedApp);

          setImmediate(function(){
            attemptStart(callback)
          });
        });

      })

      return this
    }

    callback('Cannot start server without running init first.');
    return this

  };

  /**
   * Adds a middleware function, or an array of middleware functions to the global middleware stack.
   * @method addMiddleware
   * @memberof Pomegranate
   * @instance
   * @returns {Pomegranate} this instance
   */
  this.addMiddleware = function(middleware){
    if(!started && initialized) {
      expressConfig.addMiddleware(middleware);
      return this
    }
    this.error(new Error('Cannot add middleware after server start.'));
    return this
  };

  /**
   * Registers a dependency to be made available to the injector.
   * @method addDependency
   * @memberof Pomegranate
   * @instance
   * @returns {Pomegranate} this instance
   */
  this.addDependency = function(name, item, instance){
    if(!started){
      if(_.isString(name)){
        callAsDeterminer(name, item, instance)
      }
      if(_.isArray(name)){
        _.each(name, function(obj){
          if(_.isObject(obj) && _.isString(obj.name)){
            callAsDeterminer(obj.name, obj.item, obj.instance)
          }
        })
      }
      return this
    }
    this.error(new Error('Cannot add dependencies after server start.'));
    return this
  };
  //this.nuclearOption = function(){
  //  return applicationRef;
  //}

  /**
   * Returns the currently configured stack of default middleware.
   *
   * @method getDefaultMiddleware
   * @memberof Pomegranate
   * @instance
   * @returns {Function[]}
   */
  this.getDefaultMiddleware = function(){
    if(!started && initialized) {
      return expressConfig.getMiddleware();
    }
    this.error(new Error('Cannot add middleware after server start.'));
    return this
  };

  /**
   * Overrides the default stack of middlewares, returns Pomegranate instance for chaining.
   *
   * @method setDefaultMiddleware
   * @memberof Pomegranate
   * @instance
   * @param {Function[]} middleware
   * @returns {Pomegranate}
   */
  this.setDefaultMiddleware = function(middleware){
    if(!started && initialized) {
      expressConfig.setMiddleware(middleware);
      return this
    }
    this.error(new Error('Cannot set middleware after server start.'));
    return this
  };

  /**
   * Overrides the default stack of error handlers, returns Pomegranate instance for chaining.
   *
   * @method setErrorHandlers
   * @memberof Pomegranate
   * @instance
   * @param {Function[]} errorHandlers
   * @returns {Pomegranate}
   */
  this.setErrorHandlers = function(errorHandlers){
    if(!started && initialized) {
      expressConfig.setErrorHandlers(errorHandlers);
      return this
    }
    this.error(new Error('Cannot set Error Handlers after server start.'));
    return this
  };
}
/**
 *
 * @type {Logger}
 */
Pomegranate.prototype = _.create(logger, {constructor: Pomegranate});

/**
 * An unassuming framework for building web applications.
 * @module Pomegranate
 * @returns {Pomegranate}
 */
process.on('uncaughtException', function(err){
  console.log(err)
  console.log(err.stack)
  console.log(chalk.red('Pomegranate has encountered an uncaught exception and will now exit.'))
})

module.exports = new Pomegranate();

/*
 * Utility
 */
function callAsDeterminer(name, item, instance){
  if(_.isString(name)){
    if(_.isFunction(item)) {
      if(instance){
        injector.instance(name, item)
      } else {
        injector.factory(name, item)
      }

    } else {
      injector.service(name, item)
    }
  }
}<commit_msg>Add method to attach global request handlers to express app object<commit_after>/**
 * @file Pomegranate
 * @author Jim Bulkowski <jim.b@paperelectron.com>
 * @project Pomegranate
 * @license MIT {@link http://opensource.org/licenses/MIT}
 */

var _ = require('lodash');
var path = require('path');
var http = require('http');
var express = require('express');
var injector = require('magnum-di');
var chalk = require('chalk');
var app = express();
var verifyConfig = require('./Configuration/Config');
var logger = require('./Utilities/LogEmitter');
var VERSION = require(path.join(__dirname,'../','package.json')).version

var mainPath = path.dirname(require.main.filename);
var staticFiles = path.join(mainPath, 'public');
var defaultRoutes = path.join(mainPath, 'routes');
var defaultModels = path.join(mainPath, 'models');

/**
 * @class Pomegranate
 * @extends Logger
 * @listens Logger#log
 */
function Pomegranate(){
  var initialized = false;
  var started = false;
  var maxStartAttemts = 5;
  var startAttempts = 0;
  var dataServices = [];

  var server;
  var instanceOptions;
  var Redis;
  var SQL;
  var Couch;
  var Controllers;
  var expressConfig;
  var applicationRef;
  var useFunctions = [];

  /**
   * @private
   */
  var attemptStart = function(cb) {
    if(maxStartAttemts >= 1){
      if(_.every(dataServices, 'ready', true)){
        this.log(chalk.green('DataHandlers: Data Service connections successful after ' + startAttempts + ' attempts.'));
        this.log(chalk.inverse.green('Pomegranate v'+ VERSION + ': Starting server on ' + instanceOptions.address + ':' + instanceOptions.port));
        server.listen(instanceOptions.port, instanceOptions.address, cb.bind(null, null));
        started = true;

      } else {
        this.log(chalk.yellow('DataHandlers: Waiting for connections. ' + (maxStartAttemts - 1) + ' Attempts left.'));
        setTimeout(function() {
          maxStartAttemts -= 1;
          startAttempts += 1;
          attemptStart(cb)
        }.bind(this), 200);
      }
    } else {
      this.error(chalk.red('Could not connect to services after 5 attempts.'));
      setImmediate(function() {
        process.exit();
      })

    }
  }.bind(this);

  /**
   * @method init
   * @memberof Pomegranate
   * @instance
   * @description Sets up the Pomegranate framework.
   * @param {Configuration} options - The main config object for Pomegranate.
   *
   * pomegranate.init(options)
   * @returns {Pomegranate} This instance.
   */

  this.init = function(options) {
    instanceOptions = verifyConfig(options);
    initialized = true;
    this.log(chalk.inverse.green('Pomegranate v'+ VERSION + ': Running setup.'));
    injector.service('Logger', logger);
    injector.factory('Router', express.Router);

    /**
     *  Redis
     */
    if(instanceOptions.redis){
      var redisStatus = {ready: false};
      dataServices.push(redisStatus);
      Redis = require('./DataServices/RedisLoader')(injector, instanceOptions, logger);
      Redis.on('ready', function(){
        redisStatus.ready = true
      });
    }
    /**
     * SQL
     */
    if(instanceOptions.sql) {
      var sqlStatus = {ready: false};
      dataServices.push(sqlStatus);
      SQL = require('./DataServices/SQLoader')(injector, instanceOptions, logger);
      SQL.on('ready', function() {
        sqlStatus.ready = true
      });
    }
    /**
     * Couch
     */
    if(instanceOptions.couch){
      var couchStatus = {ready: false}
      dataServices.push(couchStatus);
      Couch = require('./DataServices/CouchLoader')(injector, instanceOptions, logger);
      Couch.on('ready', function(){
        couchStatus.ready = true
      });
    }
    expressConfig = require('./Server/ExpressConfig')(app, instanceOptions, injector,  logger);

    return this
  };
  /**
   * Starts the Pomegranate server instance.
   * @method start
   * @memberof Pomegranate
   * @instance
   * @param {Pomegranate~startupCallback} callback
   * @returns {Pomegranate} this instance
   */

  /**
   * error will be encountered error if server failed to start.
   *
   * @callback Pomegranate~startupCallback
   * @param {Error} error
   */
  this.start = function(callback) {

    if(!_.isFunction(callback)){
      callback = function(){};
    }

    started = true;
    if(initialized && instanceOptions) {
      Controllers = require('./DataServices/ControllerLoader')(injector, instanceOptions, logger)
      Controllers.on('error', function(err){
        logger.error(err);
      });
      Controllers.on('ready', function() {
        /**
         *  Run this in a new stack so we can return from this function and attach
         *  any needed handlers before any log or error events happen.
         */
        var Deps = require('./DataServices/DependencyLoader')(injector, instanceOptions, logger);
        Deps.on('ready', function(){
          /**
           * Attach pre route middleware first, including user defined middleware.
           */
          var loadedApp = expressConfig.mountFirstMiddleware();

          /**
           * Load routes.
           */
          loadedApp = require('./Server/RouteLoader')(instanceOptions.routes, loadedApp, injector);

          /**
           * Load user defined global handlers
           */
          _.each(useFunctions, function(useFn, key){
            useFn(loadedApp)
          })
          /**
           * Attach post route middleware, including error handlers.
           */
          loadedApp = expressConfig.mountLastMiddleware();

          loadedApp = expressConfig.configureExpress();
          applicationRef = loadedApp;

          server = http.createServer(loadedApp);

          setImmediate(function(){
            attemptStart(callback)
          });
        });

      })

      return this
    }

    callback('Cannot start server without running init first.');
    return this

  };

  /**
   * Adds a middleware function, or an array of middleware functions to the global middleware stack.
   * @method addMiddleware
   * @memberof Pomegranate
   * @instance
   * @returns {Pomegranate} this instance
   */
  this.addMiddleware = function(middleware){
    if(!started && initialized) {
      expressConfig.addMiddleware(middleware);
      return this
    }
    this.error(new Error('Cannot add middleware after server start.'));
    return this
  };

  /**
   * Registers a dependency to be made available to the injector.
   * @method addDependency
   * @memberof Pomegranate
   * @instance
   * @returns {Pomegranate} this instance
   */
  this.addDependency = function(name, item, instance){
    if(!started){
      if(_.isString(name)){
        callAsDeterminer(name, item, instance)
      }
      if(_.isArray(name)){
        _.each(name, function(obj){
          if(_.isObject(obj) && _.isString(obj.name)){
            callAsDeterminer(obj.name, obj.item, obj.instance)
          }
        })
      }
      return this
    }
    this.error(new Error('Cannot add dependencies after server start.'));
    return this
  };
  //this.nuclearOption = function(){
  //  return applicationRef;
  //}

  /**
   * Returns the currently configured stack of default middleware.
   *
   * @method getDefaultMiddleware
   * @memberof Pomegranate
   * @instance
   * @returns {Function[]}
   */
  this.getDefaultMiddleware = function(){
    if(!started && initialized) {
      return expressConfig.getMiddleware();
    }
    this.error(new Error('Cannot add middleware after server start.'));
    return this
  };

  /**
   * Overrides the default stack of middlewares, returns Pomegranate instance for chaining.
   *
   * @method setDefaultMiddleware
   * @memberof Pomegranate
   * @instance
   * @param {Function[]} middleware
   * @returns {Pomegranate}
   */
  this.setDefaultMiddleware = function(middleware){
    if(!started && initialized) {
      expressConfig.setMiddleware(middleware);
      return this
    }
    this.error(new Error('Cannot set middleware after server start.'));
    return this
  };

  /**
   *  Provides a reference to the core express app object to attach global
   *  request handlers to.
   *
   * @param {Function} useFn
   * @returns {Pomegranate}
   */
  this.useGlobal = function(useFn){
    if(!started && initialized) {
      useFunctions.push(useFn)
      return this
    }
    this.error(new Error('Cannot add global handlers after server start.'));
    return this
  };
  /**
   * Overrides the default stack of error handlers, returns Pomegranate instance for chaining.
   *
   * @method setErrorHandlers
   * @memberof Pomegranate
   * @instance
   * @param {Function[]} errorHandlers
   * @returns {Pomegranate}
   */
  this.setErrorHandlers = function(errorHandlers){
    if(!started && initialized) {
      expressConfig.setErrorHandlers(errorHandlers);
      return this
    }
    this.error(new Error('Cannot set Error Handlers after server start.'));
    return this
  };
}
/**
 *
 * @type {Logger}
 */
Pomegranate.prototype = _.create(logger, {constructor: Pomegranate});

/**
 * An unassuming framework for building web applications.
 * @module Pomegranate
 * @returns {Pomegranate}
 */
process.on('uncaughtException', function(err){
  console.log(err)
  console.log(err.stack)
  console.log(chalk.red('Pomegranate has encountered an uncaught exception and will now exit.'))
})

module.exports = new Pomegranate();

/*
 * Utility
 */
function callAsDeterminer(name, item, instance){
  if(_.isString(name)){
    if(_.isFunction(item)) {
      if(instance){
        injector.instance(name, item)
      } else {
        injector.factory(name, item)
      }

    } else {
      injector.service(name, item)
    }
  }
}<|endoftext|>


<commit_before>/**
 * @file roll command
 * @author Sankarsan Kampa (a.k.a k3rn31p4nic)
 * @license GPL-3.0
 */

exports.exec = async (Bastion, message, args) => {
  let outcomes = [
    ':one:',
    ':two:',
    ':three:',
    ':four:',
    ':five:',
    ':six:'
  ];
  let outcome = outcomes.getRandom();

  if (args[0] && parseInt(args[0])) {
    args[0] = parseInt(args[0]);
    if (args[0] > 10) {
      args[0] = 50;
    }
    for (let i = 1; i < args[0]; i++) {
      outcome += outcomes.getRandom();
    }
  }

  await message.channel.send({
    embed: {
      color: Bastion.colors.BLUE,
      title: 'You rolled:',
      description: outcome
    }
  });
};

exports.config = {
  aliases: [],
  enabled: true
};

exports.help = {
  name: 'roll',
  description: 'Rolls the specified amount of dice and shows you the outcomes.',
  botPermission: '',
  userTextPermission: '',
  userVoicePermission: '',
  usage: 'roll [no_of_dice]',
  example: [ 'roll', 'roll 5' ]
};
<commit_msg>commands(games): minor improvements to roll command<commit_after>/**
 * @file roll command
 * @author Sankarsan Kampa (a.k.a k3rn31p4nic)
 * @license GPL-3.0
 */

exports.exec = async (Bastion, message, args) => {
  let outcomes = [
    ':one:',
    ':two:',
    ':three:',
    ':four:',
    ':five:',
    ':six:'
  ];
  let outcome = outcomes.getRandom();

  if (args.dice) {
    if (args.dice > 50) args.dice = 50;

    for (let i = 1; i < args.dice; i++) {
      outcome += ` ${outcomes.getRandom()}`;
    }
  }

  await message.channel.send({
    embed: {
      color: Bastion.colors.BLUE,
      title: 'Rolled',
      description: outcome
    }
  });
};

exports.config = {
  aliases: [],
  enabled: true,
  argsDefinitions: [
    { name: 'dice', type: Number, alias: 'c', defaultOption: true }
  ]
};

exports.help = {
  name: 'roll',
  description: 'Rolls the specified amount of dice and shows you the outcomes.',
  botPermission: '',
  userTextPermission: '',
  userVoicePermission: '',
  usage: 'roll [NO_OF_DICE]',
  example: [ 'roll', 'roll 5' ]
};
<|endoftext|>


<commit_before>"use strict";
var express = require("express");
var bodyParser = require('body-parser');
var morgan = require("morgan");
var util = require("util");
var EventEmitter = require("events").EventEmitter;

/**
 * Construct a new application service.
 * @constructor
 * @param {Object} config Configuration for this service.
 * @param {String} config.homeserverToken The incoming HS token to expect. Must
 * be set prior to calling listen(port).
 * @param {Number} config.httpMaxSizeBytes The max number of bytes allowed on an
 * incoming HTTP request. Default: 5000000.
 * @throws If a homeserver token is not supplied.
 */
function AppService(config) {
    var self = this;
    this.config = config || {};
    this.app = express();
    this.app.use(morgan("combined", {
        stream: {
            write: function(str) {
                /**
                 * An HTTP log line.
                 * @event AppService#http-log
                 * @type {String}
                 * @example
                 * appService.on("http-log", function(logLine) {
                 *   console.log(logLine);
                 * });
                 */
                var redacted_str = str.replace(/access_token=.*?(&|\s|$)/, "access_token=<REDACTED>$1");

                self.emit("http-log", redacted_str);
            }
        }
    }));

    this.app.use(bodyParser.json({
        limit: this.config.httpMaxSizeBytes || 5000000  // 5MB
    }));

    function isInvalidToken(req, res) {
        var hsToken = req.query.access_token;
        if (hsToken !== self.config.homeserverToken) {
            res.send({
                errcode: "M_FORBIDDEN",
                error: "Bad token supplied,"
            });
            return true;
        }
        return false;
    }

    this.app.get("/users/:userId", function(req, res) {
        if (isInvalidToken(req, res)) {
            return;
        }
        var possiblePromise = self.onUserQuery(req.params.userId, function() {
            res.send({});
        });
        if (possiblePromise) {
            possiblePromise.done(function() {
                res.send({});
            }, function(e) {
                res.send({
                    errcode: "M_UNKNOWN",
                    error: e ? e.message : ""
                });
            });
        }
    });

    this.app.get("/rooms/:alias", function(req, res) {
        if (isInvalidToken(req, res)) {
            return;
        }
        var possiblePromise = self.onAliasQuery(req.params.alias, function() {
            res.send({});
        });
        if (possiblePromise) {
            possiblePromise.done(function() {
                res.send({});
            }, function(e) {
                res.send({
                    errcode: "M_UNKNOWN",
                    error: e ? e.message : ""
                });
            });
        }
    });

    var lastProcessedTxnId;
    this.app.put("/transactions/:txnId", function(req, res) {
        if (isInvalidToken(req, res)) {
            return;
        }

        var txnId = req.params.txnId;
        if (!txnId) {
            res.send("Missing transaction ID.");
            return;
        }
        if (!req.body || !req.body.events) {
            res.send("Missing events body.");
            return;
        }
        var events = req.body.events;

        if (lastProcessedTxnId === txnId) {
            res.send({}); // duplicate
            return;
        }
        for (var i = 0; i < events.length; i++) {
            /**
             * An incoming Matrix JSON event.
             * @event AppService#event
             * @type {Object}
             * @example
             * appService.on("event", function(ev) {
             *   console.log("ID: %s", ev.event_id);
             * });
             */
            self.emit("event", events[i]);
            if (events[i].type) {
                /**
                 * An incoming Matrix JSON event, filtered by event.type
                 * @event AppService#type:event
                 * @type {Object}
                 * @example
                 * appService.on("type:m.room.message", function(ev) {
                 *   console.log("Body: %s", ev.content.body);
                 * });
                 */
                self.emit("type:" + events[i].type, events[i]);
            }
        }
        lastProcessedTxnId = txnId;
        res.send({});
    });
}
util.inherits(AppService, EventEmitter);

/**
 * Override this method to handle alias queries.
 * @param {string} alias The queried room alias
 * @param {Function} callback The callback to invoke when complete.
 * @return {Promise} A promise to resolve when complete (if callback isn't supplied)
 */
AppService.prototype.onAliasQuery = function(alias, callback) {
    callback(); // stub impl
    return null;
};

/**
 * Override this method to handle user queries.
 * @param {string} userId The queried user ID.
 * @param {Function} callback The callback to invoke when complete.
 * @return {Promise} A promise to resolve when complete (if callback isn't supplied)
 */
AppService.prototype.onUserQuery = function(userId, callback) {
    callback(); // stub impl
    return null;
};

/**
 * Set the token that should be used to verify incoming events.
 * @param {string} hsToken The home server token
 */
AppService.prototype.setHomeserverToken = function(hsToken) {
    this.config.homeserverToken = hsToken;
};

/**
 * Begin listening on the specified port.
 * @param {Number} port The port to listen on.
 * @param {String} hostname Optional hostname to listen on
 * @param {Number} backlog Maximum length of the queue of pending connections
 * @param {Function} callback The callback for the "listening" event
 */
AppService.prototype.listen = function(port, hostname, backlog, callback) {
    this.app.listen(port, hostname, backlog, callback);
};

/** The application service class */
module.exports = AppService;
<commit_msg>camelCase<commit_after>"use strict";
var express = require("express");
var bodyParser = require('body-parser');
var morgan = require("morgan");
var util = require("util");
var EventEmitter = require("events").EventEmitter;

/**
 * Construct a new application service.
 * @constructor
 * @param {Object} config Configuration for this service.
 * @param {String} config.homeserverToken The incoming HS token to expect. Must
 * be set prior to calling listen(port).
 * @param {Number} config.httpMaxSizeBytes The max number of bytes allowed on an
 * incoming HTTP request. Default: 5000000.
 * @throws If a homeserver token is not supplied.
 */
function AppService(config) {
    var self = this;
    this.config = config || {};
    this.app = express();
    this.app.use(morgan("combined", {
        stream: {
            write: function(str) {
                /**
                 * An HTTP log line.
                 * @event AppService#http-log
                 * @type {String}
                 * @example
                 * appService.on("http-log", function(logLine) {
                 *   console.log(logLine);
                 * });
                 */
                var redactedStr = str.replace(/access_token=.*?(&|\s|$)/, "access_token=<REDACTED>$1");

                self.emit("http-log", redactedStr);
            }
        }
    }));

    this.app.use(bodyParser.json({
        limit: this.config.httpMaxSizeBytes || 5000000  // 5MB
    }));

    function isInvalidToken(req, res) {
        var hsToken = req.query.access_token;
        if (hsToken !== self.config.homeserverToken) {
            res.send({
                errcode: "M_FORBIDDEN",
                error: "Bad token supplied,"
            });
            return true;
        }
        return false;
    }

    this.app.get("/users/:userId", function(req, res) {
        if (isInvalidToken(req, res)) {
            return;
        }
        var possiblePromise = self.onUserQuery(req.params.userId, function() {
            res.send({});
        });
        if (possiblePromise) {
            possiblePromise.done(function() {
                res.send({});
            }, function(e) {
                res.send({
                    errcode: "M_UNKNOWN",
                    error: e ? e.message : ""
                });
            });
        }
    });

    this.app.get("/rooms/:alias", function(req, res) {
        if (isInvalidToken(req, res)) {
            return;
        }
        var possiblePromise = self.onAliasQuery(req.params.alias, function() {
            res.send({});
        });
        if (possiblePromise) {
            possiblePromise.done(function() {
                res.send({});
            }, function(e) {
                res.send({
                    errcode: "M_UNKNOWN",
                    error: e ? e.message : ""
                });
            });
        }
    });

    var lastProcessedTxnId;
    this.app.put("/transactions/:txnId", function(req, res) {
        if (isInvalidToken(req, res)) {
            return;
        }

        var txnId = req.params.txnId;
        if (!txnId) {
            res.send("Missing transaction ID.");
            return;
        }
        if (!req.body || !req.body.events) {
            res.send("Missing events body.");
            return;
        }
        var events = req.body.events;

        if (lastProcessedTxnId === txnId) {
            res.send({}); // duplicate
            return;
        }
        for (var i = 0; i < events.length; i++) {
            /**
             * An incoming Matrix JSON event.
             * @event AppService#event
             * @type {Object}
             * @example
             * appService.on("event", function(ev) {
             *   console.log("ID: %s", ev.event_id);
             * });
             */
            self.emit("event", events[i]);
            if (events[i].type) {
                /**
                 * An incoming Matrix JSON event, filtered by event.type
                 * @event AppService#type:event
                 * @type {Object}
                 * @example
                 * appService.on("type:m.room.message", function(ev) {
                 *   console.log("Body: %s", ev.content.body);
                 * });
                 */
                self.emit("type:" + events[i].type, events[i]);
            }
        }
        lastProcessedTxnId = txnId;
        res.send({});
    });
}
util.inherits(AppService, EventEmitter);

/**
 * Override this method to handle alias queries.
 * @param {string} alias The queried room alias
 * @param {Function} callback The callback to invoke when complete.
 * @return {Promise} A promise to resolve when complete (if callback isn't supplied)
 */
AppService.prototype.onAliasQuery = function(alias, callback) {
    callback(); // stub impl
    return null;
};

/**
 * Override this method to handle user queries.
 * @param {string} userId The queried user ID.
 * @param {Function} callback The callback to invoke when complete.
 * @return {Promise} A promise to resolve when complete (if callback isn't supplied)
 */
AppService.prototype.onUserQuery = function(userId, callback) {
    callback(); // stub impl
    return null;
};

/**
 * Set the token that should be used to verify incoming events.
 * @param {string} hsToken The home server token
 */
AppService.prototype.setHomeserverToken = function(hsToken) {
    this.config.homeserverToken = hsToken;
};

/**
 * Begin listening on the specified port.
 * @param {Number} port The port to listen on.
 * @param {String} hostname Optional hostname to listen on
 * @param {Number} backlog Maximum length of the queue of pending connections
 * @param {Function} callback The callback for the "listening" event
 */
AppService.prototype.listen = function(port, hostname, backlog, callback) {
    this.app.listen(port, hostname, backlog, callback);
};

/** The application service class */
module.exports = AppService;
<|endoftext|>


<commit_before>'use strict';

var child_process = require('child_process');

var AtomHelper = {
  get apm() {
    return atom.packages.getApmPath();
  },

  isPackageInstalled: function() {
    return new Promise((resolve, reject) => {
      if (!this.apm) {
        reject();
        return;
      }
      var proc = child_process.spawn(this.apm, ['list'], {
        encoding: 'utf8',
      });
      var output = '';
      proc.stdout.on('data', (data) => {
        output += data.toString();
      });
      proc.on('close', (code) => {
        code || output.indexOf(' kite@') === -1 ? reject() : resolve();
      });
    });
  },

  installPackage: function() {
    return this.apm && atom && !atom.packages.getAvailablePackageNames().includes('kite')
      ? child_process.spawn(this.apm, ['install', 'kite'])
      : null;
  },

  activatePackage: function() {
    return atom && !atom.packages.getActivePackage('kite')
      ? atom.packages.activatePackage('kite')
      : null;
  },

  deactivatePackage: function() {
    if (!atom) {
      return false;
    }
    if (atom.packages.isPackageActive('kite')) {
      atom.packages.deactivatePackage('kite');
    }
    if (atom.packages.isPackageLoaded('kite')) {
      atom.packages.unloadPackage('kite');
    }
    return true;
  },

  enablePackage: function() {
    return atom ? atom.packages.enablePackage('kite') : null;
  },

  disablePackage: function() {
    return atom ? atom.packages.disablePackage('kite') : null;
  },

  refreshPackage: function() {
    if (!atom || !this.apm) {
      return null;
    }
    return new Promise((resolve, reject) => {
      this.deactivatePackage();
      var proc = this.installPackage();
      proc.on('close', (code) => {
        if (code) {
          reject(code);
        } else {
          this.activatePackage().then(() => {
            this.enablePackage();
          });
          resolve();
        }
      });
    });
  },
};

module.exports = AtomHelper;
<commit_msg>:bug: Fix post install package start issue<commit_after>'use strict';

const {spawnPromise} = require('./utils');

var AtomHelper = {
  get apm() {
    return atom.packages.getApmPath();
  },

  isPackageInstalled: function() {
    return atom.packages.getAvailablePackageNames().includes('kite')
      ? Promise.resolve()
      : Promise.reject();
  },

  installPackage: function() {
    return this.apm && atom && !atom.packages.getAvailablePackageNames().includes('kite')
      ? spawnPromise(this.apm, ['install', 'kite'])
      : null;
  },

  activatePackage: function() {
    return atom && !atom.packages.getActivePackage('kite')
      ? atom.packages.activatePackage('kite')
      : null;
  },

  deactivatePackage: function() {
    if (!atom) {
      return false;
    }
    if (atom.packages.isPackageActive('kite')) {
      atom.packages.deactivatePackage('kite');
    }
    if (atom.packages.isPackageLoaded('kite')) {
      atom.packages.unloadPackage('kite');
    }
    return true;
  },

  enablePackage: function() {
    return atom ? atom.packages.enablePackage('kite') : null;
  },

  disablePackage: function() {
    return atom ? atom.packages.disablePackage('kite') : null;
  },

  refreshPackage: function() {
    if (!atom || !this.apm) {
      return null;
    }
    return new Promise((resolve, reject) => {
      this.deactivatePackage();
      var proc = this.installPackage();
      proc.on('close', (code) => {
        if (code) {
          reject(code);
        } else {
          this.activatePackage().then(() => {
            this.enablePackage();
          });
          resolve();
        }
      });
    });
  },
};

module.exports = AtomHelper;
<|endoftext|>


<commit_before>/*
Importante
------------------------------------
discord
npm install discord.js
npm install --save discord-webhooks
------------------------------------
Music bot
ffmpeg - npm install ffmpeg-binaries
npm install --save hydrabolt/prism-media
an opus encoder, choose one from below:
npm install opusscript
npm install node-opus
------------------------------------
Radios
Radio Moe : https://listen.moe/stream
Radio AnimeNfo : http://momori.animenfo.com:8000/;?.mp3
Radio Initial D : http://go2id.net:9001/;?.mp3
------------------------------------
->git bash
.gitignore
gitstatus
git add .
git commit -m "update"
~
->remove file
gitstatus
git rm [file name]
git commit -m "remove"
------------------------------------
github / git kraken / heroku
*/<commit_msg><commit_after>/*
Importante
------------------------------------
discord
npm install discord.js
npm install --save discord-webhooks
------------------------------------
Music bot
ffmpeg - npm install ffmpeg-binaries
npm install --save hydrabolt/prism-media
an opus encoder, choose one from below:
npm install opusscript
npm install node-opus
------------------------------------
Radios
Radio Moe : https://listen.moe/stream
Radio AnimeNfo : http://momori.animenfo.com:8000/;?.mp3
Radio Initial D : http://go2id.net:9001/;?.mp3
------------------------------------
Bot falar mensagens TTS
bot.sendMessage({ to: "userID/channelID", message: "Hello World", tts: true });
------------------------------------
->git bash
.gitignore
gitstatus
git add .
git commit -m "update"
~
->remove file
gitstatus
git rm [file name]
git commit -m "remove"
------------------------------------
github / git kraken / heroku
*/<|endoftext|>


<commit_before>'use strict'
var Base = require('./')

/**
 * @function removeUpdateParent
 * remove base from parent
 * @memberOf Base#
 * @param {base} parent if not defined returns true
 * @param {event} event passedon event
 * @param {base} context checks if context has to be resolved
 * @return {boolean|undefined} if true nothing happened
 */
exports.removeUpdateParent = function (parent, event, context) {
  if (parent[this.key] === null) {
    return true
  }
  if (context) {
    if (this._context) {
      this.resolveContext(null, event, context)
    }
  } else {
    parent[this.key] = null
  }
}

/**
 * @function removeProperty
 * removeProperty from a base
 * @memberOf Base#
 * @param {property} base property to be removed
 * @param {key} key of the property
 * @param {event} event passedon event
 * @param {base} context checks if context has to be resolved
 * @param {nocontext} [boolean] dont resolveContext when true
 * @return {boolean|undefined} if true nothing happened
 * @todo how to get rid of the non-enum stuff?
 * @todo cleanup and make faster
 * @todo system for excludes (e.g. noremovable or something)
 */
exports.removeProperty = function (property, key, event, nocontext) {
  if (key !== 'key') {
    if (this.hasOwnProperty(key)) {
      if (key !== '_parent') {
        if (property instanceof Base) {
          if (key !== '_input') {
            // block if everything is allreayd removed?
            if (property._parent === this) {
              // TODO: 10 double check this....
              property.clearContext()
              property.remove(event, nocontext)
            }
          }
        }
      }
      this[key] = null
    } else {
      if (this._context) {
        console.warn('maybe some stuff going wrong with context here in removeprop')
      }
      this[key] = null
    }
  }
}

/**
 * @function removeProperties
 * remove properties from base
 * @memberOf Base#
 * @param {base} parent if not defined returns true
 * @param {event} event passedon event
 * @param {nocontext} [boolean] dont resolveContext when true
 */
exports.removeProperties = function (event, nocontext, noparent) {
  for (var key in this) {
    if (key === '_parent') {
      continue
    } else {
      this.removeProperty(this[key], key, event, nocontext)
    }
  }
  this._parent = null
  this.parent = null
  this._input = null
}

exports.removeInternal = function( event, nocontext, noparent ) {
  var parent = this._parent
  if( !noparent && !nocontext && this._context ) {
    return this.removeUpdateParent( this.parent, event, this._context )
  } else {
    if( !noparent && parent ) {
      this.removeUpdateParent( parent, event )
    }
    this.removeProperties(  event, nocontext, noparent )
  }
}

exports.remove = function( event, nocontext, noparent ) {
  // if( this._input === null ) {
  //   console.warn( 'already removed' )
  //   return true
  // }
  return this.removeInternal( event, nocontext, noparent )
}
<commit_msg>cleaned up remove<commit_after>'use strict'
var Base = require('./')

/**
 * @function removeUpdateParent
 * remove base from parent
 * @memberOf Base#
 * @param {base} parent if not defined returns true
 * @param {event} event passedon event
 * @param {base} context checks if context has to be resolved
 * @return {boolean|undefined} if true nothing happened
 */
exports.removeUpdateParent = function (parent, event, context) {
  if (parent[this.key] === null) {
    return true
  }
  if (context) {
    if (this._context) {
      this.resolveContext(null, event, context)
    }
  } else {
    parent[this.key] = null
  }
}

/**
 * @function removeProperty
 * removeProperty from a base
 * @memberOf Base#
 * @param {property} base property to be removed
 * @param {key} key of the property
 * @param {event} event passedon event
 * @param {base} context checks if context has to be resolved
 * @param {nocontext} [boolean] dont resolveContext when true
 * @return {boolean|undefined} if true nothing happened
 * @todo how to get rid of the non-enum stuff?
 * @todo cleanup and make faster
 * @todo system for excludes (e.g. noremovable or something)
 */
exports.removeProperty = function (property, key, event, nocontext) {
  if (key !== 'key') {
    if (this.hasOwnProperty(key)) {
      if (key !== '_parent') {
        if (property instanceof Base) {
          if (key !== '_input') {
            // block if everything is allreayd removed?
            if (property._parent === this) {
              // TODO: 10 double check this....
              property.clearContext()
              property.remove(event, nocontext)
            }
          }
        }
      }
      this[key] = null
    } else {
      if (this._context) {
        console.warn('maybe some stuff going wrong with context here in removeprop')
      }
      this[key] = null
    }
  }
}

/**
 * @function removeProperties
 * remove properties from base
 * @memberOf Base#
 * @param {event} event passedon event
 * @param {nocontext} [boolean] dont resolveContext when true
 */
exports.removeProperties = function (event, nocontext) {
  for (var key in this) {
    if (key === '_parent') {
      continue
    } else {
      this.removeProperty(this[key], key, event, nocontext)
    }
  }
  this._parent = null
  this.parent = null
  this._input = null
}

/**
 * @function removeInternal
 * remove properties from base
 * @memberOf Base#
 * @param {event} event passedon event
 * @param {nocontext} [boolean] dont resolveContext when true
 * @param {noparent} [boolean] dont remove from parent when true
 * @return {true|undefined} if true no updates happened on parent
 * @todo return a base when a change happened (consistency)
 */
exports.removeInternal = function (event, nocontext, noparent) {
  var parent = this._parent
  if (!noparent && !nocontext && this._context) {
    return this.removeUpdateParent(this.parent, event, this._context)
  } else {
    if (!noparent && parent) {
      this.removeUpdateParent(parent, event)
    }
    this.removeProperties(event, nocontext, noparent)
  }
}

/**
 * @function remove
 * remove a base
 * @memberOf Base#
 * @param {event} event passedon event
 * @param {nocontext} [boolean] dont resolveContext when true
 * @param {noparent} [boolean] dont remove from parent when true
 * @return {true|undefined} if true no updates happened
 * @todo return a base when a change happened (consistency)
 */
exports.remove = function (event, nocontext, noparent) {
  return this.removeInternal(event, nocontext, noparent)
}
<|endoftext|>


<commit_before>window.Bloob = window.Bloob  || {};

/*
	// basic
	.include(includePath + "external/" + "libraryextensions")
	.include(basicPath + "constants")
	.include(basicPath + "utils")
	.include(basicPath + "uniqueidgenerator")

	.include(assetsPath + "assetmanager")
	.include(assetsPath + "loadassembler")
	.include(assetsPath + "loader")

	.include(basicPath + "gui")
	.include(basicPath + "camera")
	.include(basicPath + "interactionhandler")
	.include(basicPath + "interactionhandlerbuilder")

	// audio
	.include(basicPath + "audio/audio")
	.include(basicPath + "audio/sound")

	.include(basicPath + "audio/music")

	// physics
	// lib already included in .html
	//.include(physicsPath + "jellyphysics")

	//.include(physicsPath + "queue")

	//.include(physicsPath + "bitmask")

	//.include(physicsPath + "internalspring")

	//.include(physicsPath + "jellyprerequisites")
	//.include(physicsPath + "vector2")
	//.include(physicsPath + "pointmass")
	//.include(physicsPath + "aabb") // needs vector2
	//.include(physicsPath + "vectortools") // needs vector2, jellyprerequisites
	//.include(physicsPath + "closedshape") // needs VectorTools, JellyPrerequisites, Vector2

	//.include(physicsPath + "body") // needs VectorTools, JellyPrerequisites, Vector2, ClosedShape, Bitmask, AABB, PointMass
	//.include(physicsPath + "bodycollisioninfo") // vector2
	//.include(physicsPath + "materialmanager")
	//.include(physicsPath + "world")
	//.include(physicsPath + "springbody") // Body, InternalSpring, World, VectorTools
	//.include(physicsPath + "pressurebody") // springbody

	//.include(physicsPath + "ray") // vector, ...

	//.include(physicsPath + "bodybuilder")
	//.include(physicsPath + "bodyblueprint") // provides chainable interface for creation of bodies
	//.include(physicsPath + "bodyfactory") //
	//.include(physicsPath + "particle") //
	//.include(physicsPath + "particlecannon") //

	//.include(physicsPath + "joints/distancejoint") //
	//.include(physicsPath + "joints/pinjoint") //
	//.include(physicsPath + "joints/interpolationjoint") //

	//.include(physicsPath + "springbuilder") // springbody

	//.include(physicsPath + "contactmanager")

	.include(renderingPath + "debugdraw/debugdraw")
	// basic canvas
	.include(basicPath + "canvas")

	// basic for map
	.include(basicPath + "map")
	// from json conversion
	.include(assetsPath + "converter/fromjson/jsontovector2converter")
	.include(assetsPath + "converter/fromjson/jsontointernalspringconverter")
	.include(assetsPath + "converter/fromjson/jsontoclosedshapeconverter")
	.include(assetsPath + "converter/fromjson/jsontobodyconverter")
	.include(assetsPath + "converter/fromjson/jsontoworldconverter")
	.include(assetsPath + "converter/decompressmapjson")
	.include(assetsPath + "converter/fromjson/jsontomapconverter")
	// to json conversion
	.include(assetsPath + "converter/tojson/vector2tojsonconverter")
	.include(assetsPath + "converter/tojson/internalspringtojsonconverter")
	.include(assetsPath + "converter/tojson/closedshapetojsonconverter")
	.include(assetsPath + "converter/tojson/bodytojsonconverter")
	.include(assetsPath + "converter/tojson/worldtojsonconverter")
	.include(assetsPath + "converter/tojson/maptojsonconverter")

	// logic
	.include(logicPath + "entity")

	// basic for builder
	.include(basicPath + "shapebuilder")
	.include(basicPath + "mapbuilder")

	// TODO: move mouse to top after refactoring
	.include(basicPath + "mouse")
	// scenes
	.include(scenesPath + "scene")
	.include(scenesPath + "mapscene")
	.include(scenesPath + "editorscene")
	.include(scenesPath + "titlescene")
	.include(scenesPath + "transition")

	// game
	.include(gamePath + "loop")
	.include(gamePath + "config")
	.include(gamePath + "game")
	.include(gamePath + "main");
	;
	*/

mini.Module(
	"bloob/bloob"
)
.requires(
	"engine/main",
	"engine/game",
	"engine/config",
	"basic/audio/sound",
	"basic/audio/music",
	"bloob/scenes/titlescene"
)
.defines(function(main, Game, Config, Sound, Track, TitleScene) {
	var BloobGame = Game.subclass({
		initialize: function(configuration) {
			Game.prototype.initialize.apply(this, arguments);

			this.testAudio();

			var titleScene = new TitleScene(this, this.loop).run();
		},

		testAudio: function() {
			var audioFolder = this.datGui.addFolder("Audio");
			audioFolder.open();
			audioFolder.add(this.audio.trackParent.gain, 'value').name('TrackVolume').min(0.0).max(1.0).listen().step(0.1);
			audioFolder.add(this.audio.soundParent.gain, 'value').name('SoundVolume').min(0.0).max(1.0).listen().step(0.1);

			var testSound = new Sound(this.audio, "data/audio/sounds/test/cursor_sounds/water-bubble-high.wav");
			audioFolder.add(testSound, "play").name('play test sound');

			var testTrack = new Track(this.audio, "data/audio/music/test/217741_vibe_timid_girl.mp3");
			audioFolder.add(testTrack, "play").name('play test track');
			audioFolder.add(testTrack, '_volume')
				.name('track volume')
				.min(0.0)
				.max(1.0)
				.listen()
				.step(0.1)
				.onChange(function(volume) {
					testTrack.setVolume(volume);
				});
		}
	});

	// start several Game instances
	main(BloobGame, new Config().setStartLevel("SecondMap"));
	main(BloobGame, new Config().setStartLevel("SecondMap"));
	main(BloobGame);
});
<commit_msg>removed Bloob from global namespace<commit_after>/*
	// basic
	.include(includePath + "external/" + "libraryextensions")
	.include(basicPath + "constants")
	.include(basicPath + "utils")
	.include(basicPath + "uniqueidgenerator")

	.include(assetsPath + "assetmanager")
	.include(assetsPath + "loadassembler")
	.include(assetsPath + "loader")

	.include(basicPath + "gui")
	.include(basicPath + "camera")
	.include(basicPath + "interactionhandler")
	.include(basicPath + "interactionhandlerbuilder")

	// audio
	.include(basicPath + "audio/audio")
	.include(basicPath + "audio/sound")

	.include(basicPath + "audio/music")

	// physics
	// lib already included in .html
	//.include(physicsPath + "jellyphysics")

	//.include(physicsPath + "queue")

	//.include(physicsPath + "bitmask")

	//.include(physicsPath + "internalspring")

	//.include(physicsPath + "jellyprerequisites")
	//.include(physicsPath + "vector2")
	//.include(physicsPath + "pointmass")
	//.include(physicsPath + "aabb") // needs vector2
	//.include(physicsPath + "vectortools") // needs vector2, jellyprerequisites
	//.include(physicsPath + "closedshape") // needs VectorTools, JellyPrerequisites, Vector2

	//.include(physicsPath + "body") // needs VectorTools, JellyPrerequisites, Vector2, ClosedShape, Bitmask, AABB, PointMass
	//.include(physicsPath + "bodycollisioninfo") // vector2
	//.include(physicsPath + "materialmanager")
	//.include(physicsPath + "world")
	//.include(physicsPath + "springbody") // Body, InternalSpring, World, VectorTools
	//.include(physicsPath + "pressurebody") // springbody

	//.include(physicsPath + "ray") // vector, ...

	//.include(physicsPath + "bodybuilder")
	//.include(physicsPath + "bodyblueprint") // provides chainable interface for creation of bodies
	//.include(physicsPath + "bodyfactory") //
	//.include(physicsPath + "particle") //
	//.include(physicsPath + "particlecannon") //

	//.include(physicsPath + "joints/distancejoint") //
	//.include(physicsPath + "joints/pinjoint") //
	//.include(physicsPath + "joints/interpolationjoint") //

	//.include(physicsPath + "springbuilder") // springbody

	//.include(physicsPath + "contactmanager")

	.include(renderingPath + "debugdraw/debugdraw")
	// basic canvas
	.include(basicPath + "canvas")

	// basic for map
	.include(basicPath + "map")
	// from json conversion
	.include(assetsPath + "converter/fromjson/jsontovector2converter")
	.include(assetsPath + "converter/fromjson/jsontointernalspringconverter")
	.include(assetsPath + "converter/fromjson/jsontoclosedshapeconverter")
	.include(assetsPath + "converter/fromjson/jsontobodyconverter")
	.include(assetsPath + "converter/fromjson/jsontoworldconverter")
	.include(assetsPath + "converter/decompressmapjson")
	.include(assetsPath + "converter/fromjson/jsontomapconverter")
	// to json conversion
	.include(assetsPath + "converter/tojson/vector2tojsonconverter")
	.include(assetsPath + "converter/tojson/internalspringtojsonconverter")
	.include(assetsPath + "converter/tojson/closedshapetojsonconverter")
	.include(assetsPath + "converter/tojson/bodytojsonconverter")
	.include(assetsPath + "converter/tojson/worldtojsonconverter")
	.include(assetsPath + "converter/tojson/maptojsonconverter")

	// logic
	.include(logicPath + "entity")

	// basic for builder
	.include(basicPath + "shapebuilder")
	.include(basicPath + "mapbuilder")

	// TODO: move mouse to top after refactoring
	.include(basicPath + "mouse")
	// scenes
	.include(scenesPath + "scene")
	.include(scenesPath + "mapscene")
	.include(scenesPath + "editorscene")
	.include(scenesPath + "titlescene")
	.include(scenesPath + "transition")

	// game
	.include(gamePath + "loop")
	.include(gamePath + "config")
	.include(gamePath + "game")
	.include(gamePath + "main");
	;
	*/

mini.Module(
	"bloob/bloob"
)
.requires(
	"engine/main",
	"engine/game",
	"engine/config",
	"basic/audio/sound",
	"basic/audio/music",
	"bloob/scenes/titlescene"
)
.defines(function(main, Game, Config, Sound, Track, TitleScene) {
	var BloobGame = Game.subclass({
		initialize: function(configuration) {
			Game.prototype.initialize.apply(this, arguments);

			this.testAudio();

			var titleScene = new TitleScene(this, this.loop).run();
		},

		testAudio: function() {
			var audioFolder = this.datGui.addFolder("Audio");
			audioFolder.open();
			audioFolder.add(this.audio.trackParent.gain, 'value').name('TrackVolume').min(0.0).max(1.0).listen().step(0.1);
			audioFolder.add(this.audio.soundParent.gain, 'value').name('SoundVolume').min(0.0).max(1.0).listen().step(0.1);

			var testSound = new Sound(this.audio, "data/audio/sounds/test/cursor_sounds/water-bubble-high.wav");
			audioFolder.add(testSound, "play").name('play test sound');

			var testTrack = new Track(this.audio, "data/audio/music/test/217741_vibe_timid_girl.mp3");
			audioFolder.add(testTrack, "play").name('play test track');
			audioFolder.add(testTrack, '_volume')
				.name('track volume')
				.min(0.0)
				.max(1.0)
				.listen()
				.step(0.1)
				.onChange(function(volume) {
					testTrack.setVolume(volume);
				});
		}
	});

	// start several Game instances
	main(BloobGame, new Config().setStartLevel("SecondMap"));
	main(BloobGame, new Config().setStartLevel("SecondMap"));
	main(BloobGame);
});
<|endoftext|>


<commit_before>var nodemailer = require('nodemailer');
var argv = require('optimist')
    .usage('Usage: $0 --recipient ["comma-separated list of email addresses"] --url ["http://your.link.com"] --size [bytes]')
    .demand(['recipient','url'])
    .argv;
var from_email = 'trufflehunter.webservice@gmail.com'; // Change this to something legitimate

// Create a Sendmail transport object
var transport = nodemailer.createTransport("Sendmail", "/usr/sbin/sendmail");
var url = argv.url,
    recipient = argv.recipient,
    bytes = argv.bytes || 'unknown';

    //console.log('Sendmail Configured');

// Message object
var message = {
    from: 'PgBadger Web Service <' + from_email + '>',

    // Comma separated list of recipients
    to: recipient,

    // Subject of the message
    subject: 'PgBadger results',

    // plain-text body
    test:'PgBadger parsed log file results.'+
         'Results: ' + url +
         'Original file size: ' + bytes + ' bytes',

    // HTML body
    html:'
PgBadger parsed log file results.
'+
         '
Results: ' + url + '
'+
         '
Original file size: ' + bytes + ' bytes
',

};

//console.log('Sending Mail');

transport.sendMail(message, function(error){
    if (error) {
        console.log('Error occured sending email via Nodemailer.');
        console.log(error.message);
        return;
    }
    //console.log('Message sent successfully!');
    transport.close(); // shut down the connection pool, no more messages. Comment this line out to continue sending emails.
});
<commit_msg>Added default email address to send_email.js<commit_after>var nodemailer = require('nodemailer');
var argv = require('optimist')
    .usage('Usage: $0 --recipient ["comma-separated list of email addresses"] --url ["http://your.link.com"] --size [bytes]')
    .demand(['recipient','url'])
    .argv;
var from_email = 'user@example.com'; // Change this to something legitimate

// Create a Sendmail transport object
var transport = nodemailer.createTransport("Sendmail", "/usr/sbin/sendmail");
var url = argv.url,
    recipient = argv.recipient,
    bytes = argv.bytes || 'unknown';

    //console.log('Sendmail Configured');

// Message object
var message = {
    from: 'PgBadger Web Service <' + from_email + '>',

    // Comma separated list of recipients
    to: recipient,

    // Subject of the message
    subject: 'PgBadger results',

    // plain-text body
    test:'PgBadger parsed log file results.'+
         'Results: ' + url +
         'Original file size: ' + bytes + ' bytes',

    // HTML body
    html:'
PgBadger parsed log file results.
'+
         '
Results: ' + url + '
'+
         '
Original file size: ' + bytes + ' bytes
',

};

//console.log('Sending Mail');

transport.sendMail(message, function(error){
    if (error) {
        console.log('Error occured sending email via Nodemailer.');
        console.log(error.message);
        return;
    }
    //console.log('Message sent successfully!');
    transport.close(); // shut down the connection pool, no more messages. Comment this line out to continue sending emails.
});
<|endoftext|>


<commit_before>/**
 * Created by kelvinzhang on 7/1/17.
 */

window.onerror = function (msg, url, lineNo, columnNo, error)
{
	var string = msg.toLowerCase();
	var substring = "script error";
	if (string.indexOf(substring) > -1)
	{
		alert('Script Error: See Browser Console for Detail');
	} else
	{
		var message = [
			'Message: ' + msg,
			'URL: ' + url,
			'Line: ' + lineNo,
			'Column: ' + columnNo,
			'Error object: ' + JSON.stringify(error)
		].join(' - ');

		alert(message);
	}
	return false;
};

var simpleActuation;
var a1Demo;
var a2Demo;
var a3Demo;
var a4Demo;

var measurementDemo;
var sensorDemo;

var motionDemo;
var a1MDemo;
var a2MDemo;
var a3MDemo;
var a4MDemo;

var mclDemo;

const actuationNoiseSliderFormat = {
	min: 0,
	max: 1,
	step: 0.05,
	value: 0.01,
	formatter: function (value)
	{
		return round(value * 100) + '%';
	}
};

function initMotionDemo()
{
	const path = vanillaPath;
	const x = path[0].x;
	const y = path[0].y;
	const dir = atan2(path[1].y - path[0].y, path[1].x - path[0].x);
	const filter = new ParticleFilter(
		500,
		new OdometryModel(
			getValue('motion_a1') / 100.0,
			getValue('motion_a2') / 100.0,
			getValue('motion_a3') / 100.0,
			getValue('motion_a4') / 100.0),
		undefined,
		new RobotState(x, y, dir),
		0);
	var slider = new Slider("#motion_stride");

	//Individual Simulations
	const s_path = simPath;
	const st_path = straightPath;
	const s_x = s_path[0].x;
	const s_y = s_path[0].y;
	const s_dir = atan2(s_path[1].y - s_path[0].y, s_path[1].x - s_path[0].x);
	const st_x = st_path[0].x;
	const st_y = st_path[0].y;
	const st_dir = atan2(st_path[1].y - st_path[0].y, st_path[1].x - st_path[0].x);
	const exaggerateFilterNoise = 0.3;
	const smallParticleCount = 100;
	const filtera1 = new ParticleFilter(
		smallParticleCount,
		new OdometryModel(
			exaggerateFilterNoise,
			0,
			0,
			0
		),
		undefined,
		new RobotState(s_x, s_y, s_dir),
		0);
	const filtera2 = new ParticleFilter(
		smallParticleCount,
		new OdometryModel(
			0,
			exaggerateFilterNoise,
			0,
			0
		),
		undefined,
		new RobotState(st_x, st_y, st_dir),
		0);
	const filtera3 = new ParticleFilter(
		smallParticleCount,
		new OdometryModel(
			0,
			0,
			exaggerateFilterNoise,
			0
		),
		undefined,
		new RobotState(st_x, st_y, st_dir),
		0);
	const filtera4 = new ParticleFilter(
		smallParticleCount,
		new OdometryModel(
			0,
			0,
			0,
			exaggerateFilterNoise
		),
		undefined,
		new RobotState(s_x, s_y, s_dir),
		0);

	slider.on("slide", function (sliderValue)
	{
		motionDemo.setStride(sliderValue);
		a1MDemo.setStride(sliderValue);
		a2MDemo.setStride(sliderValue);
		a3MDemo.setStride(sliderValue);
		a4MDemo.setStride(sliderValue);
	});

	var a1Slider = new Slider('#motion_a1', actuationNoiseSliderFormat);
	var a2Slider = new Slider('#motion_a2', actuationNoiseSliderFormat);
	var a3Slider = new Slider('#motion_a3', actuationNoiseSliderFormat);
	var a4Slider = new Slider('#motion_a4', actuationNoiseSliderFormat);

	a1Slider.on('slide', function (value)
	{
		motionDemo.setA1(value);
		a1MDemo.setA1(value);
	});
	a2Slider.on('slide', function (value)
	{
		motionDemo.setA2(value);
		a2MDemo.setA2(value);
	});
	a3Slider.on('slide', function (value)
	{
		motionDemo.setA3(value);
		a3MDemo.setA3(value);
	});
	a4Slider.on('slide', function (value)
	{
		motionDemo.setA4(value);
		a4MDemo.setA4(value);
	});

	var robot = new Robot(filter, path, 0, 0, slider.getValue());
	var robotA1 = new Robot(filtera1, s_path, 0, 0, slider.getValue());
	var robotA2 = new Robot(filtera2, st_path, 0, 0, slider.getValue());
	var robotA3 = new Robot(filtera3, st_path, 0, 0, slider.getValue());
	var robotA4 = new Robot(filtera4, s_path, 0, 0, slider.getValue());
	motionDemo = new RobotDemo('motion_canvas', 'motion_minicanvas', getMap(), robot, 10);
	a1MDemo = new RobotDemo('motion_a1_demo', ' ', getSimMap(), robotA1, 10);
	a2MDemo = new RobotDemo('motion_a2_demo', ' ', getSimMap(), robotA2, 10);
	a3MDemo = new RobotDemo('motion_a3_demo', ' ', getSimMap(), robotA3, 10);
	a4MDemo = new RobotDemo('motion_a4_demo', ' ', getSimMap(), robotA4, 10);
}

function initMCLDemo()
{
	var slider = new Slider("#mcl_stride", {
		min: 0.01,
		max: 0.2,
		step: 0.01,
		value: 0.04
	});
	slider.on("slide", function (sliderValue)
	{
		mclDemo.setStride(sliderValue);
	});

	var a1Slider = new Slider('#mcl_a1', actuationNoiseSliderFormat);
	var a2Slider = new Slider('#mcl_a2', actuationNoiseSliderFormat);
	var a3Slider = new Slider('#mcl_a3', actuationNoiseSliderFormat);
	var a4Slider = new Slider('#mcl_a4', actuationNoiseSliderFormat);

	a1Slider.on('slide', function (value)
	{
		mclDemo.setA1(value)
	});
	a2Slider.on('slide', function (value)
	{
		mclDemo.setA2(value)
	});
	a3Slider.on('slide', function (value)
	{
		mclDemo.setA3(value)
	});
	a4Slider.on('slide', function (value)
	{
		mclDemo.setA4(value)
	});

	var sensorRadiusSlider = new Slider('#mcl_sensorRadius', {
		min: 1,
		max: 10,
		step: 0.5
	});
	sensorRadiusSlider.on('slide', function (value)
	{
		mclDemo.setSensorRadius(value);
	});

	var sensorNoiseSlider = new Slider('#mcl_sensorNoise', {
		min: 0,
		max: 3,
		step: 0.1
	});
	sensorNoiseSlider.on('slide', function (value)
	{
		mclDemo.setSensorNoise(value);
	});

	var colorResSlider = new Slider('#mcl_colorRes', {
		min: 1,
		max: 20,
		step: 1
	});
	colorResSlider.on('slide', function (value)
	{
		measurementDemo.setColoringResolution(value);
	});

	var pRatioSlider = new Slider('#mcl_pRatio', {
		min: 0,
		max: 1,
		step: 0.01,
		formatter: function (value)
		{
			return round(value * 100) + "%";
		}
	});
	pRatioSlider.on('slide', function (value)
	{
		mclDemo.robot.filter.resampleRatio = value;
	});

	const path = vanillaPath;
	const x = path[0].x;
	const y = path[0].y;
	const dir = atan2(path[1].y - path[0].y, path[1].x - path[0].x);
	const filter = new ParticleFilter(
		getValue('mcl_nParticles'),
		new OdometryModel(
			a1Slider.getValue(),
			a2Slider.getValue(),
			a3Slider.getValue(),
			a4Slider.getValue()),
		new BeamModel(
			sensorNoiseSlider.getValue(),
			sensorRadiusSlider.getValue(),
			getMap()),
		new RobotState(x, y, dir),
		pRatioSlider.getValue());
	robot = new Robot(filter, path, 19, getValue('mcl_sensorRadius'), getValue('mcl_stride'));
	mclDemo = new RobotDemo('mcl_canvas', 'mcl_minicanvas', getMap(), robot, 10);
}

function simulateAllActuations()
{
	a1Demo.simulateActuation();
	a2Demo.simulateActuation();
	a3Demo.simulateActuation();
	a4Demo.simulateActuation();
}

function initActuationDemo()
{
	//Noise parameters
	const a1 = 0.02;
	const a2 = 0.02;
	const a3 = 0.02;
	const a4 = 0.02;

	const firstMove = 2;
	const turn = Math.PI / 6;
	const secondMove = 2;

	simpleActuation = new ActuationDemo('simple_actuation', firstMove, turn, secondMove,
		a1, a2, a3, a4);
	simpleActuation.simulateActuation();

	var noiseSlider = new Slider('#actuation_noise', actuationNoiseSliderFormat);
	const noise = noiseSlider.getValue();
	a1Demo = new ActuationDemo('actuation_a1', firstMove, turn, secondMove,
		noise, 0, 0, 0);
	a2Demo = new ActuationDemo('actuation_a2', firstMove, turn, secondMove,
		0, noise, 0, 0);
	a3Demo = new ActuationDemo('actuation_a3', firstMove, turn, secondMove,
		0, 0, noise, 0);
	a4Demo = new ActuationDemo('actuation_a4', firstMove, turn, secondMove,
		0, 0, 0, noise);
	noiseSlider.on('slide', function (sliderValue)
	{
		a1Demo.setA1(sliderValue);
		a2Demo.setA2(sliderValue);
		a3Demo.setA3(sliderValue);
		a4Demo.setA4(sliderValue);
	});
	noiseSlider.on('slideStop', simulateAllActuations);
	simulateAllActuations();
}

function initMeasurementDemo()
{
	var map = getMap();
	compactMap(map);
	var nLasersSlider = new Slider('#nLasers', {
		min: 6,
		max: 36,
		step: 1
	});
	nLasersSlider.on('slide', function (value)
	{
		measurementDemo.setNLasers(value)
	});
	nLasersSlider.on('slideStop', function ()
	{
		measurementDemo.colorMapIfShould();
	});

	var sensorRadiusSlider = new Slider('#sensorRadius', {
		min: 1,
		max: 10,
		step: 0.5
	});
	sensorRadiusSlider.on('slide', function (value)
	{
		measurementDemo.setSensorRadius(value);
	});
	sensorRadiusSlider.on('slideStop', function ()
	{
		measurementDemo.colorMapIfShould();
	});

	var sensorNoiseSlider = new Slider('#sensorNoise', {
		min: 0,
		max: 3,
		step: 0.1
	});
	sensorNoiseSlider.on('slide', function (value)
	{
		measurementDemo.setSensorNoise(value);
	});
	sensorNoiseSlider.on('slideStop', function ()
	{
		measurementDemo.colorMapIfShould();
	});

	var colorResSlider = new Slider('#colorRes', {
		min: 1,
		max: 20,
		step: 1
	});
	colorResSlider.on('slide', function (value)
	{
		measurementDemo.setColoringResolution(value);
	});
	colorResSlider.on('slideStop', function ()
	{
		measurementDemo.colorMapIfShould();
	});

	measurementDemo = new BeamModelDemo('sensor_model_demo', map,
		sensorRadiusSlider.getValue(), sensorNoiseSlider.getValue());
}

function onFirstAppear(selector, callback)
{
	$(selector).appear().on('appear', function (event, $targets)
	{
		callback(event, $targets);
		$(selector).off('appear');
	});
}

function initSensorDemo(id)
{
	var noiseSlider = new Slider("#sensor_demo_sensorNoise", {
		min: 1,
		max: 7,
		step: 0.5,
		value: 2
	});
	sensorDemo = new SensorDemo(id, noiseSlider.getValue());
	noiseSlider.on("slideStop", function (sliderValue)
	{
		sensorDemo.setSensorNoise(sliderValue)
	});
	var repSlider = new Slider('#nSamples', {
		min: 0,
		max: 5,
		step: 0.2,
		value: 2,
		formatter: function (value)
		{
			return round(Math.pow(10, value));
		}
	});
}

function init()
{
	smoothenPath(vanillaPath);
	onFirstAppear('#simple_actuation', function (e, $t)
	{
		initActuationDemo();
	});
	onFirstAppear('#motion_canvas', function (e, $t)
	{
		initMotionDemo();
	});
	onFirstAppear('#mcl_canvas', function (e, $t)
	{
		initMCLDemo();
	});
	onFirstAppear('#sensor_model_demo', function (e, $t)
	{
		initMeasurementDemo();
	});
	onFirstAppear('#sensor_demo', function (e, $t)
	{
		initSensorDemo(e.target.id);
	});
}
<commit_msg>rename for readability<commit_after>/**
 * Created by kelvinzhang on 7/1/17.
 */

window.onerror = function (msg, url, lineNo, columnNo, error)
{
	var string = msg.toLowerCase();
	var substring = "script error";
	if (string.indexOf(substring) > -1)
	{
		alert('Script Error: See Browser Console for Detail');
	} else
	{
		var message = [
			'Message: ' + msg,
			'URL: ' + url,
			'Line: ' + lineNo,
			'Column: ' + columnNo,
			'Error object: ' + JSON.stringify(error)
		].join(' - ');

		alert(message);
	}
	return false;
};

var simpleActuation;
var a1Demo;
var a2Demo;
var a3Demo;
var a4Demo;

var measurementDemo;
var sensorDemo;

var motionDemo;
var a1MDemo;
var a2MDemo;
var a3MDemo;
var a4MDemo;

var mclDemo;

const actuationNoiseSliderFormat = {
	min: 0,
	max: 1,
	step: 0.05,
	value: 0.01,
	formatter: function (value)
	{
		return round(value * 100) + '%';
	}
};

function initMotionDemo()
{
	const path = vanillaPath;
	const x = path[0].x;
	const y = path[0].y;
	const dir = atan2(path[1].y - path[0].y, path[1].x - path[0].x);
	const filter = new ParticleFilter(
		500,
		new OdometryModel(
			getValue('motion_a1') / 100.0,
			getValue('motion_a2') / 100.0,
			getValue('motion_a3') / 100.0,
			getValue('motion_a4') / 100.0),
		undefined,
		new RobotState(x, y, dir),
		0);
	var slider = new Slider("#motion_stride");

	//Individual Simulations
	const s_path = simPath;
	const st_path = straightPath;
	const s_x = s_path[0].x;
	const s_y = s_path[0].y;
	const s_dir = atan2(s_path[1].y - s_path[0].y, s_path[1].x - s_path[0].x);
	const st_x = st_path[0].x;
	const st_y = st_path[0].y;
	const st_dir = atan2(st_path[1].y - st_path[0].y, st_path[1].x - st_path[0].x);
	const exaggerateFilterNoise = 0.3;
	const smallParticleCount = 100;
	const filterA1 = new ParticleFilter(
		smallParticleCount,
		new OdometryModel(
			exaggerateFilterNoise,
			0,
			0,
			0
		),
		undefined,
		new RobotState(s_x, s_y, s_dir),
		0);
	const filterA2 = new ParticleFilter(
		smallParticleCount,
		new OdometryModel(
			0,
			exaggerateFilterNoise,
			0,
			0
		),
		undefined,
		new RobotState(st_x, st_y, st_dir),
		0);
	const filterA3 = new ParticleFilter(
		smallParticleCount,
		new OdometryModel(
			0,
			0,
			exaggerateFilterNoise,
			0
		),
		undefined,
		new RobotState(st_x, st_y, st_dir),
		0);
	const filterA4 = new ParticleFilter(
		smallParticleCount,
		new OdometryModel(
			0,
			0,
			0,
			exaggerateFilterNoise
		),
		undefined,
		new RobotState(s_x, s_y, s_dir),
		0);

	slider.on("slide", function (sliderValue)
	{
		motionDemo.setStride(sliderValue);
		a1MDemo.setStride(sliderValue);
		a2MDemo.setStride(sliderValue);
		a3MDemo.setStride(sliderValue);
		a4MDemo.setStride(sliderValue);
	});

	var a1Slider = new Slider('#motion_a1', actuationNoiseSliderFormat);
	var a2Slider = new Slider('#motion_a2', actuationNoiseSliderFormat);
	var a3Slider = new Slider('#motion_a3', actuationNoiseSliderFormat);
	var a4Slider = new Slider('#motion_a4', actuationNoiseSliderFormat);

	a1Slider.on('slide', function (value)
	{
		motionDemo.setA1(value);
		a1MDemo.setA1(value);
	});
	a2Slider.on('slide', function (value)
	{
		motionDemo.setA2(value);
		a2MDemo.setA2(value);
	});
	a3Slider.on('slide', function (value)
	{
		motionDemo.setA3(value);
		a3MDemo.setA3(value);
	});
	a4Slider.on('slide', function (value)
	{
		motionDemo.setA4(value);
		a4MDemo.setA4(value);
	});

	var robot = new Robot(filter, path, 0, 0, slider.getValue());
	var robotA1 = new Robot(filterA1, s_path, 0, 0, slider.getValue());
	var robotA2 = new Robot(filterA2, st_path, 0, 0, slider.getValue());
	var robotA3 = new Robot(filterA3, st_path, 0, 0, slider.getValue());
	var robotA4 = new Robot(filterA4, s_path, 0, 0, slider.getValue());
	motionDemo = new RobotDemo('motion_canvas', 'motion_minicanvas', getMap(), robot, 10);
	a1MDemo = new RobotDemo('motion_a1_demo', ' ', getSimMap(), robotA1, 10);
	a2MDemo = new RobotDemo('motion_a2_demo', ' ', getSimMap(), robotA2, 10);
	a3MDemo = new RobotDemo('motion_a3_demo', ' ', getSimMap(), robotA3, 10);
	a4MDemo = new RobotDemo('motion_a4_demo', ' ', getSimMap(), robotA4, 10);
}

function initMCLDemo()
{
	var slider = new Slider("#mcl_stride", {
		min: 0.01,
		max: 0.2,
		step: 0.01,
		value: 0.04
	});
	slider.on("slide", function (sliderValue)
	{
		mclDemo.setStride(sliderValue);
	});

	var a1Slider = new Slider('#mcl_a1', actuationNoiseSliderFormat);
	var a2Slider = new Slider('#mcl_a2', actuationNoiseSliderFormat);
	var a3Slider = new Slider('#mcl_a3', actuationNoiseSliderFormat);
	var a4Slider = new Slider('#mcl_a4', actuationNoiseSliderFormat);

	a1Slider.on('slide', function (value)
	{
		mclDemo.setA1(value)
	});
	a2Slider.on('slide', function (value)
	{
		mclDemo.setA2(value)
	});
	a3Slider.on('slide', function (value)
	{
		mclDemo.setA3(value)
	});
	a4Slider.on('slide', function (value)
	{
		mclDemo.setA4(value)
	});

	var sensorRadiusSlider = new Slider('#mcl_sensorRadius', {
		min: 1,
		max: 10,
		step: 0.5
	});
	sensorRadiusSlider.on('slide', function (value)
	{
		mclDemo.setSensorRadius(value);
	});

	var sensorNoiseSlider = new Slider('#mcl_sensorNoise', {
		min: 0,
		max: 3,
		step: 0.1
	});
	sensorNoiseSlider.on('slide', function (value)
	{
		mclDemo.setSensorNoise(value);
	});

	var colorResSlider = new Slider('#mcl_colorRes', {
		min: 1,
		max: 20,
		step: 1
	});
	colorResSlider.on('slide', function (value)
	{
		measurementDemo.setColoringResolution(value);
	});

	var pRatioSlider = new Slider('#mcl_pRatio', {
		min: 0,
		max: 1,
		step: 0.01,
		formatter: function (value)
		{
			return round(value * 100) + "%";
		}
	});
	pRatioSlider.on('slide', function (value)
	{
		mclDemo.robot.filter.resampleRatio = value;
	});

	const path = vanillaPath;
	const x = path[0].x;
	const y = path[0].y;
	const dir = atan2(path[1].y - path[0].y, path[1].x - path[0].x);
	const filter = new ParticleFilter(
		getValue('mcl_nParticles'),
		new OdometryModel(
			a1Slider.getValue(),
			a2Slider.getValue(),
			a3Slider.getValue(),
			a4Slider.getValue()),
		new BeamModel(
			sensorNoiseSlider.getValue(),
			sensorRadiusSlider.getValue(),
			getMap()),
		new RobotState(x, y, dir),
		pRatioSlider.getValue());
	robot = new Robot(filter, path, 19, getValue('mcl_sensorRadius'), getValue('mcl_stride'));
	mclDemo = new RobotDemo('mcl_canvas', 'mcl_minicanvas', getMap(), robot, 10);
}

function simulateAllActuations()
{
	a1Demo.simulateActuation();
	a2Demo.simulateActuation();
	a3Demo.simulateActuation();
	a4Demo.simulateActuation();
}

function initActuationDemo()
{
	//Noise parameters
	const a1 = 0.02;
	const a2 = 0.02;
	const a3 = 0.02;
	const a4 = 0.02;

	const firstMove = 2;
	const turn = Math.PI / 6;
	const secondMove = 2;

	simpleActuation = new ActuationDemo('simple_actuation', firstMove, turn, secondMove,
		a1, a2, a3, a4);
	simpleActuation.simulateActuation();

	var noiseSlider = new Slider('#actuation_noise', actuationNoiseSliderFormat);
	const noise = noiseSlider.getValue();
	a1Demo = new ActuationDemo('actuation_a1', firstMove, turn, secondMove,
		noise, 0, 0, 0);
	a2Demo = new ActuationDemo('actuation_a2', firstMove, turn, secondMove,
		0, noise, 0, 0);
	a3Demo = new ActuationDemo('actuation_a3', firstMove, turn, secondMove,
		0, 0, noise, 0);
	a4Demo = new ActuationDemo('actuation_a4', firstMove, turn, secondMove,
		0, 0, 0, noise);
	noiseSlider.on('slide', function (sliderValue)
	{
		a1Demo.setA1(sliderValue);
		a2Demo.setA2(sliderValue);
		a3Demo.setA3(sliderValue);
		a4Demo.setA4(sliderValue);
	});
	noiseSlider.on('slideStop', simulateAllActuations);
	simulateAllActuations();
}

function initMeasurementDemo()
{
	var map = getMap();
	compactMap(map);
	var nLasersSlider = new Slider('#nLasers', {
		min: 6,
		max: 36,
		step: 1
	});
	nLasersSlider.on('slide', function (value)
	{
		measurementDemo.setNLasers(value)
	});
	nLasersSlider.on('slideStop', function ()
	{
		measurementDemo.colorMapIfShould();
	});

	var sensorRadiusSlider = new Slider('#sensorRadius', {
		min: 1,
		max: 10,
		step: 0.5
	});
	sensorRadiusSlider.on('slide', function (value)
	{
		measurementDemo.setSensorRadius(value);
	});
	sensorRadiusSlider.on('slideStop', function ()
	{
		measurementDemo.colorMapIfShould();
	});

	var sensorNoiseSlider = new Slider('#sensorNoise', {
		min: 0,
		max: 3,
		step: 0.1
	});
	sensorNoiseSlider.on('slide', function (value)
	{
		measurementDemo.setSensorNoise(value);
	});
	sensorNoiseSlider.on('slideStop', function ()
	{
		measurementDemo.colorMapIfShould();
	});

	var colorResSlider = new Slider('#colorRes', {
		min: 1,
		max: 20,
		step: 1
	});
	colorResSlider.on('slide', function (value)
	{
		measurementDemo.setColoringResolution(value);
	});
	colorResSlider.on('slideStop', function ()
	{
		measurementDemo.colorMapIfShould();
	});

	measurementDemo = new BeamModelDemo('sensor_model_demo', map,
		sensorRadiusSlider.getValue(), sensorNoiseSlider.getValue());
}

function onFirstAppear(selector, callback)
{
	$(selector).appear().on('appear', function (event, $targets)
	{
		callback(event, $targets);
		$(selector).off('appear');
	});
}

function initSensorDemo(id)
{
	var noiseSlider = new Slider("#sensor_demo_sensorNoise", {
		min: 1,
		max: 7,
		step: 0.5,
		value: 2
	});
	sensorDemo = new SensorDemo(id, noiseSlider.getValue());
	noiseSlider.on("slideStop", function (sliderValue)
	{
		sensorDemo.setSensorNoise(sliderValue)
	});
	var repSlider = new Slider('#nSamples', {
		min: 0,
		max: 5,
		step: 0.2,
		value: 2,
		formatter: function (value)
		{
			return round(Math.pow(10, value));
		}
	});
}

function init()
{
	smoothenPath(vanillaPath);
	onFirstAppear('#simple_actuation', function (e, $t)
	{
		initActuationDemo();
	});
	onFirstAppear('#motion_canvas', function (e, $t)
	{
		initMotionDemo();
	});
	onFirstAppear('#mcl_canvas', function (e, $t)
	{
		initMCLDemo();
	});
	onFirstAppear('#sensor_model_demo', function (e, $t)
	{
		initMeasurementDemo();
	});
	onFirstAppear('#sensor_demo', function (e, $t)
	{
		initSensorDemo(e.target.id);
	});
}
<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */

var Builder = require('component-builder');
var json = require('./json');
var jade = require('./jade');
var fs = require('fs');
var write = fs.writeFileSync;
var log = require('debug')('democracyos:build');

/**
 * Expose component
 * builder getter
 */

module.exports.createBuilder = createBuilder;

/**
 * Expose component
 * build middleware.
 */

module.exports.middleware = middleware;

/**
 * Creates a `Builder` instance
 * ready for build
 */

function createBuilder () {
  var builder = new Builder('.');
  builder.copyFiles();
  builder.addLookup('lib'); // TODO: shouldn't be necessary
  builder.copyAssetsTo('public');
  builder.use(jade);

  return builder;
}

/**
 * Express build middleware
 */

function middleware (req, res, next) {
  // Build on application request paths only
  if (!~['/app.js', '/app.css'].indexOf(req.path)) {
    return next();
  };

  log('Attempting to build for %s request path.', req.path);

  var builder = createBuilder();
  builder.build(function(err, res){
    if (err) return next(err);
    log('Writing recent build for %s request path.', req.path);

    write('public/app.js', res.require + res.js);
    write('public/app.css', res.css);

    log('Leaving middleware after write for path %s', req.path);
    next();
  });
};
<commit_msg>[build] - Improve logging<commit_after>/**
 * Module dependencies.
 */

var Builder = require('component-builder');
var json = require('./json');
var jade = require('./jade');
var fs = require('fs');
var write = fs.writeFileSync;
var log = require('debug')('democracyos:build');

/**
 * Expose component
 * builder getter
 */

module.exports.createBuilder = createBuilder;

/**
 * Expose component
 * build middleware.
 */

module.exports.middleware = middleware;

/**
 * Creates a `Builder` instance
 * ready for build
 */

function createBuilder () {
  var builder = new Builder('.');
  builder.copyFiles();
  builder.addLookup('lib'); // TODO: shouldn't be necessary
  builder.copyAssetsTo('public');
  builder.use(jade);

  return builder;
}

/**
 * Express build middleware
 */

function middleware (req, res, next) {
  // Build only script and stylesheet
  if (!~['/app.js', '/app.css'].indexOf(req.path)) {
    return next();
  };

  log('Build %s.', req.path);

  var builder = createBuilder();
  builder.build(function(err, res){
    if (err) return next(err);

    log('Write script and stylesheet');
    write('public/app.js', res.require + res.js);
    write('public/app.css', res.css);
    next();
  });
};
<|endoftext|>


<commit_before>var events = require('events');
var util = require('util');

function CdifDevice(spec) {
  this.spec = spec;
  this.connected = false;
  this.actions = {};
  var services = spec.device.serviceList;
  for (var i in services) {
    var service = services[i];
    this.actions[i] = {};
    var actions = service.actionList;
    for (var j in actions) {
      this.actions[i][j] = {};
    }
  }
  this.getDeviceSpec = this.getDeviceSpec.bind(this);
  this.connect = this.connect.bind(this);
  this.disconnect = this.disconnect.bind(this);
  this.getHWAddress = this.getHWAddress.bind(this);
  this.deviceControl = this.deviceControl.bind(this);
  this.subscribeDeviceEvent = this.subscribeDeviceEvent.bind(this);
  this.unSubscribeDeviceEvent = this.unSubscribeDeviceEvent.bind(this);
}

util.inherits(CdifDevice, events.EventEmitter);

CdifDevice.prototype.getDeviceSpec = function(callback) {
  if (this.spec == null) {
    callback(new Error('cannot get device spec'), null);
  } else {
    callback(null, JSON.stringify(this.spec));
  }
}

CdifDevice.prototype.connect = function(user, pass, callback) {
  var _this = this;
  if (this._connect) {
    this._connect(user, pass, function(error) {
      if (!error) {
        _this.connected = true;
      }
      callback(error);
    });
  }
}

CdifDevice.prototype.disconnect = function(callback) {
  var _this = this;
  if (this._disconnect) {
    this._disconnect(function(error) {
      if (!error) {
        _this.connected = false;
      }
      callback(error);
    });
  }
}

CdifDevice.prototype.getHWAddress = function(callback) {
  if (this._getHWAddress) {
    this._getHWAddress(function(error, data) {
      callback(error, data);
    });
  }
}

CdifDevice.prototype.deviceControl = function(serviceId, actionName, args, callback) {
  var action = this.actions[serviceId][actionName];
  if (action == null) {
    callback(new Error('action not found: ' + actionName), null);
  } else {
    if (this.connected == false) {
      callback(new Error('device not connected'), null);
      return;
    }
    action(args, function(err, data) {
      callback(err, data);
    });
  }
}

var eventCallback = function(data) {
  console.log(data);
}

CdifDevice.prototype.subscribeDeviceEvent = function(serviceId, callback) {
  if (this.spec.device.serviceList[serviceId] == null) {
    callback(new Error('cannot subscribe to unknown serviceId: ' + serviceId));
    return;
  }
  if (this.subscribeEvent) {
    if (this.listeners(serviceId).length === 0) {
      this.addListener(serviceId, eventCallback);
    }
    this.subscribeEvent(serviceId, function(err) {
      callback(err);
    });
  }
}

CdifDevice.prototype.unSubscribeDeviceEvent = function(serviceId, callback) {
  var _this = this;
  if (this.spec.device.serviceList[serviceId] == null) {
    callback(new Error('cannot unsubscribe from unknown serviceId: ' + serviceId));
    return;
  }
  if (this.unsubscribeEvent) {
    this.unsubscribeEvent(serviceId, function(err) {
      if (!err) {
        if (_this.listeners(serviceId).length === 1) {
          _this.removeListener(serviceId, eventCallback);
        }
      }
      callback(err);
    });
  }
}

module.exports = CdifDevice;
<commit_msg>invoke callback anyway if a module doesn't implement event subscription interface<commit_after>var events = require('events');
var util = require('util');

function CdifDevice(spec) {
  this.spec = spec;
  this.connected = false;
  this.actions = {};
  var services = spec.device.serviceList;
  for (var i in services) {
    var service = services[i];
    this.actions[i] = {};
    var actions = service.actionList;
    for (var j in actions) {
      this.actions[i][j] = {};
    }
  }
  this.getDeviceSpec = this.getDeviceSpec.bind(this);
  this.connect = this.connect.bind(this);
  this.disconnect = this.disconnect.bind(this);
  this.getHWAddress = this.getHWAddress.bind(this);
  this.deviceControl = this.deviceControl.bind(this);
  this.subscribeDeviceEvent = this.subscribeDeviceEvent.bind(this);
  this.unSubscribeDeviceEvent = this.unSubscribeDeviceEvent.bind(this);
}

util.inherits(CdifDevice, events.EventEmitter);

CdifDevice.prototype.getDeviceSpec = function(callback) {
  if (this.spec == null) {
    callback(new Error('cannot get device spec'), null);
  } else {
    callback(null, JSON.stringify(this.spec));
  }
}

CdifDevice.prototype.connect = function(user, pass, callback) {
  var _this = this;
  if (this._connect) {
    this._connect(user, pass, function(error) {
      if (!error) {
        _this.connected = true;
      }
      callback(error);
    });
  }
}

CdifDevice.prototype.disconnect = function(callback) {
  var _this = this;
  if (this._disconnect) {
    this._disconnect(function(error) {
      if (!error) {
        _this.connected = false;
      }
      callback(error);
    });
  }
}

CdifDevice.prototype.getHWAddress = function(callback) {
  if (this._getHWAddress) {
    this._getHWAddress(function(error, data) {
      callback(error, data);
    });
  }
}

CdifDevice.prototype.deviceControl = function(serviceId, actionName, args, callback) {
  var action = this.actions[serviceId][actionName];
  if (action == null) {
    callback(new Error('action not found: ' + actionName), null);
  } else {
    if (this.connected == false) {
      callback(new Error('device not connected'), null);
      return;
    }
    action(args, function(err, data) {
      callback(err, data);
    });
  }
}

var eventCallback = function(data) {
  console.log(data);
}

CdifDevice.prototype.subscribeDeviceEvent = function(serviceId, callback) {
  if (this.spec.device.serviceList[serviceId] == null) {
    callback(new Error('cannot subscribe to unknown serviceId: ' + serviceId));
    return;
  }
  if (this.subscribeEvent) {
    if (this.listeners(serviceId).length === 0) {
      this.addListener(serviceId, eventCallback);
    }
    this.subscribeEvent(serviceId, function(err) {
      callback(err);
    });
  } else {
    callback(null);
  }
}

CdifDevice.prototype.unSubscribeDeviceEvent = function(serviceId, callback) {
  var _this = this;
  if (this.spec.device.serviceList[serviceId] == null) {
    callback(new Error('cannot unsubscribe from unknown serviceId: ' + serviceId));
    return;
  }
  if (this.unsubscribeEvent) {
    this.unsubscribeEvent(serviceId, function(err) {
      if (!err) {
        if (_this.listeners(serviceId).length === 1) {
          _this.removeListener(serviceId, eventCallback);
        }
      }
      callback(err);
    });
  } else {
    callback(null);
  }
}

module.exports = CdifDevice;
<|endoftext|>