<commit_before>
// require dependencies
const eden         = require ('eden');
const http         = require ('http');
const multer       = require ('multer');
const express      = require ('express');
const session      = require ('express-session');
const bodyParser   = require ('body-parser');
const redisStore   = require ('connect-redis') (session);
const responseTime = require ('response-time');
const cookieParser = require ('cookie-parser');

// require local dependencies
const acl    = require ('lib/utilities/acl');
const config = require ('app/config');

// require cache
const routes  = cache ('routes');
const classes = cache ('classes');

// require eden dependencies
const view = require ('./view');

/**
 * builds eden router
 */
class router {
  /**
   * constructs router
   */
  constructor () {
    // set private variables
    this._multer  = false;
    this._server  = false;
    this._express = false;

    // bind methods
    this.build = this.build.bind (this);

    // bind private methods
    this._api     = this._api.bind (this);
    this._ajax    = this._ajax.bind (this);
    this._view    = this._view.bind (this);
    this._error   = this._error.bind (this);
    this._default = this._default.bind (this);

    // bind super private methods
    this.__error  = this.__error.bind (this);
    this.__rotue  = this.__route.bind (this);
    this.__upload = this.__upload.bind (this);
    this.__listen = this.__listen.bind (this);

    // build
    this.build ();
  }

  /**
   * build eden express
   */
  async build () {
    // log building app
    eden.logger.log ('debug', 'building', {
      'class' : 'express'
    });

    // create express
    this._express = express ();

    // set port
    this._express.set ('port', eden.port);

    // create server
    this._server = http.createServer (this._express);

    // listen to port
    this._server.listen (eden.port);

    // listen to server events
    this._server.on ('error',     this.__error);
    this._server.on ('listening', this.__listen);

    // set uploader
    this._multer = multer (config.upload || {
      'dest' : '/tmp'
    });

    // set use
    ['use', 'get', 'post', 'push', 'delete', 'all'].forEach ((method) => {
      // create mixin method
      this[method] = function () {
        // call express method
        this._express[method].apply (this._express, arguments);
      }
    });

    // run express build methods
    let methods = ['_default', '_api', '_ajax', '_view', '_router', '_error'];

    // do method loop
    for (let i = 0; i < methods.length; i++) {
      // await method
      await this[methods[i]] (this._express);
    }

    // log built express
    eden.logger.log ('debug', 'building completed', {
      'class' : 'express'
    });
  }

  /**
   * adds default uses
   *
   * @param {Express} app
   * @private
   */
  async _default (app) {
    // set default locals
    app.use ((req, res, next) => {
      // set headers
      res.header ('X-Powered-By', 'EdenFrame');

      // set variables
      res.locals.url = req.originalUrl.replace ('/ajx', '');

      // set route start
      res.locals.timer = {
        'start' : new Date ().getTime ()
      };

      // set locals
      res.locals.page = {};
      res.locals.res  = res;

      // go to next
      next ();
    });

    // use functionality
    app.use (responseTime ());
    app.use (bodyParser.json ());
    app.use (bodyParser.urlencoded ({
      'extended' : true
    }));
    app.use (cookieParser (config.secret));
    app.use (express.static ('www'));
    app.use (session ({
      'key'               : config.session.key || 'eden.session.id',
      'store'             : new redisStore (config.redis || {}),
      'secret'            : config.secret,
      'resave'            : false,
      'cookie'            : config.session.cookie || {
        'secure'   : false,
        'httpOnly' : false
      },
      'saveUninitialized' : true
    }));

    // do hook
    await eden.hook ('eden.app', app);
  }

  /**
   * api functionality
   *
   * @param {Express} app
   * @private
   */
  _api (app) {
    // add app headers
    app.all ('/api/*', (req, res, next) => {
      // set headers
      res.header ('Access-Control-Allow-Origin',  '*');
      res.header ('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');

      // go to next
      next ();
    });
  }

  /**
   * ajax middleware
   *
   * @param {Express} app
   * @private
   */
  _ajax (app) {
    // add ajax headers
    app.all ('/ajx/*', (req, res, next) => {
      // set response to json
      req.isJSON        = true;
      res.locals.isJSON = true;

      // set header
      res.setHeader ('Content-Type', 'application/json');

      // set res.redirect
      res.redirect = (url) => {
        // render json
        res.json ({
          'redirect' : url
        });
      };

      // go to next
      next ();
    });
  }

  /**
   * view engine
   *
   * @param {Express} app
   * @private
   */
  _view (app) {
    // build view engine
    app.set ('views', global.appRoot + '/app/cache/views');
    app.set ('view engine', 'tag');

    // do view engine
    app.engine ('tag', new view ().render);
  }

  /**
   * build router
   *
   * @param {Express} app
   * @private
   */
  async _router (app) {
    // create express router
    this._router = express.Router ();

    // set router classes
    let routerClasses = Object.keys (classes).map (key => classes[key]);

    // hook routes
    await eden.hook ('eden:classes', routerClasses);

    // sort classes
    routerClasses.sort ((a, b) => {
      // return sort
      return (b.priority || 0) - (a.priority || 0);
    });

    // require classes
    for (let a = 0; a < routerClasses.length; a++) {
      // load controller
      await eden.controller (routerClasses[a].file);
    }

    // hook routes
    await eden.hook ('eden:routes', routes);

    // sort routes
    routes.sort ((a, b) => {
      // return sort
      return (b.priority || 0) - (a.priority || 0);
    });

    // routes forEach
    for (let i = 0; i < routes.length; i++) {
      // run route
      await this.__route (routes[i]);
    }

    // set routes to app
    app.use ('/',    this._router);
    app.use ('/ajx', this._router);
  }

  /**
   * use error handler
   *
   * @param {Express} app
   * @private
   */
  _error (app) {
    // use 404 handler
    app.use ((req, res) => {
      // set status 404
      res.status (404);

      // render 404 page
      res.render ('error', {
        'message' : '404 page not found'
      });
    });
  }

  /**
   * creates route
   *
   * @param {Object} route
   *
   * @private
   */
  async __route (route) {
    // set variables
    let path = (route.mount + route.route).replace ('//', '/');
        path = path.length > 1 ? path.replace (/\/$/, '') : path;

    // create route arguements
    let args = [path];

    // push timer arg
    args.push ((req, res, next) => {
      // set route start time
      res.locals.timer.route = new Date ().getTime ();

      // run next
      next ();
    });

    // check upload
    let upload = this.__upload (route);

    // push upload to args
    if (upload) args.push (upload);

    // add actual route
    args.push (async (req, res, next) => {
      // set route
      res.locals.path = path;

      // set route
      res.locals.route = route;

      // set title
      if (route.title) res.locals.page.title = route.title;

      // run acl middleware
      let aclCheck = await acl.middleware (req, res);

      // check acl result
      if (aclCheck === 0) {
        // nexted
        return next ();
      } else if (aclCheck === 2) {
        // redirected
        return;
      }

      // try catch
      try {
        // get controller
        let controller = await eden.controller (route.class);

        // try run function
        return controller[route.fn] (req, res, next);
      } catch (e) {
        // set error
        eden.error (e);

        // run next
        return next ();
      }
    });

    // call router function
    this._router[route.type].apply (this._router, args);
  }

  /**
   * upload method check
   *
   * @param {Object} route
   *
   * @private
   */
  __upload (route) {
    // add upload middleware
    if (route.type !== 'post') return false;

    // set type
    let upType = route.upload && route.upload.type || 'array';

    // set middle
    let upApply = [];

    // check type
    if (route.upload && route.upload.fields) {
      if (upType === 'array') {
        // push to middle
        upApply.push (route.upload.fields.name);
      } else if (upType === 'single') {
        // push single name
        upApply.push (route.upload.fields[0].name);
      } else if (upType === 'fields') {
        // fields
        upApply = fields;
      }
    }

    // check if any
    if (upType === 'any') upApply = [];

    // create upload middleware
    return this._multer[upType].apply (this._multer, upApply);
  }

  /**
   * on error function
   *
   * @param error
   */
  __error (error) {
    // throw error
    if (error.syscall !== 'listen') {
      // throw error
      eden.error (error);
    }

    // bind check
    let bind = typeof this.port === 'string' ? 'Pipe ' + this.port : 'Port ' + this.port;

    // handle specific listen errors with friendly messages
    if (error.code === 'EACCES') {
      // log error
      eden.logger.log ('error', bind + ' requires elevated privileges', {
        'class' : 'eden'
      });

      // exit
      process.exit (1);
    } else if (error.code === 'EADDRINUSE') {
      // log error
      eden.logger.log ('error', bind + ' is already in use', {
        'class' : 'eden'
      });

      // exit
      process.exit (1);
    } else {
      // throw error
      eden.error (error);
    }
  }

  /**
   * on listen function
   */
  __listen () {
    // get server address
    let addr = this._server.address ();

    // check if string
    let bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port;
  }
}

/**
 * export router class
 *
 * @type {router}
 */
exports = module.exports = router;
<commit_msg>Add 'proxy' option to router to allow secure cookies through reverse proxy.<commit_after>
// require dependencies
const eden         = require ('eden');
const http         = require ('http');
const multer       = require ('multer');
const express      = require ('express');
const session      = require ('express-session');
const bodyParser   = require ('body-parser');
const redisStore   = require ('connect-redis') (session);
const responseTime = require ('response-time');
const cookieParser = require ('cookie-parser');

// require local dependencies
const acl    = require ('lib/utilities/acl');
const config = require ('app/config');

// require cache
const routes  = cache ('routes');
const classes = cache ('classes');

// require eden dependencies
const view = require ('./view');

/**
 * builds eden router
 */
class router {
  /**
   * constructs router
   */
  constructor () {
    // set private variables
    this._multer  = false;
    this._server  = false;
    this._express = false;

    // bind methods
    this.build = this.build.bind (this);

    // bind private methods
    this._api     = this._api.bind (this);
    this._ajax    = this._ajax.bind (this);
    this._view    = this._view.bind (this);
    this._error   = this._error.bind (this);
    this._default = this._default.bind (this);

    // bind super private methods
    this.__error  = this.__error.bind (this);
    this.__rotue  = this.__route.bind (this);
    this.__upload = this.__upload.bind (this);
    this.__listen = this.__listen.bind (this);

    // build
    this.build ();
  }

  /**
   * build eden express
   */
  async build () {
    // log building app
    eden.logger.log ('debug', 'building', {
      'class' : 'express'
    });

    // create express
    this._express = express ();

    // set port
    this._express.set ('port', eden.port);

    // create server
    this._server = http.createServer (this._express);

    // listen to port
    this._server.listen (eden.port);

    // listen to server events
    this._server.on ('error',     this.__error);
    this._server.on ('listening', this.__listen);

    // set uploader
    this._multer = multer (config.upload || {
      'dest' : '/tmp'
    });

    // set use
    ['use', 'get', 'post', 'push', 'delete', 'all'].forEach ((method) => {
      // create mixin method
      this[method] = function () {
        // call express method
        this._express[method].apply (this._express, arguments);
      }
    });

    // run express build methods
    let methods = ['_default', '_api', '_ajax', '_view', '_router', '_error'];

    // do method loop
    for (let i = 0; i < methods.length; i++) {
      // await method
      await this[methods[i]] (this._express);
    }

    // log built express
    eden.logger.log ('debug', 'building completed', {
      'class' : 'express'
    });
  }

  /**
   * adds default uses
   *
   * @param {Express} app
   * @private
   */
  async _default (app) {
    // set default locals
    app.use ((req, res, next) => {
      // set headers
      res.header ('X-Powered-By', 'EdenFrame');

      // set variables
      res.locals.url = req.originalUrl.replace ('/ajx', '');

      // set route start
      res.locals.timer = {
        'start' : new Date ().getTime ()
      };

      // set locals
      res.locals.page = {};
      res.locals.res  = res;

      // go to next
      next ();
    });

    // use functionality
    app.use (responseTime ());
    app.use (bodyParser.json ());
    app.use (bodyParser.urlencoded ({
      'extended' : true
    }));
    app.use (cookieParser (config.secret));
    app.use (express.static ('www'));
    app.use (session ({
      'key'               : config.session.key || 'eden.session.id',
      'store'             : new redisStore (config.redis || {}),
      'secret'            : config.secret,
      'resave'            : false,
      'cookie'            : config.session.cookie || {
        'secure'   : false,
        'httpOnly' : false
      },
      'proxy'             : true,
      'saveUninitialized' : true
    }));

    // do hook
    await eden.hook ('eden.app', app);
  }

  /**
   * api functionality
   *
   * @param {Express} app
   * @private
   */
  _api (app) {
    // add app headers
    app.all ('/api/*', (req, res, next) => {
      // set headers
      res.header ('Access-Control-Allow-Origin',  '*');
      res.header ('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');

      // go to next
      next ();
    });
  }

  /**
   * ajax middleware
   *
   * @param {Express} app
   * @private
   */
  _ajax (app) {
    // add ajax headers
    app.all ('/ajx/*', (req, res, next) => {
      // set response to json
      req.isJSON        = true;
      res.locals.isJSON = true;

      // set header
      res.setHeader ('Content-Type', 'application/json');

      // set res.redirect
      res.redirect = (url) => {
        // render json
        res.json ({
          'redirect' : url
        });
      };

      // go to next
      next ();
    });
  }

  /**
   * view engine
   *
   * @param {Express} app
   * @private
   */
  _view (app) {
    // build view engine
    app.set ('views', global.appRoot + '/app/cache/views');
    app.set ('view engine', 'tag');

    // do view engine
    app.engine ('tag', new view ().render);
  }

  /**
   * build router
   *
   * @param {Express} app
   * @private
   */
  async _router (app) {
    // create express router
    this._router = express.Router ();

    // set router classes
    let routerClasses = Object.keys (classes).map (key => classes[key]);

    // hook routes
    await eden.hook ('eden:classes', routerClasses);

    // sort classes
    routerClasses.sort ((a, b) => {
      // return sort
      return (b.priority || 0) - (a.priority || 0);
    });

    // require classes
    for (let a = 0; a < routerClasses.length; a++) {
      // load controller
      await eden.controller (routerClasses[a].file);
    }

    // hook routes
    await eden.hook ('eden:routes', routes);

    // sort routes
    routes.sort ((a, b) => {
      // return sort
      return (b.priority || 0) - (a.priority || 0);
    });

    // routes forEach
    for (let i = 0; i < routes.length; i++) {
      // run route
      await this.__route (routes[i]);
    }

    // set routes to app
    app.use ('/',    this._router);
    app.use ('/ajx', this._router);
  }

  /**
   * use error handler
   *
   * @param {Express} app
   * @private
   */
  _error (app) {
    // use 404 handler
    app.use ((req, res) => {
      // set status 404
      res.status (404);

      // render 404 page
      res.render ('error', {
        'message' : '404 page not found'
      });
    });
  }

  /**
   * creates route
   *
   * @param {Object} route
   *
   * @private
   */
  async __route (route) {
    // set variables
    let path = (route.mount + route.route).replace ('//', '/');
        path = path.length > 1 ? path.replace (/\/$/, '') : path;

    // create route arguements
    let args = [path];

    // push timer arg
    args.push ((req, res, next) => {
      // set route start time
      res.locals.timer.route = new Date ().getTime ();

      // run next
      next ();
    });

    // check upload
    let upload = this.__upload (route);

    // push upload to args
    if (upload) args.push (upload);

    // add actual route
    args.push (async (req, res, next) => {
      // set route
      res.locals.path = path;

      // set route
      res.locals.route = route;

      // set title
      if (route.title) res.locals.page.title = route.title;

      // run acl middleware
      let aclCheck = await acl.middleware (req, res);

      // check acl result
      if (aclCheck === 0) {
        // nexted
        return next ();
      } else if (aclCheck === 2) {
        // redirected
        return;
      }

      // try catch
      try {
        // get controller
        let controller = await eden.controller (route.class);

        // try run function
        return controller[route.fn] (req, res, next);
      } catch (e) {
        // set error
        eden.error (e);

        // run next
        return next ();
      }
    });

    // call router function
    this._router[route.type].apply (this._router, args);
  }

  /**
   * upload method check
   *
   * @param {Object} route
   *
   * @private
   */
  __upload (route) {
    // add upload middleware
    if (route.type !== 'post') return false;

    // set type
    let upType = route.upload && route.upload.type || 'array';

    // set middle
    let upApply = [];

    // check type
    if (route.upload && route.upload.fields) {
      if (upType === 'array') {
        // push to middle
        upApply.push (route.upload.fields.name);
      } else if (upType === 'single') {
        // push single name
        upApply.push (route.upload.fields[0].name);
      } else if (upType === 'fields') {
        // fields
        upApply = fields;
      }
    }

    // check if any
    if (upType === 'any') upApply = [];

    // create upload middleware
    return this._multer[upType].apply (this._multer, upApply);
  }

  /**
   * on error function
   *
   * @param error
   */
  __error (error) {
    // throw error
    if (error.syscall !== 'listen') {
      // throw error
      eden.error (error);
    }

    // bind check
    let bind = typeof this.port === 'string' ? 'Pipe ' + this.port : 'Port ' + this.port;

    // handle specific listen errors with friendly messages
    if (error.code === 'EACCES') {
      // log error
      eden.logger.log ('error', bind + ' requires elevated privileges', {
        'class' : 'eden'
      });

      // exit
      process.exit (1);
    } else if (error.code === 'EADDRINUSE') {
      // log error
      eden.logger.log ('error', bind + ' is already in use', {
        'class' : 'eden'
      });

      // exit
      process.exit (1);
    } else {
      // throw error
      eden.error (error);
    }
  }

  /**
   * on listen function
   */
  __listen () {
    // get server address
    let addr = this._server.address ();

    // check if string
    let bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port;
  }
}

/**
 * export router class
 *
 * @type {router}
 */
exports = module.exports = router;
<|endoftext|>


<commit_before>var fs = require('fs');
var spawn = require('child_process').spawn;
var util = require('util');
var path = require('path');
var EventEmitter = require('events').EventEmitter;
var MessageHandler = require('./lib/message-handler').MessageHandler;

// TODO: Make these configurable
var NACL_SDK_ROOT = process.env.NACL_SDK_ROOT || path.resolve(__dirname, 'deps/nacl/nacl_sdk/pepper_35');
var RUN_CONTRACT_COMMAND = path.resolve(NACL_SDK_ROOT, 'tools/sel_ldr_x86_32');
var RUN_CONTRACT_LIBS = [
	path.resolve(__dirname, 'deps/nacl/v8/out/nacl_ia32.release/lib.target'),
	path.resolve(NACL_SDK_ROOT, 'toolchain/linux_x86_glibc/x86_64-nacl/lib32'),
];
var RUN_CONTRACT_ARGS = [
  '-h',
  '3:3',
  '-h',
  '4:4',
  '-a',
  '--',
  path.resolve(NACL_SDK_ROOT, 'toolchain/linux_x86_glibc/x86_64-nacl/lib32/runnable-ld.so'),
  '--library-path',
  RUN_CONTRACT_LIBS.join(':'),
  path.resolve(__dirname, 'deps/nacl/codius_node.nexe')
];

var RUN_CONTRACT_DISABLE_NACL_COMMAND = path.resolve(__dirname, 'deps/seccomp/codius_node');
var RUN_CONTRACT_DISABLE_NACL_ARGS = [ ];

/**
 * Sandbox class wrapper around Native Client
 */
function Sandbox(opts) {
	var self = this;

	if (!opts) {
		opts = {};
	}

	self._api = opts.api;
	self._timeout = opts.timeout || 1000;
	self._enableGdb = opts.enableGdb || false;
	self._enableValgrind = opts.enableValgrind || false;
	self._disableNacl = opts.disableNacl || false;
	self._stdout_dest = (opts.passthroughStdio ? process.stdout : null);
	self._stderr_dest = (opts.passthroughStdio ? process.stderr : null);

	// Set when Sandbox.run is called
	self._stdio = null;
	self._message_handler = new MessageHandler({
		api: self._api
	});;
	self._native_client_child = null;

}

/**
 *	Set the API
 */
Sandbox.prototype.setApi = function(api) {
	var self = this;
	self._message_handler.setApi(api);
};

/**
 * Run the given file inside the sandbox
 *
 * @param {String} file_path
 */
Sandbox.prototype.run = function(file_path, opts, callback) {
	var self = this;

	if (typeof opts === 'function') {
		callback = opts;
		opts = {};
	}

	// Create new sandbox
	self._native_client_child = self._spawnChildToRunCode(file_path, opts.env);
	self._native_client_child.on('exit', function(code){
		if (typeof callback === 'function') {
			callback();
		}
	});
	self._stdio = self._native_client_child.stdio;

	if (self._stdout_dest) {
		self._stdio[1].pipe(self._stdout_dest);
	}

	if (self._stderr_dest) {
		self._stdio[2].pipe(self._stderr_dest);
	}

	self._message_handler.setupStdio(self._stdio);

};

Sandbox.prototype._spawnChildToRunCode = function (file_path, env) {
	var self = this;

	if (self._disableNacl) {
		console.warn('NaCl is disabled');
	}

	var cmd = (self._disableNacl ? RUN_CONTRACT_DISABLE_NACL_COMMAND : RUN_CONTRACT_COMMAND);
	var args = (self._disableNacl ? RUN_CONTRACT_DISABLE_NACL_ARGS.slice() : RUN_CONTRACT_ARGS.slice());
	args.push(file_path);

	if (self._enableGdb) {
		args.unshift(cmd);
		args.unshift('localhost:4484');
		cmd = 'gdbserver';
	} else if (self._enableValgrind) {
		args.unshift('--');
		args.unshift(cmd);
		cmd = 'valgrind';
	}

	var child = spawn(cmd, args, {
		env: env,
		stdio: [ 'pipe', 'pipe', 'pipe', 'pipe',  'pipe' ]
	});

  child.on('error', self._handleChildProcessError.bind(self));

  return child;
};

/**
 * Handle child process errors and try to give a little bit better error information.
 */
Sandbox.prototype._handleChildProcessError = function (err) {
  // TODO Should this handle the error? Pass it on as an event?
  if (err.code === 'ENOENT') {
    // TODO Error information could be further improved, check whether libc is there etc.
    console.log('ENOENT: The child process was unable to spawn.');
    if (process.arch === 'x64') {
      console.error('Note that on x64 architectures you need to install the 32-bit versions of libc and libstdc++.');
    }
  } else {
    throw err;
  }
};

/**
 * Kill the sandbox process.
 *
 * @param {String} ['SIGKILL'] message
 */
Sandbox.prototype.kill = function(message){
	var self = this;

	if (self._native_client_child) {
		self._native_client_child.kill(message);
	}
};

/**
 * Pipe Native Client stdout and stderr to
 * the parent process' stdout and stderr
 */
Sandbox.prototype.passthroughStdio = function() {
	var self = this;

	self._stdout_dest = process.stdout;
	self._stderr_dest = process.stderr;
};

/**
 * Set up the sandbox's `stdout` stream to be piped to
 * the given destination when the child process is spawned
 */
Sandbox.prototype.pipeStdout = function(dest) {
	var self = this;

	self._stdout_dest = dest;
};

/**
 * Set up the sandbox's `stderr` stream to be piped to
 * the given destination when the child process is spawned
 */
Sandbox.prototype.pipeStderr = function(dest) {
	var self = this;

	self._stderr_dest = dest;
};

module.exports = Sandbox;
<commit_msg>[FEATURE] Make options object optional.<commit_after>var fs = require('fs');
var spawn = require('child_process').spawn;
var util = require('util');
var path = require('path');
var EventEmitter = require('events').EventEmitter;
var MessageHandler = require('./lib/message-handler').MessageHandler;

// TODO: Make these configurable
var NACL_SDK_ROOT = process.env.NACL_SDK_ROOT || path.resolve(__dirname, 'deps/nacl/nacl_sdk/pepper_35');
var RUN_CONTRACT_COMMAND = path.resolve(NACL_SDK_ROOT, 'tools/sel_ldr_x86_32');
var RUN_CONTRACT_LIBS = [
	path.resolve(__dirname, 'deps/nacl/v8/out/nacl_ia32.release/lib.target'),
	path.resolve(NACL_SDK_ROOT, 'toolchain/linux_x86_glibc/x86_64-nacl/lib32'),
];
var RUN_CONTRACT_ARGS = [
  '-h',
  '3:3',
  '-h',
  '4:4',
  '-a',
  '--',
  path.resolve(NACL_SDK_ROOT, 'toolchain/linux_x86_glibc/x86_64-nacl/lib32/runnable-ld.so'),
  '--library-path',
  RUN_CONTRACT_LIBS.join(':'),
  path.resolve(__dirname, 'deps/nacl/codius_node.nexe')
];

var RUN_CONTRACT_DISABLE_NACL_COMMAND = path.resolve(__dirname, 'deps/seccomp/codius_node');
var RUN_CONTRACT_DISABLE_NACL_ARGS = [ ];

/**
 * Sandbox class wrapper around Native Client
 */
function Sandbox(opts) {
	var self = this;

	if (!opts) {
		opts = {};
	}

	self._api = opts.api;
	self._timeout = opts.timeout || 1000;
	self._enableGdb = opts.enableGdb || false;
	self._enableValgrind = opts.enableValgrind || false;
	self._disableNacl = opts.disableNacl || false;
	self._stdout_dest = (opts.passthroughStdio ? process.stdout : null);
	self._stderr_dest = (opts.passthroughStdio ? process.stderr : null);

	// Set when Sandbox.run is called
	self._stdio = null;
	self._message_handler = new MessageHandler({
		api: self._api
	});;
	self._native_client_child = null;

}

/**
 *	Set the API
 */
Sandbox.prototype.setApi = function(api) {
	var self = this;
	self._message_handler.setApi(api);
};

/**
 * Run the given file inside the sandbox
 *
 * @param {String} file_path
 */
Sandbox.prototype.run = function(file_path, opts, callback) {
	var self = this;

	if (typeof opts === 'function') {
		callback = opts;
		opts = {};
	}

    opts = opts || {};

	// Create new sandbox
	self._native_client_child = self._spawnChildToRunCode(file_path, opts.env);
	self._native_client_child.on('exit', function(code){
		if (typeof callback === 'function') {
			callback();
		}
	});
	self._stdio = self._native_client_child.stdio;

	if (self._stdout_dest) {
		self._stdio[1].pipe(self._stdout_dest);
	}

	if (self._stderr_dest) {
		self._stdio[2].pipe(self._stderr_dest);
	}

	self._message_handler.setupStdio(self._stdio);

};

Sandbox.prototype._spawnChildToRunCode = function (file_path, env) {
	var self = this;

	if (self._disableNacl) {
		console.warn('NaCl is disabled');
	}

	var cmd = (self._disableNacl ? RUN_CONTRACT_DISABLE_NACL_COMMAND : RUN_CONTRACT_COMMAND);
	var args = (self._disableNacl ? RUN_CONTRACT_DISABLE_NACL_ARGS.slice() : RUN_CONTRACT_ARGS.slice());
	args.push(file_path);

	if (self._enableGdb) {
		args.unshift(cmd);
		args.unshift('localhost:4484');
		cmd = 'gdbserver';
	} else if (self._enableValgrind) {
		args.unshift('--');
		args.unshift(cmd);
		cmd = 'valgrind';
	}

	var child = spawn(cmd, args, {
		env: env,
		stdio: [ 'pipe', 'pipe', 'pipe', 'pipe',  'pipe' ]
	});

  child.on('error', self._handleChildProcessError.bind(self));

  return child;
};

/**
 * Handle child process errors and try to give a little bit better error information.
 */
Sandbox.prototype._handleChildProcessError = function (err) {
  // TODO Should this handle the error? Pass it on as an event?
  if (err.code === 'ENOENT') {
    // TODO Error information could be further improved, check whether libc is there etc.
    console.log('ENOENT: The child process was unable to spawn.');
    if (process.arch === 'x64') {
      console.error('Note that on x64 architectures you need to install the 32-bit versions of libc and libstdc++.');
    }
  } else {
    throw err;
  }
};

/**
 * Kill the sandbox process.
 *
 * @param {String} ['SIGKILL'] message
 */
Sandbox.prototype.kill = function(message){
	var self = this;

	if (self._native_client_child) {
		self._native_client_child.kill(message);
	}
};

/**
 * Pipe Native Client stdout and stderr to
 * the parent process' stdout and stderr
 */
Sandbox.prototype.passthroughStdio = function() {
	var self = this;

	self._stdout_dest = process.stdout;
	self._stderr_dest = process.stderr;
};

/**
 * Set up the sandbox's `stdout` stream to be piped to
 * the given destination when the child process is spawned
 */
Sandbox.prototype.pipeStdout = function(dest) {
	var self = this;

	self._stdout_dest = dest;
};

/**
 * Set up the sandbox's `stderr` stream to be piped to
 * the given destination when the child process is spawned
 */
Sandbox.prototype.pipeStderr = function(dest) {
	var self = this;

	self._stderr_dest = dest;
};

module.exports = Sandbox;
<|endoftext|>


<commit_before>/**
 * Copyright 2015 IBM Corp. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

require('assert');
var nock = require('nock');
var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
chai.should();

var ZosJobs = require('../zosjobs.js');

describe('zosjobs', function () {
  describe('getJobs', function () {
    it('should return a list of jobs', function () {
      var conn = new ZosJobs('http://test:9080', 'user', 'password', 'user');
      nock('http://test:9080').get('/zosmf/restjobs/jobs/').query({
        owner: 'user',
      }).reply(200, [{
          class: 'TSU',
          'files-url': 'https://winmvs21:20049/zosmf/restjobs/jobs//-JES2/SMITHSO/TSU34306/files',
          jobid: 'TSU34306',
          jobname: 'SMITHSO',
          owner: 'SMITHSO',
          retcode: null,
          status: 'ACTIVE',
          subsystem: 'JES2',
          type: 'TSU',
          url: 'https://winmvs21:20049/zosmf/restjobs/jobs//-JES2/SMITHSO/TSU34306',
        },
        {
          class: 'A',
          'files-url': 'https://winmvs21:20049/zosmf/restjobs/jobs//-JES2/TESTA/JOB34307/files',
          jobid: 'JOB34307',
          jobname: 'TESTA',
          owner: 'SMITHSO',
          retcode: null,
          status: 'ACTIVE',
          subsystem: 'JES2',
          type: 'JOB',
          url: 'https://winmvs21:20049/zosmf/restjobs/jobs//-JES2/TESTA/JOB34307',
        },
      ]);
      return conn.getJobs().should.eventually.have.keys('SMITHSO', 'TESTA');
    });
    it('should fail with a security error', function () {
      var conn = new ZosJobs('http://test:9080', 'user', 'password', 'user');
      nock('http://test:9080').get('/zosmf/restjobs/jobs/').query({
        owner: 'user',
      }).reply(403);
      return conn.getJobs().should.be.rejectedWith(403);
    });
    it('should fail due to network error', function () {
      var conn = new ZosJobs('http://test:9080', 'user', 'password', 'user');
      nock('http://test:9080').get('/zosmf/restjobs/jobs/').query({
        owner: 'user',
      }).replyWithError('Socket Error');
      return conn.getJobs().should.be.rejectedWith('Socket Error');
    });
  });
});
<commit_msg>Normalize responses for future use<commit_after>/**
 * Copyright 2015 IBM Corp. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

require('assert');
var nock = require('nock');
var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
chai.should();

var ZosJobs = require('../zosjobs.js');

describe('zosjobs', function () {
  describe('getJobs', function () {
    it('should return a list of jobs', function () {
      var conn = new ZosJobs('http://test:9080', 'user', 'password', 'user');
      nock('http://test:9080').get('/zosmf/restjobs/jobs/').query({
        owner: 'user',
      }).reply(200, [{
          class: 'TSU',
          'files-url': 'http://test:9080/zosmf/restjobs/jobs//-JES2/SMITHSO/TSU34306/files',
          jobid: 'TSU34306',
          jobname: 'SMITHSO',
          owner: 'SMITHSO',
          retcode: null,
          status: 'ACTIVE',
          subsystem: 'JES2',
          type: 'TSU',
          url: 'http://test:9080/zosmf/restjobs/jobs//-JES2/SMITHSO/TSU34306',
        },
        {
          class: 'A',
          'files-url': 'http://test:9080/zosmf/restjobs/jobs//-JES2/TESTA/JOB34307/files',
          jobid: 'JOB34307',
          jobname: 'TESTA',
          owner: 'SMITHSO',
          retcode: null,
          status: 'ACTIVE',
          subsystem: 'JES2',
          type: 'JOB',
          url: 'http://test:9080/zosmf/restjobs/jobs//-JES2/TESTA/JOB34307',
        },
      ]);
      return conn.getJobs().should.eventually.have.keys('SMITHSO', 'TESTA');
    });
    it('should fail with a security error', function () {
      var conn = new ZosJobs('http://test:9080', 'user', 'password', 'user');
      nock('http://test:9080').get('/zosmf/restjobs/jobs/').query({
        owner: 'user',
      }).reply(403);
      return conn.getJobs().should.be.rejectedWith(403);
    });
    it('should fail due to network error', function () {
      var conn = new ZosJobs('http://test:9080', 'user', 'password', 'user');
      nock('http://test:9080').get('/zosmf/restjobs/jobs/').query({
        owner: 'user',
      }).replyWithError('Socket Error');
      return conn.getJobs().should.be.rejectedWith('Socket Error');
    });
  });
});
<|endoftext|>


<commit_before>const lit = require('fountain-generator').lit;

module.exports = function karmaConf(props) {
  const conf = {
    browsers: ['PhantomJS'],
    basePath: '../',
    singleRun: props.singleRun,
    autoWatch: !props.singleRun,
    logLevel: 'INFO',
    junitReporter: { outputDir: 'test-reports' }
  };

  const pathSrcJs = lit`conf.path.src('index.spec.js')`;
  const pathSrcHtml = lit`conf.path.src('**/*.html')`;

  if (props.modules === 'systemjs') {
    conf.frameworks = ['phantomjs-shim', 'jspm', 'jasmine'];
  } else if (props.modules === 'inject' && props.framework === 'angular1') {
    conf.frameworks = ['phantomjs-shim', 'jasmine', 'angular-filesort'];
  } else {
    conf.frameworks = ['phantomjs-shim', 'jasmine'];
  }

  if (props.modules === 'webpack') {
    conf.files = [
      'node_modules/es6-shim/es6-shim.js',
      pathSrcJs
    ];

    if (props.framework === 'angular1') {
      conf.files.push(pathSrcHtml);
    }
  }
  if (props.modules === 'inject') {
    conf.files = lit`listFiles()`;
  }

  if (props.modules === 'webpack' || props.framework === 'angular1') {
    conf.preprocessors = {};
  }
  if (props.modules === 'webpack') {
    conf.preprocessors[pathSrcJs] = ['webpack'];
  }
  if (props.framework === 'angular1') {
    conf.preprocessors[pathSrcHtml] = ['ng-html2js'];
    if (props.modules === 'systemjs' && props.js === 'typescript') {
      conf.preprocessors[pathSrcHtml].push('generic');
      conf.genericPreprocessor = {
        rules: [lit`{
        process(content, file, done) {
          file.path = file.path.replace(/\\.js$/, '.ts');
          done(content);
        }
      }`]
      };
    }
  }

  if (props.framework === 'angular1') {
    conf.ngHtml2JsPreprocessor = {};

    if (props.modules !== 'systemjs') {
      conf.ngHtml2JsPreprocessor.stripPrefix = lit`\`\${conf.paths.src}/\``;
    }

    if (props.modules === 'inject') {
      conf.angularFilesort = {
        whitelist: [lit`conf.path.tmp('**/!(*.html|*.spec|*.mock).js')`]
      };
    }
  }

  if (props.modules === 'webpack') {
    conf.webpack = lit`require('./webpack-test.conf.js')`;
    conf.webpackMiddleware = { noInfo: true };
  }

  if (props.modules === 'systemjs') {
    conf.jspm = {
      loadFiles: []
    };

    if (props.framework === 'angular2') {
      conf.jspm.loadFiles.push(
        'jspm_packages/npm/reflect-metadata@0.1.2/Reflect.js',
        'node_modules/es6-shim/es6-shim.js'
      );
    }

    if (props.js === 'typescript') {
      if (props.framework === 'react') {
        conf.jspm.loadFiles.push(lit`conf.path.src('app/**/*.tsx')`);
      } else {
        conf.jspm.loadFiles.push(lit`conf.path.src('app/**/*.ts')`);
      }
    } else {
      conf.jspm.loadFiles.push(lit`conf.path.src('app/**/*.js')`);
    }

    // if (props.framework !== 'react') {
    if (props.framework === 'angular1') {
      conf.jspm.loadFiles.push(lit`conf.path.src('**/*.html')`);
    }
  }

  conf.plugins = [
    lit`require('karma-jasmine')`,
    lit`require('karma-junit-reporter')`,
    lit`require('karma-phantomjs-launcher')`,
    lit`require('karma-phantomjs-shim')`,
    lit`require('karma-coverage')`
  ];

  if (props.framework === 'angular1') {
    conf.plugins.push(lit`require('karma-ng-html2js-preprocessor')`);
  }
  if (props.modules === 'webpack') {
    conf.plugins.push(lit`require('karma-webpack')`);
  }
  if (props.modules === 'systemjs') {
    conf.plugins.push(lit`require('karma-jspm')`);
  }
  if (props.modules === 'inject' && props.framework === 'angular1') {
    conf.plugins.push(lit`require('karma-angular-filesort')`);
  }
  if (props.modules === 'systemjs' && props.framework === 'angular1' && props.js === 'typescript') {
    conf.plugins.push(lit`require('karma-generic-preprocessor')`);
  }

  return conf;
};
<commit_msg>Specify jspm config file<commit_after>const lit = require('fountain-generator').lit;

module.exports = function karmaConf(props) {
  const conf = {
    browsers: ['PhantomJS'],
    basePath: '../',
    singleRun: props.singleRun,
    autoWatch: !props.singleRun,
    logLevel: 'INFO',
    junitReporter: { outputDir: 'test-reports' }
  };

  const pathSrcJs = lit`conf.path.src('index.spec.js')`;
  const pathSrcHtml = lit`conf.path.src('**/*.html')`;

  if (props.modules === 'systemjs') {
    conf.frameworks = ['phantomjs-shim', 'jspm', 'jasmine'];
  } else if (props.modules === 'inject' && props.framework === 'angular1') {
    conf.frameworks = ['phantomjs-shim', 'jasmine', 'angular-filesort'];
  } else {
    conf.frameworks = ['phantomjs-shim', 'jasmine'];
  }

  if (props.modules === 'webpack') {
    conf.files = [
      'node_modules/es6-shim/es6-shim.js',
      pathSrcJs
    ];

    if (props.framework === 'angular1') {
      conf.files.push(pathSrcHtml);
    }
  }
  if (props.modules === 'inject') {
    conf.files = lit`listFiles()`;
  }

  if (props.modules === 'webpack' || props.framework === 'angular1') {
    conf.preprocessors = {};
  }
  if (props.modules === 'webpack') {
    conf.preprocessors[pathSrcJs] = ['webpack'];
  }
  if (props.framework === 'angular1') {
    conf.preprocessors[pathSrcHtml] = ['ng-html2js'];
    if (props.modules === 'systemjs' && props.js === 'typescript') {
      conf.preprocessors[pathSrcHtml].push('generic');
      conf.genericPreprocessor = {
        rules: [lit`{
        process(content, file, done) {
          file.path = file.path.replace(/\\.js$/, '.ts');
          done(content);
        }
      }`]
      };
    }
  }

  if (props.framework === 'angular1') {
    conf.ngHtml2JsPreprocessor = {};

    if (props.modules !== 'systemjs') {
      conf.ngHtml2JsPreprocessor.stripPrefix = lit`\`\${conf.paths.src}/\``;
    }

    if (props.modules === 'inject') {
      conf.angularFilesort = {
        whitelist: [lit`conf.path.tmp('**/!(*.html|*.spec|*.mock).js')`]
      };
    }
  }

  if (props.modules === 'webpack') {
    conf.webpack = lit`require('./webpack-test.conf.js')`;
    conf.webpackMiddleware = { noInfo: true };
  }

  if (props.modules === 'systemjs') {
    conf.jspm = {
      loadFiles: []
      config: 'jspm.config.js'
    };

    if (props.framework === 'angular2') {
      conf.jspm.loadFiles.push(
        'jspm_packages/npm/reflect-metadata@0.1.2/Reflect.js',
        'node_modules/es6-shim/es6-shim.js'
      );
    }

    if (props.js === 'typescript') {
      if (props.framework === 'react') {
        conf.jspm.loadFiles.push(lit`conf.path.src('app/**/*.tsx')`);
      } else {
        conf.jspm.loadFiles.push(lit`conf.path.src('app/**/*.ts')`);
      }
    } else {
      conf.jspm.loadFiles.push(lit`conf.path.src('app/**/*.js')`);
    }

    // if (props.framework !== 'react') {
    if (props.framework === 'angular1') {
      conf.jspm.loadFiles.push(lit`conf.path.src('**/*.html')`);
    }
  }

  conf.plugins = [
    lit`require('karma-jasmine')`,
    lit`require('karma-junit-reporter')`,
    lit`require('karma-phantomjs-launcher')`,
    lit`require('karma-phantomjs-shim')`,
    lit`require('karma-coverage')`
  ];

  if (props.framework === 'angular1') {
    conf.plugins.push(lit`require('karma-ng-html2js-preprocessor')`);
  }
  if (props.modules === 'webpack') {
    conf.plugins.push(lit`require('karma-webpack')`);
  }
  if (props.modules === 'systemjs') {
    conf.plugins.push(lit`require('karma-jspm')`);
  }
  if (props.modules === 'inject' && props.framework === 'angular1') {
    conf.plugins.push(lit`require('karma-angular-filesort')`);
  }
  if (props.modules === 'systemjs' && props.framework === 'angular1' && props.js === 'typescript') {
    conf.plugins.push(lit`require('karma-generic-preprocessor')`);
  }

  return conf;
};
<|endoftext|>


<commit_before>function NineSlice(image) {
    var img = image;
    return {
        topLeft:undefined, top:undefined, topRight:undefined,
        right:undefined, bottomRight:undefined, bottom:undefined,
        bottomLeft:undefined, left:undefined, center:undefined,

        copyDimensions: function(slice) {
            this.topLeft = slice.topLeft;
            this.top = slice.top;
            this.topRight = slice.topRight;
            this.right = slice.right;
            this.bottomRight = slice.bottomRight;
            this.bottom = slice.bottom;
            this.bottomLeft = slice.bottomLeft;
            this.left = slice.left;
            this.center = slice.center;
        },

        render: function(gc, x, y, width, height) {
            gc.drawImage(img, this.left.x, this.left.y, this.left.width, this.left.height, x, y+this.topLeft.height, this.left.width, height-this.topLeft.height); //Left
            gc.drawImage(img, this.top.x, this.top.y, this.top.width, this.top.height, x+this.topLeft.width, y, width-this.topLeft.width, this.top.height); //Top
            gc.drawImage(img, this.right.x, this.right.y, this.right.width, this.right.height, x+width, y+this.topRight.height, this.right.width, height-this.topRight.height); //Right
            gc.drawImage(img, this.bottom.x, this.bottom.y, this.bottom.width, this.bottom.height, x+this.bottomLeft.width, y+height, width-this.bottomLeft.width, this.bottom.height); //Bottom
            gc.drawImage(img, this.topLeft.x, this.topLeft.y, this.topLeft.width, this.topLeft.height, x, y, this.topLeft.width, this.topLeft.height); //TopLeft
            gc.drawImage(img, this.topRight.x, this.topRight.y, this.topRight.width, this.topRight.height, x+width, y, this.topRight.width, this.topRight.height); //TopRight
            gc.drawImage(img, this.bottomRight.x, this.bottomRight.y, this.bottomRight.width, this.bottomRight.height, x+width, y+height, this.bottomRight.width, this.bottomRight.height); //BottomRight
            gc.drawImage(img, this.bottomLeft.x, this.bottomLeft.y, this.bottomLeft.width, this.bottomLeft.height, x, y+height, this.bottomRight.width, this.bottomRight.height); //BottomLeft
            if (this.center) gc.drawImage(img, this.center.x, this.center.y, this.center.width, this.center.height, x+this.left.width, y+this.top.height, width-this.left.width, height-this.top.height); //Center
        },
    }
}

function Graphic(image) {
    var img = image;
    return {
        x: 0,
        y: 0,
        scaleX: 1,
        scaleY: 1,
        originX: 0,
        originY: 0,
        angle: 0,
        render: function(gc) {
            gc.save();
            gc.translate(this.x, this.y);
            gc.rotate(this.angle*(Math.PI/180));
            gc.drawImage(img, -this.originX, -this.originY, img.width * this.scaleX, img.height * this.scaleY);
            gc.rotate(0);
            gc.restore();
        },

        getImage: function() {
            return img;
        },

        getWidth: function() {
            return img.width;
        },

        getHeight: function() {
            return img.height;
        },
    }
}

function Animation(image, _cellWidth, _cellHeight) {
    'use strict';
    var base = Graphic(image),
    cellWidth = _cellWidth,
    cellHeight = _cellHeight,
    cells,
    cell = 0,
    timer = 0,
    speed = 1;

    base.onComplete = undefined;

    base.update = function(delta) {
        if (timer >= delta) {
            if (cell < cells) {
                cell++;
            } else {
                if (base.onComplete) {
                    base.onComplete();
                }
                cell = 0;
            }
            timer = 0;
        } else {
            timer += delta * speed;
        }
    };

    base.render = function(gc) {
        var img = base.getImage();
        cells = img.width / cellWidth - 1; //For some reason base.img won't work in the constructor.

        gc.save();
        gc.translate(base.x, base.y);
        gc.rotate(base.angle*(Math.PI/180));
        gc.drawImage(img, cell*cellWidth, 0, cellWidth, cellHeight, -base.originX, -base.originY, cellWidth * base.scaleX, cellHeight * base.scaleY);
        gc.rotate(0);
        gc.restore();
    };

    base.getWidth = function() {
        return cellWidth;
    };

    base.getHeight = function() {
        return cellHeight;
    };

    base.getSpeed = function() {
        return speed;
    };

    base.setSpeed = function(value) {
        speed = value;
    };

    return base;
}
<commit_msg>NineSlices can now be cached if they are static.<commit_after>function NineSlice(image) {
    var img = image;
    return {
        topLeft:undefined, top:undefined, topRight:undefined,
        right:undefined, bottomRight:undefined, bottom:undefined,
        bottomLeft:undefined, left:undefined, center:undefined,

        cached: false,
        cache: undefined,

        copyDimensions: function(slice) {
            this.topLeft = slice.topLeft;
            this.top = slice.top;
            this.topRight = slice.topRight;
            this.right = slice.right;
            this.bottomRight = slice.bottomRight;
            this.bottom = slice.bottom;
            this.bottomLeft = slice.bottomLeft;
            this.left = slice.left;
            this.center = slice.center;
        },

        render: function(gc, x, y, width, height) {
            gc.drawImage(img, this.left.x, this.left.y, this.left.width, this.left.height, x, y+this.topLeft.height, this.left.width, height-this.topLeft.height); //Left
            gc.drawImage(img, this.top.x, this.top.y, this.top.width, this.top.height, x+this.topLeft.width, y, width-this.topLeft.width, this.top.height); //Top
            gc.drawImage(img, this.right.x, this.right.y, this.right.width, this.right.height, x+width, y+this.topRight.height, this.right.width, height-this.topRight.height); //Right
            gc.drawImage(img, this.bottom.x, this.bottom.y, this.bottom.width, this.bottom.height, x+this.bottomLeft.width, y+height, width-this.bottomLeft.width, this.bottom.height); //Bottom
            gc.drawImage(img, this.topLeft.x, this.topLeft.y, this.topLeft.width, this.topLeft.height, x, y, this.topLeft.width, this.topLeft.height); //TopLeft
            gc.drawImage(img, this.topRight.x, this.topRight.y, this.topRight.width, this.topRight.height, x+width, y, this.topRight.width, this.topRight.height); //TopRight
            gc.drawImage(img, this.bottomRight.x, this.bottomRight.y, this.bottomRight.width, this.bottomRight.height, x+width, y+height, this.bottomRight.width, this.bottomRight.height); //BottomRight
            gc.drawImage(img, this.bottomLeft.x, this.bottomLeft.y, this.bottomLeft.width, this.bottomLeft.height, x, y+height, this.bottomRight.width, this.bottomRight.height); //BottomLeft
            if (this.center) gc.drawImage(img, this.center.x, this.center.y, this.center.width, this.center.height, x+this.left.width, y+this.top.height, width-this.left.width, height-this.top.height); //Center
        },

        renderCache: function(gc, x, y, width, height) {
            if (!this.cached) {
                var c = document.createElement('canvas');
                var ctx = c.getContext('2d');

                this.render(ctx, 0, 0, width, height);

                this.cache = c;
                this.cached = true;
            }

            gc.drawImage(this.cache, x, y);
        },
    }
}

function Graphic(image) {
    var img = image;
    return {
        x: 0,
        y: 0,
        scaleX: 1,
        scaleY: 1,
        originX: 0,
        originY: 0,
        angle: 0,
        render: function(gc) {
            gc.save();
            gc.translate(this.x, this.y);
            gc.rotate(this.angle*(Math.PI/180));
            gc.drawImage(img, -this.originX, -this.originY, img.width * this.scaleX, img.height * this.scaleY);
            gc.rotate(0);
            gc.restore();
        },

        getImage: function() {
            return img;
        },

        getWidth: function() {
            return img.width;
        },

        getHeight: function() {
            return img.height;
        },
    }
}

function Animation(image, _cellWidth, _cellHeight) {
    'use strict';
    var base = Graphic(image),
    cellWidth = _cellWidth,
    cellHeight = _cellHeight,
    cells,
    cell = 0,
    timer = 0,
    speed = 1;

    base.onComplete = undefined;

    base.update = function(delta) {
        if (timer >= delta) {
            if (cell < cells) {
                cell++;
            } else {
                if (base.onComplete) {
                    base.onComplete();
                }
                cell = 0;
            }
            timer = 0;
        } else {
            timer += delta * speed;
        }
    };

    base.render = function(gc) {
        var img = base.getImage();
        cells = img.width / cellWidth - 1; //For some reason base.img won't work in the constructor.

        gc.save();
        gc.translate(base.x, base.y);
        gc.rotate(base.angle*(Math.PI/180));
        gc.drawImage(img, cell*cellWidth, 0, cellWidth, cellHeight, -base.originX, -base.originY, cellWidth * base.scaleX, cellHeight * base.scaleY);
        gc.rotate(0);
        gc.restore();
    };

    base.getWidth = function() {
        return cellWidth;
    };

    base.getHeight = function() {
        return cellHeight;
    };

    base.getSpeed = function() {
        return speed;
    };

    base.setSpeed = function(value) {
        speed = value;
    };

    return base;
}
<|endoftext|>


<commit_before>/*
* Benchmark Engine Rules for Developers
*   1-Define the tests Suites to run using the filename of the javascript
*   in the suites array in runAllEnabledTestSuites() method in the form {"name" : testSelectors_1, "enabled": true|false }.
*   2-The name of the suite inside the file must be the same as the name of the file.
*   3-Include the JavaScript file in the benchmark.html head.
*/

/* CONSTANT TO DEFINE NUMBER OF REPEAT OF SUITE */
var TIMES_REPEAT_SUITE = 1;

/* FLAG TO ENABLE (true)|DISABLE (false) PRINT AS TABLE */
var PRINT_TABLE = false;

function runAllEnabledTestSuites(){
  // Define the test suites using the names as defined in the files
  var suites = [
                {"name" : testSelectors_1, "enabled": true },
                {"name" : testSelectors_2, "enabled": false },
                {"name" : testSelectors_3, "enabled": false},
                {"name" : testChecked, "enabled": false},
                {"name" : testParseNumber, "enabled": false},
                {"name" : testLoopFor, "enabled": false}
               ];

  //Run as many times as defined in the constant
  while(TIMES_REPEAT_SUITE !== 0) {
    //Run the enabled suites
    for(var i=0; i<suites.length; i++) {
      if(suites[i].enabled === true && suites[i].enabled !== undefined) {
        suites[i].name.execute();
      }
    }
    TIMES_REPEAT_SUITE--;
  }
};<commit_msg>Added setInterval between run of benchmarks<commit_after>/*
* Benchmark Engine Rules for Developers
*   1-Define the tests Suites to run using the filename of the javascript
*   in the suites array in runAllEnabledTestSuites() method in the form {"name" : testSelectors_1, "enabled": true|false }.
*   2-The name of the suite inside the file must be the same as the name of the file.
*   3-Include the JavaScript file in the benchmark.html head.
*/

/* CONSTANT TO DEFINE NUMBER OF REPEAT OF SUITE */
var TIMES_REPEAT_SUITE = 30;

/* FLAG TO ENABLE (true)|DISABLE (false) PRINT AS TABLE */
var PRINT_TABLE = true;

var suites = [];
function runSuitesMultipleTimes(){

	// Define the test suites using the names as defined in the files
	suites = [
					{"name" : testSelectors_1, "enabled": false },
					{"name" : testSelectors_2, "enabled": false },
					{"name" : testSelectors_3, "enabled": false},
					{"name" : testChecked, "enabled": false},
					{"name" : testParseNumber, "enabled": false},
					{"name" : testLoopFor, "enabled": false},
					{"name" : testGetElementsById, "enabled": false},
					{"name" : testGetElementsByClassName, "enabled": false},
					{"name" : testGetElementsByTagName, "enabled": true}
				   ];
	interval = setInterval(runEnabledSuites, 1000);
};
function runEnabledSuites() {
	if(TIMES_REPEAT_SUITE !== 0) {
		TIMES_REPEAT_SUITE--;
		for(var i=0; i<suites.length; i++) {
		  if(suites[i].enabled === true && suites[i].enabled !== undefined) {
			suites[i].name.execute();
		  }
		}
	}
	else {
		clearInterval(interval);
	}
};<|endoftext|>


<commit_before>'use strict'
var evaluate = require('../util/test')
var isPlainObj = require('../util').isPlainObj
var createPath
var getPath

exports.clean = function (obj, index) {
  if (obj.constructor === Array) {
    return obj.splice(0, index)
  }
  while (obj[index]) {
    delete obj[index++]
  }
  return obj
}

exports.createPath = createPath = function (obj, path, length, set) {
  var setObj = {}
  var nextObj = setObj
  var i = 0
  var field
  for (;i < length - 1; i++) {
    field = path[i]
    nextObj[field] = {}
    nextObj = nextObj[field]
  }
  if (set !== void 0) {
    nextObj[path[i]] = set
  } else {
    nextObj[path[i]] = {}
  }
  obj.set(setObj)
  return getPath(obj, path, length)
}

exports.getPath = getPath = function (obj, path, length, filter, set) {
  var i = 0
  var result = obj[path[0]]

  while (result) {
    if (++i === length) {
      if (filter === void 0 || filter(result, obj)) {
        return result
      }
    }
    if (typeof result === 'function') {
      return result.call(obj, path.splice(i), filter)
    }
    obj = result
    result = result[path[i]]
  }

  if (set !== void 0) {
    return createPath(obj, path.splice(i), length - i, set)
  }
}

exports.returnFilter = function (options) {
  if (options !== void 0) {
    var conditions
    // var filter

    if (typeof options === 'function') {
      return options
    }

    if (isPlainObj(options)) {
      conditions = options.conditions

      if (conditions) {
        return function (subject) {
          return evaluate(subject, conditions)
        }
      }

      if (options instanceof RegExp) {
        return function (subject) {
          return options.test(subject)
        }
      }

      if (options.constructor === Array) {
        var length = options.length
        return function (subject) {
          for (var i = length - 1; i >= 0; i--) {
            var value = options[i]
            if (subject === value || subject.input === value) {
              return true
            }
          }
        }
      }
    } else {
      return function (subject) {
        return subject === options || subject.input === options
      }
    }
  }
}

exports.returnPath = function (path) {
  return typeof path === 'string' ? path.split('.') : path
}
<commit_msg>commented function parse functionality (want to be able to look within functions)<commit_after>'use strict'
var evaluate = require('../util/test')
var isPlainObj = require('../util').isPlainObj
var createPath
var getPath

exports.clean = function (obj, index) {
  if (obj.constructor === Array) {
    return obj.splice(0, index)
  }
  while (obj[index]) {
    delete obj[index++]
  }
  return obj
}

exports.createPath = createPath = function (obj, path, length, set) {
  var setObj = {}
  var nextObj = setObj
  var i = 0
  var field
  for (;i < length - 1; i++) {
    field = path[i]
    nextObj[field] = {}
    nextObj = nextObj[field]
  }
  if (set !== void 0) {
    nextObj[path[i]] = set
  } else {
    nextObj[path[i]] = {}
  }
  obj.set(setObj)
  return getPath(obj, path, length)
}

exports.getPath = getPath = function (obj, path, length, filter, set) {
  var i = 0
  var result = obj[path[0]]

  while (result) {
    if (++i === length) {
      if (filter === void 0 || filter(result, obj)) {
        return result
      }
    }
    // if (typeof result === 'function') {
      //this is what goes wrong :/
      // return result.call(obj, path.splice(i), filter)
    // }
    obj = result
    result = result[path[i]]
  }

  if (set !== void 0) {
    return createPath(obj, path.splice(i), length - i, set)
  }
}

exports.returnFilter = function (options) {
  if (options !== void 0) {
    var conditions
    // var filter

    if (typeof options === 'function') {
      return options
    }

    if (isPlainObj(options)) {
      conditions = options.conditions

      if (conditions) {
        return function (subject) {
          return evaluate(subject, conditions)
        }
      }

      if (options instanceof RegExp) {
        return function (subject) {
          return options.test(subject)
        }
      }

      if (options.constructor === Array) {
        var length = options.length
        return function (subject) {
          for (var i = length - 1; i >= 0; i--) {
            var value = options[i]
            if (subject === value || subject.input === value) {
              return true
            }
          }
        }
      }
    } else {
      return function (subject) {
        return subject === options || subject.input === options
      }
    }
  }
}

exports.returnPath = function (path) {
  return typeof path === 'string' ? path.split('.') : path
}
<|endoftext|>


<commit_before>mini.Module(
		"engine/game"
)
.requires(
		"engine/loop",
		"engine/config",
		"basic/canvas",
		"basic/audio/audio",
		"basic/audio/music",
		"basic/audio/sound",
		"bloob/scenes/titlescene"
)
.defines(function(Loop, Config, Canvas, Audio, Track, Sound, TitleScene) {
	var Game = mini.Class.subclass({
		initialize: function(configuration) {
			this.config = configuration || Config.getDefault();
			this.id = Game.nextGameID++;
			console.log("NEW GAME: " + this.id);
			this.init();
		},
		init: function() {
			// prepare datGui
			this.datGui = new dat.GUI();
			var obj = {
				testServerPost: function() {
					var path = "untitled.js";
					var dataString = "THIS IS THE DATA";

					var postString =
						'path=' + encodeURIComponent( path ) +
						'&data=' + encodeURIComponent(dataString);

					var req = $.ajax({
						url: 'lib/weltmeister/api/save.php',
						type: 'POST',
						dataType: 'json',
						async: false,
						data: postString,
						success: function() {
							console.log("FILE SAVED");
						}
					});
				},
				testReadFiles: function() {
					var dir = '';
					var fileType = "scripts";

					var path = 'lib/weltmeister/api/browse.php' + '?dir=' + encodeURIComponent( dir || '' ) + '&type=' + fileType;
					var req = $.ajax({
						url: path,
						dataType: 'json',
						async: false,
						success: function(data) {
							console.log(data);
						}
					});
				},
				testGlob: function() {

				}
			};
			this.datGui.add(obj, "testServerPost");
			this.datGui.add(obj, "testReadFiles");
			this.datGui.add(obj, "testGlob");

			// prepare stats
			this.stats = new Stats();
			$("body").prepend(this.stats.domElement);

			// Configure and start the game loop.
			this.loop = new Loop()
				.clear()
				.add(this.stats, this.stats.update)
				.start();

			this.canvas = new Canvas({canvasId: "bloobCanvas" + this.id});
			this.audio = new Audio();

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

	Game.nextGameID = 0;

	return Game;
});
<commit_msg>extracted testServer method<commit_after>mini.Module(
		"engine/game"
)
.requires(
		"engine/loop",
		"engine/config",
		"basic/canvas",
		"basic/audio/audio",
		"basic/audio/music",
		"basic/audio/sound",
		"bloob/scenes/titlescene"
)
.defines(function(Loop, Config, Canvas, Audio, Track, Sound, TitleScene) {
	var Game = mini.Class.subclass({
		initialize: function(configuration) {
			this.config = configuration || Config.getDefault();
			this.id = Game.nextGameID++;
			console.log("NEW GAME: " + this.id);
			this.init();
		},
		init: function() {
			// prepare datGui
			this.datGui = new dat.GUI();
			this.testServer();

			// prepare stats
			this.stats = new Stats();
			$("body").prepend(this.stats.domElement);

			// Configure and start the game loop.
			this.loop = new Loop()
				.clear()
				.add(this.stats, this.stats.update)
				.start();

			this.canvas = new Canvas({canvasId: "bloobCanvas" + this.id});
			this.audio = new Audio();

			var titleScene = new TitleScene(this, this.loop).run();
		},
		testServer: function() {
			var obj = {
				testServerPost: function() {
					var path = "untitled.js";
					var dataString = "THIS IS THE DATA";

					var postString =
						'path=' + encodeURIComponent( path ) +
						'&data=' + encodeURIComponent(dataString);

					var req = $.ajax({
						url: 'lib/weltmeister/api/save.php',
						type: 'POST',
						dataType: 'json',
						async: false,
						data: postString,
						success: function() {
							console.log("FILE SAVED");
						}
					});
				},
				testReadFiles: function() {
					var dir = '';
					var fileType = "scripts";

					var path = 'lib/weltmeister/api/browse.php' + '?dir=' + encodeURIComponent( dir || '' ) + '&type=' + fileType;
					var req = $.ajax({
						url: path,
						dataType: 'json',
						async: false,
						success: function(data) {
							console.log(data);
						}
					});
				},
				testGlob: function() {

				}
			};
			this.datGui.add(obj, "testServerPost");
			this.datGui.add(obj, "testReadFiles");
			this.datGui.add(obj, "testGlob");
		}
	});

	Game.nextGameID = 0;

	return Game;
});
<|endoftext|>


<commit_before>// ==UserScript==
// @name           plugdj-playlist-exporter
// @description    Creates plug.dj playlist JSON files, and saves them to harddrive.
// @author         Ivan (sq10.net)
// @include        https://plug.dj/*
// @version        2.0.3
// ==/UserScript==

var playlists = {};

function check_for_api(){
    //We're going to keep trying to attach the API handler
    //until window.API shows up
    try{ready_up();}
    catch(e){setTimeout(check_for_api, 50);}
}

function ready_up(){
    //Attach the API.CHAT_COMMAND handler
    API.on(API.CHAT_COMMAND, function(val){
        if(val == "/pexport")
            start_export();
    });
}

function start_export(){
    API.chatLog("[PYE] Step 1: Load FileSaver.js");
    $.getScript("https://media.sq10.net/pye/FileSaver.js").done(function(){
        get_playlist_listing();
    }).fail(function(jqxhr, settings, exception){
        API.chatLog("[PYE] Could not fetch FileSaver.js!", true);
        API.chatLog("[PYE] Exception: "+String(exception), true);
    });
}

function parse_playlists(){
    API.chatLog("[PYE] Step 4: Parsing playlists into PYE JSON file.")
    var jo = {
        is_plugdj_playlist: true,
        userid: API.getUser().username,
        playlists: {}
    };

    for (var i in playlists){
        var item = playlists[i];

        var ct = 1,
            oldName = item.name,
            newName = item.name;

        while (jo.playlists[newName]){
            newName = oldName+" ("+ct+")";
            ct++;
        }

        jo.playlists[newName] = [];
        for (var x=0;x<item.items.length;x++){
            var media = item.items[x];
            jo.playlists.push({
                type:media.format,
                id:media.cid
            });
        }
    }

    save_json(jo);
}

function get_playlists(){
    API.chatLog("[PYE] Step 3: Fetch individual playlists");

    function finish(){
        parse_playlists();
    }

    var queue = [];
    var totalQueue;
    function fetch_next(){
        if (!queue.length){
            finish();
            return;
        }
        var cur = queue.pop();
        API.chatLog("[PYE] Fetching playlist "+(totalQueue-queue.length)+" of "+totalQueue);

        function fail(){
            API.chatLog("[PYE] Could not fetch playlist id:"+cur+"! Aborting.");
            return;
        }
        function success(data){
            if (!data.status == "ok"){
                API.chatLog("[PYE] Could not fetch playlist id:"+cur+"! Status: "+data.status+". Aborting.");
                return;
            }
            playlists[cur].items = data.data;
            setTimeout(fetch_next, 1000);
        }

        $.ajax({
            url: "https://plug.dj/_/playlists/"+cur+"/media",
            contentType: "application/json",
            dataType: "json",
            type: "GET",
            fail: fail,
            success: success
        });
    }
    for (var i in playlists){
        queue.push(i);
    }
    totalQueue = queue.length;
    fetch_next();
}

function get_playlist_listing(){
    API.chatLog("[PYE] Step 2: Fetch playlist listing");

    //Define the handler functions.
    function ajax_success(data){
        if (data.status != "ok"){
            API.chatLog("[PYE] Could not get playlist listing! Status: "+data.status, true);
            return;
        }
        var body = data.data;
        API.chatLog("[PYE] Parsing listing.");

        for (var i=0;i<body.length;i++){
            playlists[body[i].id] = {
                name: body[i].name
            };
        }

        setTimeout(get_playlists);
    }

    function ajax_error(jqXHR, textStatus, errorThrown){
        API.chatLog("[PYE] Could not fetch the playlists object!", true);
        API.chatLog("[PYE] Error: "+String(errorThrown), true);
    }

    //Make the AJAX call.
    $.ajax({
        url: "https://plug.dj/_/playlists",
        contentType: "application/json",
        dataType: "json",
        type: "GET",
        fail: ajax_error,
        success: ajax_success
    });
}

function save_json(obj){
    API.chatLog("[PYE] Step 5: Saving playlist file.");
    var blob = new Blob(
        [JSON.stringify(obj)],
        {
            type: "application/json;charset=utf-8"
        }
    );
    saveAs(blob, "PLUG_PLAYLISTS.json");
    API.chatLog("[PYE] Done! You should have downloaded PLUG_PLAYLISTS.json by now.", true);
}
setTimeout(check_for_api, 50);<commit_msg>pause button<commit_after>// ==UserScript==
// @name           plugdj-playlist-exporter
// @description    Creates plug.dj playlist JSON files, and saves them to harddrive.
// @author         Ivan (sq10.net)
// @include        https://plug.dj/*
// @version        2.0.5
// ==/UserScript==

var playlists = {};
var accepted = false;

function check_for_api(){
    //We're going to keep trying to attach the API handler
    //until window.API shows up
    try{ready_up();}
    catch(e){setTimeout(check_for_api, 50);}
}

function ready_up(){
    //Attach the API.CHAT_COMMAND handler
    API.on(API.CHAT_COMMAND, function(val){
        if(val == "/pexport")
            start_export();
    });
}

function start_export(){
    if (!accepted){
        API.chatLog("[PYE] WARNING", true);
        API.chatLog(
            "BE CAREFUL USING THIS EXTENSION. "+
            "WHEN YOU GET AN ALERT IN WHICH PYE IS SENDING TOO MANY REQUESTS, "+
            "PRESS THE PAUSE BUTTON IN THE TOP LEFT CORNER IMMEDIATELY."
        , true);
        API.chatLog(
            "If you have read this warning, and want to run the exporter, "+
            "run the /pexport command again."
        );
        accepted = true;
        return;
    }
    API.chatLog("[PYE] Step 1: Load FileSaver.js");
    $.getScript("https://media.sq10.net/pye/FileSaver.js").done(function(){
        get_playlist_listing();
    }).fail(function(jqxhr, settings, exception){
        API.chatLog("[PYE] Could not fetch FileSaver.js!", true);
        API.chatLog("[PYE] Exception: "+String(exception), true);
    });
}

function parse_playlists(){
    API.chatLog("[PYE] Step 4: Parsing playlists into PYE JSON file.")
    var jo = {
        is_plugdj_playlist: true,
        userid: API.getUser().username,
        playlists: {}
    };

    for (var i in playlists){
        var item = playlists[i];

        var ct = 1,
            oldName = item.name,
            newName = item.name;

        while (jo.playlists[newName]){
            newName = oldName+" ("+ct+")";
            ct++;
        }

        jo.playlists[newName] = [];
        for (var x=0;x<item.items.length;x++){
            var media = item.items[x];
            jo.playlists.push({
                type:media.format,
                id:media.cid
            });
        }
    }

    save_json(jo);
}

function get_playlists(){
    API.chatLog("[PYE] Step 3: Fetch individual playlists");

    var cooloff = false;

    $("body").append("
PAUSE PYE
");
    $("#pye-pexport").css({
        position: "fixed",
        top: "55px",
        left: "0px",
        width: "200px",
        height: "100px",
        "font-size": "45px",
        "line-height": "50px",
        "color":"white",
        "background-color":"red",
        "cursor":"pointer",
        "text-align":"center",
        "z-index":10000
    });
    $("#pye-export").on("click", function(){
        cooloff = true;
    });

    function finish(){
        parse_playlists();
    }

    var queue = [];
    var totalQueue;
    function fetch_next(){
        if (!queue.length){
            finish();
            return;
        }

        if (cooloff){
            API.chatLog("[PYE] Pause button pressed. Cooling off for 15 seconds.");
            cooloff = false;
            setTimeout(fetch_next, 15000);
            return;
        }

        var cur = queue.pop();
        API.chatLog("[PYE] Fetching playlist "+(totalQueue-queue.length)+" of "+totalQueue);

        function fail(){
            API.chatLog("[PYE] Could not fetch playlist id:"+cur+"! Aborting.");
            return;
        }
        function success(data){
            if (!data.status == "ok"){
                API.chatLog("[PYE] Could not fetch playlist id:"+cur+"! Status: "+data.status+". Aborting.");
                return;
            }
            playlists[cur].items = data.data;
            setTimeout(fetch_next, 1000);
        }

        $.ajax({
            url: "https://plug.dj/_/playlists/"+cur+"/media",
            contentType: "application/json",
            dataType: "json",
            type: "GET",
            fail: fail,
            success: success
        });
    }
    for (var i in playlists){
        queue.push(i);
    }
    totalQueue = queue.length;
    fetch_next();
}

function get_playlist_listing(){
    API.chatLog("[PYE] Step 2: Fetch playlist listing");

    //Define the handler functions.
    function ajax_success(data){
        if (data.status != "ok"){
            API.chatLog("[PYE] Could not get playlist listing! Status: "+data.status, true);
            return;
        }
        var body = data.data;
        API.chatLog("[PYE] Parsing listing.");

        for (var i=0;i<body.length;i++){
            playlists[body[i].id] = {
                name: body[i].name
            };
        }

        setTimeout(get_playlists);
    }

    function ajax_error(jqXHR, textStatus, errorThrown){
        API.chatLog("[PYE] Could not fetch the playlists object!", true);
        API.chatLog("[PYE] Error: "+String(errorThrown), true);
    }

    //Make the AJAX call.
    $.ajax({
        url: "https://plug.dj/_/playlists",
        contentType: "application/json",
        dataType: "json",
        type: "GET",
        fail: ajax_error,
        success: ajax_success
    });
}

function save_json(obj){
    API.chatLog("[PYE] Step 5: Saving playlist file.");
    var blob = new Blob(
        [JSON.stringify(obj)],
        {
            type: "application/json;charset=utf-8"
        }
    );
    saveAs(blob, "PLUG_PLAYLISTS.json");
    API.chatLog("[PYE] Done! You should have downloaded PLUG_PLAYLISTS.json by now.", true);
}
setTimeout(check_for_api, 50);<|endoftext|>


<commit_before>define([
    'underscore',
    'jquery',
    'oroui/js/app/components/base/component',
], function(_, $, BaseComponent) {
    'use strict';

    var CreateOrSelectChoiceComponent =  BaseComponent.extend({

        MODE_CREATE: 'create',
        MODE_VIEW: 'view',

        requiredOptions: [
            'modeSelector',
            'newEntitySelector',
            'existingEntitySelector',
            'existingEntityInputSelector',
            '_sourceElement',
        ],

        $el: null,
        $mode: null,
        $newEntity: null,
        $existingEntity: null,
        $dialog: null,

        updateDialogPositionCb: null,

        initialize: function(options) {
            var missingProperties = _.filter(this.requiredOptions, _.negate(_.bind(options.hasOwnProperty, options)));
            if (missingProperties.length) {
                throw new Error(
                    'Following properties are required but weren\'t passed: ' +
                    missingProperties.join(', ') +
                    '.'
                );
            }

            this.updateDialogPositionCb = _.bind(this._updateDialogPosition, this);

            this.$el = options._sourceElement;
            this.$mode = this.$el.find(options.modeSelector);
            this.$newEntity = this.$el.find(options.newEntitySelector);
            this.$existingEntity = this.$el.find(options.existingEntitySelector);
            this.$dialog = this.$el.closest('.ui-dialog');

            this.$existingEntity.on('change', _.bind(this._onEntityChange, this));
            this.$mode.on('change', _.bind(this._updateNewEntityVisibility, this));
            this.$mode.on('change', this.updateDialogPositionCb);

            this._onEntityChange({val: $(options.existingEntityInputSelector).val()});
        },

        _onEntityChange: function(e) {
            var mode = e.val ? this.MODE_VIEW : this.MODE_CREATE;
            this._setMode(mode);
        },

        _updateDialogPosition: function() {
            var maxHeight = $(window).height();
            var dialogHeight = this.$dialog.height();
            var dialogBottom = dialogHeight + this.$dialog.position.top;

            if (dialogBottom <= maxHeight) {
                return;
            }

            var top = Math.max(0, (maxHeight - dialogHeight) / 2);
            this.$dialog.css('top', top + 'px');
        },

        _updateNewEntityVisibility: function() {
            if (this._isInCreateMode()) {
                this.$newEntity.show();
            } else {
                this.$newEntity.hide();
            }
        },

        _setMode: function(mode) {
            if (this.$mode.val() === mode) {
                return;
            }

            this.$mode.val(mode).change();
        },

        _isInCreateMode: function() {
            return this.$mode.val() === this.MODE_CREATE;
        }
    });

    return CreateOrSelectChoiceComponent;
});
<commit_msg>CRM-3808: Finish PR<commit_after>define([
    'underscore',
    'jquery',
    'oroui/js/app/components/base/component',
], function(_, $, BaseComponent) {
    'use strict';

    var CreateOrSelectChoiceComponent =  BaseComponent.extend({

        MODE_CREATE: 'create',
        MODE_VIEW: 'view',

        requiredOptions: [
            'modeSelector',
            'newEntitySelector',
            'existingEntitySelector',
            'existingEntityInputSelector',
            '_sourceElement',
        ],

        $el: null,
        $mode: null,
        $newEntity: null,
        $existingEntity: null,
        $dialog: null,

        initialize: function(options) {
            var missingProperties = _.filter(this.requiredOptions, _.negate(_.bind(options.hasOwnProperty, options)));
            if (missingProperties.length) {
                throw new Error(
                    'Following properties are required but weren\'t passed: ' +
                    missingProperties.join(', ') +
                    '.'
                );
            }

            this.$el = options._sourceElement;
            this.$mode = this.$el.find(options.modeSelector);
            this.$newEntity = this.$el.find(options.newEntitySelector);
            this.$existingEntity = this.$el.find(options.existingEntitySelector);
            this.$dialog = this.$el.closest('.ui-dialog');
            this.$dialog.css('top', 0);

            this.$existingEntity.on('change', _.bind(this._onEntityChange, this));
            this.$mode.on('change', _.bind(this._updateNewEntityVisibility, this));

            this._onEntityChange({val: $(options.existingEntityInputSelector).val()});
        },

        _onEntityChange: function(e) {
            var mode = e.val ? this.MODE_VIEW : this.MODE_CREATE;
            this._setMode(mode);
        },

        _updateNewEntityVisibility: function() {
            if (this._isInCreateMode()) {
                this.$newEntity.show();
            } else {
                this.$newEntity.hide();
            }
        },

        _setMode: function(mode) {
            if (this.$mode.val() === mode) {
                return;
            }

            this.$mode.val(mode).change();
        },

        _isInCreateMode: function() {
            return this.$mode.val() === this.MODE_CREATE;
        }
    });

    return CreateOrSelectChoiceComponent;
});
<|endoftext|>


<commit_before>
import React from 'react';
import R from 'ramda';
import EditorMetaService from '../../../../../../services/EditorMetaService';
import { Operator, getSupportedOperators } from './Operator';
import PropertyValue from './PropertyValue';

const editorMetaService = EditorMetaService.instance;

const isValueType = (value) => R.isArrayLike(value) || typeof (value) !== 'object';

let BinaryPredicate = ({ onValueUpdate, onOpUpdate, op, meta, value }) => (

    <Operator onUpdate={onOpUpdate} supportedOperators={getSupportedOperators(meta) } selectedOp={op} />
    <PropertyValue {...{ meta, value, onUpdate: onValueUpdate, op }} />

);

let ShortPredicate = ({ meta, mutate, value }) => {
  return (
    <BinaryPredicate
      onValueUpdate={mutate.updateValue}
      onOpUpdate={selectedOp => {
        if (selectedOp === '$eq') return;
        mutate.updateValue({
          [selectedOp]: meta.multipleValues && selectedOp === '$in' ? [] : mutate.getValue(),
          ...(meta.compare ? { $compare: meta.compare } : {}),
        });
      }}
      op = "$eq" {...{ value, meta } }
    />
  );
};

let ComplexPredicate = ({ predicate, mutate, property, meta }) => {
  return (

{
      R.flatten(R.toPairs(predicate)
        .filter(([key]) => key[0] === '$')
        .filter(([op]) => op !== '$compare')
        .map(([op, value]) =>
          (isValueType(value)) ?
            <BinaryPredicate key={op}
              onOpUpdate={selectedOp => {
                if (selectedOp === '$eq') mutate.updateValue(mutate.in(op).getValue());
                else mutate.in(op).updateKey(selectedOp);
              } }
              onValueUpdate={mutate.in(op).updateValue} {...{ value, op, meta }}
            />
            : <PropertyPredicate predicate={value} mutate={mutate.in(op) } property={property} />)
      )
    }

  );
};

let PropertyPredicate = ({ predicate, mutate, property }) => {
  const meta = editorMetaService.getFieldMeta(property);
  return (typeof (predicate) !== 'object') ?
    <ShortPredicate value={predicate} {...{ meta, mutate } } /> :
    <ComplexPredicate {...{ predicate, mutate, property, meta }} />;
};
export default PropertyPredicate;
<commit_msg>- small bug fix<commit_after>
import React from 'react';
import R from 'ramda';
import EditorMetaService from '../../../../../../services/EditorMetaService';
import { Operator, getSupportedOperators } from './Operator';
import PropertyValue from './PropertyValue';

const editorMetaService = EditorMetaService.instance;

const isValueType = (value) => R.isArrayLike(value) || typeof (value) !== 'object';

let BinaryPredicate = ({ onValueUpdate, onOpUpdate, op, meta, value }) => (

    <Operator onUpdate={onOpUpdate} supportedOperators={getSupportedOperators(meta) } selectedOp={op} />
    <PropertyValue {...{ meta, value, onUpdate: onValueUpdate, op }} />

);

let ShortPredicate = ({ meta, mutate, value }) => {
  return (
    <BinaryPredicate
      onValueUpdate={mutate.updateValue}
      onOpUpdate={selectedOp => {
        if (selectedOp === '$eq') return;
        mutate.updateValue({
          [selectedOp]: meta.multipleValues && selectedOp === '$in' ? [mutate.getValue()] : mutate.getValue(),
          ...(meta.compare ? { $compare: meta.compare } : {}),
        });
      }}
      op = "$eq"
      {...{ value, meta } }
    />
  );
};

let ComplexPredicate = ({ predicate, mutate, property, meta }) => {
  return (

{
      R.flatten(R.toPairs(predicate)
        .filter(([key]) => key[0] === '$')
        .filter(([op]) => op !== '$compare')
        .map(([op, value]) =>
          (isValueType(value)) ?
            <BinaryPredicate key={op}
              onOpUpdate={selectedOp => {
                if (selectedOp === '$eq') mutate.updateValue(mutate.in(op).getValue());
                else mutate.in(op).updateKey(selectedOp);
              } }
              onValueUpdate={mutate.in(op).updateValue} {...{ value, op, meta }}
            />
            : <PropertyPredicate predicate={value} mutate={mutate.in(op) } property={property} />)
      )
    }

  );
};

let PropertyPredicate = ({ predicate, mutate, property }) => {
  const meta = editorMetaService.getFieldMeta(property);
  return (typeof (predicate) !== 'object') ?
    <ShortPredicate value={predicate} {...{ meta, mutate } } /> :
    <ComplexPredicate {...{ predicate, mutate, property, meta }} />;
};
export default PropertyPredicate;
<|endoftext|>


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

var AWS = require('aws-sdk'),
    cloudwatchlogs = new AWS.CloudWatchLogs(),
    lynx = require('lynx'),
    lynxInstance = undefined;

function metrics() {
  if (!lynxInstance) {
    lynxInstance = new lynx(process.env.SAWMILL_STATSD_URL, 8125, {on_error: function(a, b) {
      console.log(a, b);
    }});
  }
  return lynxInstance;
}

function bucket(name) {
  return [process.env.SAWMILL_STATSD_PREFIX, name].join('.');
}

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

function run(nextToken) {
  var params = {
    logGroupName: '/var/log/haproxy.log',
    logStreamName: 'loadbalancers',
    nextToken: nextToken
  };

  process.stdout.write('chop!');
  cloudwatchlogs.getLogEvents(params, function(err, log) {
    if(err) {
      console.error('saw failure!', err);
    }

    if (!log) return wait(nextToken, run);
    if (!nextToken) return wait(log.nextForwardToken, run);

    var requestCount = 0;

    var statusCounts = {
    };

    //reset the counts
    _.keys(statusCounts).forEach(k) {
      statusCounts[k] = 0;
    }

    function incStatusCode(code) {
      if(!statusCounts[code]) {
        statusCounts[code] = 0;
      }

      statusCounts[code] = statusCounts[code] + 1;
    }

    log.events.forEach(function(event) {
      process.stdout.write('z');
      var splits = event.message.split(' ');
      //find the haproxy index:
      var haproxyindex = -1;
      for(var i=0; i<splits.length; ++i) {
        if(splits[i].substr(0, 7) === 'haproxy') {
          haproxyindex = i;
          break;
        }
      }

      if(haproxyindex === -1) {
        return;
      }

      requestCount++;

      var statuscode = splits[haproxyindex + 6],
      totalTimes = splits[haproxyindex + 5],
      haproxy = splits[haproxyindex],
      nodeserver = splits[haproxyindex + 4],
      connections = splits[haproxyindex + 11];

      //console.log('status', { statuscode: statuscode, haproxy: haproxy, nodeserver: nodeserver, connections: connections, splits: splits });

      haproxy = haproxy.replace('[', '.').replace(']', '').replace(':', '');

      if (isNumber(statuscode)) {
        incStatusCode(['statuscode', statuscode, 'all'].join('.'));
        incStatusCode(['statuscode', statuscode, haproxy].join('.'));
        incStatusCode(['statuscode', statuscode[0], 'all'].join('.'));
        process.stdout.write('buzz!');
      }

      if (connections && connections.length) {
        var frontendConnections = connections.split('/')[1],
          backendConnections = connections.split('/')[2],
                             frontendConnectionsBucket = bucket('connections.frontend.all'),
                             backendConnectionsBucket = bucket(['connections.backend', nodeserver.replace('node-servers/', '')].join('.'));
        metrics().gauge(frontendConnectionsBucket, +frontendConnections);
        metrics().gauge(backendConnectionsBucket, +backendConnections);
        process.stdout.write('buzz!');
      }

      var totalTimes = totalTimes.split('/');
      if (totalTimes && totalTimes.length === 5) {
        var tq = totalTimes[0];
        var tr = totalTimes[3];
        var tt = totalTimes[4];
        var payload = {};
        payload[bucket('totaltime.request')] = tq + '|ms';
        payload[bucket('totaltime.response')] = tr + '|ms';
        payload[bucket('totaltime.total')] = tt + '|ms';
        metrics().send(payload);
        process.stdout.write('buzz!');
      }

    });

    var requestsPerSecond = log.events.length / 10;
    metrics().gauge(bucket('request.all'), requestsPerSecond);
    _.keys(statusCounts).forEach(k) {
      metrics().gauge(bucket(k), statusCounts[k]);
      if(statusCounts[k] === 0) {
        delete statusCounts[k];
      }
    }

    console.log('');
    wait(log.nextForwardToken, run);
  });
}

function wait(token, cb) {
  setTimeout(function() {
    cb(token);
  }, 10000);
}

console.log('starting the saws...');
return run();
<commit_msg>converted status codes to use guages (fixed syntax)<commit_after>#!/usr/local/bin/node

var AWS = require('aws-sdk'),
  cloudwatchlogs = new AWS.CloudWatchLogs(),
  lynx = require('lynx'),
  lynxInstance = undefined;

function metrics() {
  if (!lynxInstance) {
    lynxInstance = new lynx(process.env.SAWMILL_STATSD_URL, 8125, {
      on_error: function(a, b) {
        console.log(a, b);
      }
    });
  }
  return lynxInstance;
}

function bucket(name) {
  return [process.env.SAWMILL_STATSD_PREFIX, name].join('.');
}

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

function run(nextToken) {
  var params = {
    logGroupName: '/var/log/haproxy.log',
    logStreamName: 'loadbalancers',
    nextToken: nextToken
  };

  process.stdout.write('chop!');
  cloudwatchlogs.getLogEvents(params, function(err, log) {
    if (err) {
      console.error('saw failure!', err);
    }

    if (!log) return wait(nextToken, run);
    if (!nextToken) return wait(log.nextForwardToken, run);

    var requestCount = 0;

    var statusCounts = {};

    //reset the counts
    _.keys(statusCounts).forEach(function(k) {
      statusCounts[k] = 0;
    });

    function incStatusCode(code) {
      if (!statusCounts[code]) {
        statusCounts[code] = 0;
      }

      statusCounts[code] = statusCounts[code] + 1;
    }

    log.events.forEach(function(event) {
      process.stdout.write('z');
      var splits = event.message.split(' ');
      //find the haproxy index:
      var haproxyindex = -1;
      for (var i = 0; i < splits.length; ++i) {
        if (splits[i].substr(0, 7) === 'haproxy') {
          haproxyindex = i;
          break;
        }
      }

      if (haproxyindex === -1) {
        return;
      }

      requestCount++;

      var statuscode = splits[haproxyindex + 6],
        totalTimes = splits[haproxyindex + 5],
        haproxy = splits[haproxyindex],
        nodeserver = splits[haproxyindex + 4],
        connections = splits[haproxyindex + 11];

      //console.log('status', { statuscode: statuscode, haproxy: haproxy, nodeserver: nodeserver, connections: connections, splits: splits });

      haproxy = haproxy.replace('[', '.').replace(']', '').replace(':', '');

      if (isNumber(statuscode)) {
        incStatusCode(['statuscode', statuscode, 'all'].join('.'));
        incStatusCode(['statuscode', statuscode, haproxy].join('.'));
        incStatusCode(['statuscode', statuscode[0], 'all'].join('.'));
        process.stdout.write('buzz!');
      }

      if (connections && connections.length) {
        var frontendConnections = connections.split('/')[1],
          backendConnections = connections.split('/')[2],
          frontendConnectionsBucket = bucket('connections.frontend.all'),
          backendConnectionsBucket = bucket(['connections.backend', nodeserver.replace('node-servers/', '')].join('.'));
        metrics().gauge(frontendConnectionsBucket, +frontendConnections);
        metrics().gauge(backendConnectionsBucket, +backendConnections);
        process.stdout.write('buzz!');
      }

      var totalTimes = totalTimes.split('/');
      if (totalTimes && totalTimes.length === 5) {
        var tq = totalTimes[0];
        var tr = totalTimes[3];
        var tt = totalTimes[4];
        var payload = {};
        payload[bucket('totaltime.request')] = tq + '|ms';
        payload[bucket('totaltime.response')] = tr + '|ms';
        payload[bucket('totaltime.total')] = tt + '|ms';
        metrics().send(payload);
        process.stdout.write('buzz!');
      }

    });

    var requestsPerSecond = log.events.length / 10;
    metrics().gauge(bucket('request.all'), requestsPerSecond);
    _.keys(statusCounts).forEach(function(k) {
      metrics().gauge(bucket(k), statusCounts[k]);
      if (statusCounts[k] === 0) {
        delete statusCounts[k];
      }
    });

    console.log('');
    wait(log.nextForwardToken, run);
  });
}

function wait(token, cb) {
  setTimeout(function() {
    cb(token);
  }, 10000);
}

console.log('starting the saws...');
return run();
<|endoftext|>