<commit_before>module.exports = function (babel) {
  var t = babel.types;

  var path = require('path');

  var UmdFormatter = require('./../babel-core/lib/babel/transformation/modules/umd');

  function getImportPath(file, relativeImportPath) {
    var filename = file.opts.filename;
    var filePath = filename.replace(/[^\/]+$/, '');
    var result = path.join(filePath, relativeImportPath);
    return result;
  }

  function getImportModuleName(file, importPath) {
    var importedModulePath = getImportPath(file, importPath);

    // There should be a better way
    var importedModuleFile = t.cloneDeep(file);
    importedModuleFile.opts = t.cloneDeep(file.opts);
    importedModuleFile.opts.filename = importedModuleFile.opts.filenameRelative = importedModulePath + '.js';
    var result = new UmdFormatter(importedModuleFile).getModuleName();
    return result;
  }

  function createTransformedExpression(importedModuleNode, moduleNameNode) {
    var globalIdentifier = t.identifier('global');
    if (!moduleNameNode) {
      moduleNameNode = importedModuleNode;
    }

    // typeof global.define === 'function' && global.define.amd
    var amdTest = t.logicalExpression('&&',
      t.binaryExpression('===',
        t.unaryExpression('typeof', t.memberExpression(
          globalIdentifier,
          t.identifier('define')
        )),
        t.literal('function')
      ),
      t.memberExpression(
        t.memberExpression(
          globalIdentifier,
          t.identifier('define')
        ),
        t.identifier('amd')
      )
    );

    // global.require(['localforageSerializer'], resolve, reject);
    var amdRequire = t.expressionStatement(
      t.callExpression(
        t.memberExpression(
          globalIdentifier,
          t.identifier('require')
        ),
        [
          t.arrayExpression([moduleNameNode]),
          t.identifier('resolve'),
          t.identifier('reject')
        ]
      )
    );

    // typeof module !== 'undefined' && module.exports && typeof require !== 'undefined'
    var commonJSTest = t.logicalExpression('&&',
      t.binaryExpression('!==',
        t.unaryExpression('typeof', t.identifier('module')),
        t.literal('undefined')
      ),
      t.logicalExpression('&&',
        t.memberExpression(
          t.identifier('module'),
          t.identifier('exports')
        ),
        t.binaryExpression('!==',
          t.unaryExpression('typeof', t.identifier('require')),
          t.literal('undefined')
        )
      )
    );

    // typeof module !== 'undefined' && module.component && global.require && global.require.loader === 'component'
    var componentTest = t.logicalExpression('&&',
      t.binaryExpression('!==',
        t.unaryExpression('typeof', t.identifier('module')),
        t.literal('undefined')
      ),
      t.logicalExpression('&&',
        t.memberExpression(
          t.identifier('module'),
          t.identifier('component')
        ),
        t.logicalExpression('&&',
          t.memberExpression(
            globalIdentifier,
            t.identifier('require')
          ),
          t.binaryExpression('===',
            t.memberExpression(
              t.memberExpression(
                globalIdentifier,
                t.identifier('require')
              ),
              t.identifier('loader')
            ),
            t.literal('component')
          )
        )
      )
    );

    // resolve(require('./../utils/serializer'));
    var commonJSRequire = t.expressionStatement(
      t.callExpression(
        t.identifier('resolve'), [
          t.callExpression(
            t.identifier('require'),
            [importedModuleNode]
          )
        ]
      )
    );

    // resolve(global.localforageSerializer);
    var globalMemberExpression = t.memberExpression(
      globalIdentifier,
      moduleNameNode
    );
    globalMemberExpression.computed = true;
    var globalRequire = t.expressionStatement(
      t.callExpression(
        t.identifier('resolve'), [globalMemberExpression]
      )
    );

    var commonJSOrComponentTest = t.logicalExpression('||', commonJSTest, componentTest);

    var umdTests = t.ifStatement(amdTest,
      t.blockStatement([amdRequire]),
      t.ifStatement(commonJSOrComponentTest,
        t.blockStatement([commonJSRequire]),
        t.blockStatement([globalRequire])
      )
    );

    var newPromiseExpression = t.newExpression(t.identifier('Promise'), [
      t.functionExpression(null,
        [t.identifier('resolve'), t.identifier('reject')],
        t.blockStatement([
          t.variableDeclaration('var', [t.variableDeclarator(globalIdentifier, t.identifier('window'))]),
          umdTests
        ])
      )
    ]);
    return newPromiseExpression;
  }

  return new babel.Transformer('system-import-transformer', {
    CallExpression: function (node, parent, scope, file) {
      if (this.get('callee').matchesPattern('System.import')) {
        var params = this.get('arguments');
        if (params.length && params[0].isLiteral()) {
          var param = params[0];
          var importedModuleLiteral = t.literal(param.node.value);

          var moduleName = getImportModuleName(file, importedModuleLiteral.value);
          var moduleNameLiteral = t.literal(moduleName);

          return t.expressionStatement(createTransformedExpression(importedModuleLiteral, moduleNameLiteral));
        }
      }
    }
  });
};
<commit_msg>feat: add support for explicit CommonJS & AMD module import<commit_after>module.exports = function (babel) {
  var t = babel.types;

  var path = require('path');

  var UmdFormatter = require('./../babel-core/lib/babel/transformation/modules/umd');

  function getImportPath(file, relativeImportPath) {
    var filename = file.opts.filename;
    var filePath = filename.replace(/[^\/]+$/, '');
    var result = path.join(filePath, relativeImportPath);
    return result;
  }

  function getImportModuleName(file, importPath) {
    var importedModulePath = getImportPath(file, importPath);

    // There should be a better way
    var importedModuleFile = t.cloneDeep(file);
    importedModuleFile.opts = t.cloneDeep(file.opts);
    importedModuleFile.opts.filename = importedModuleFile.opts.filenameRelative = importedModulePath + '.js';
    var result = new UmdFormatter(importedModuleFile).getModuleName();
    return result;
  }

  function createTransformedExpression(importedModuleNode, moduleNameNode, fileOpts) {
    var globalIdentifier = t.identifier('global');
    var globalVarDeclaration = t.variableDeclaration('var', [t.variableDeclarator(globalIdentifier, t.identifier('window'))]);
    if (!moduleNameNode) {
      moduleNameNode = importedModuleNode;
    }

    // typeof global.define === 'function' && global.define.amd
    var amdTest = t.logicalExpression('&&',
      t.binaryExpression('===',
        t.unaryExpression('typeof', t.memberExpression(
          globalIdentifier,
          t.identifier('define')
        )),
        t.literal('function')
      ),
      t.memberExpression(
        t.memberExpression(
          globalIdentifier,
          t.identifier('define')
        ),
        t.identifier('amd')
      )
    );

    // global.require(['localforageSerializer'], resolve, reject);
    var amdRequire = t.expressionStatement(
      t.callExpression(
        t.memberExpression(
          globalIdentifier,
          t.identifier('require')
        ),
        [
          t.arrayExpression([moduleNameNode]),
          t.identifier('resolve'),
          t.identifier('reject')
        ]
      )
    );

    // typeof module !== 'undefined' && module.exports && typeof require !== 'undefined'
    var commonJSTest = t.logicalExpression('&&',
      t.binaryExpression('!==',
        t.unaryExpression('typeof', t.identifier('module')),
        t.literal('undefined')
      ),
      t.logicalExpression('&&',
        t.memberExpression(
          t.identifier('module'),
          t.identifier('exports')
        ),
        t.binaryExpression('!==',
          t.unaryExpression('typeof', t.identifier('require')),
          t.literal('undefined')
        )
      )
    );

    // typeof module !== 'undefined' && module.component && global.require && global.require.loader === 'component'
    var componentTest = t.logicalExpression('&&',
      t.binaryExpression('!==',
        t.unaryExpression('typeof', t.identifier('module')),
        t.literal('undefined')
      ),
      t.logicalExpression('&&',
        t.memberExpression(
          t.identifier('module'),
          t.identifier('component')
        ),
        t.logicalExpression('&&',
          t.memberExpression(
            globalIdentifier,
            t.identifier('require')
          ),
          t.binaryExpression('===',
            t.memberExpression(
              t.memberExpression(
                globalIdentifier,
                t.identifier('require')
              ),
              t.identifier('loader')
            ),
            t.literal('component')
          )
        )
      )
    );

    // resolve(require('./../utils/serializer'));
    var commonJSRequire = t.expressionStatement(
      t.callExpression(
        t.identifier('resolve'), [
          t.callExpression(
            t.identifier('require'),
            [importedModuleNode]
          )
        ]
      )
    );

    // resolve(global.localforageSerializer);
    var globalMemberExpression = t.memberExpression(
      globalIdentifier,
      moduleNameNode
    );
    globalMemberExpression.computed = true;
    var globalRequire = t.expressionStatement(
      t.callExpression(
        t.identifier('resolve'), [globalMemberExpression]
      )
    );

    var commonJSOrComponentTest = t.logicalExpression('||', commonJSTest, componentTest);

    var umdRequire = t.ifStatement(amdTest,
      t.blockStatement([amdRequire]),
      t.ifStatement(commonJSOrComponentTest,
        t.blockStatement([commonJSRequire]),
        t.blockStatement([globalRequire])
      )
    );

    var moduleImportExpressions = [globalVarDeclaration, umdRequire];
    if (fileOpts.modules === 'amd') {
      moduleImportExpressions = [globalVarDeclaration, amdRequire];
    } else if (fileOpts.modules === 'common') {
      moduleImportExpressions = [commonJSRequire];
    }

    var newPromiseExpression = t.newExpression(t.identifier('Promise'), [
      t.functionExpression(null,
        [t.identifier('resolve'), t.identifier('reject')],
        t.blockStatement(moduleImportExpressions)
      )
    ]);
    return newPromiseExpression;
  }

  return new babel.Transformer('system-import-transformer', {
    CallExpression: function (node, parent, scope, file) {
      if (this.get('callee').matchesPattern('System.import')) {
        var params = this.get('arguments');
        if (params.length && params[0].isLiteral()) {
          var param = params[0];
          var importedModuleLiteral = t.literal(param.node.value);

          var moduleName = getImportModuleName(file, importedModuleLiteral.value);
          var moduleNameLiteral = t.literal(moduleName);

          var transformedExpression = createTransformedExpression(importedModuleLiteral, moduleNameLiteral, file.opts);
          if (transformedExpression) {
            return t.expressionStatement(transformedExpression);
          }
        }
      }
    }
  });
};
<|endoftext|>


<commit_before>
var Game     = require('./models/game');
var Facility = require('./models/facility');
var User = require('./models/user');
var Court = require('./models/court');

module.exports = function(app) {

	// server routes ===========================================================
	// handle things like api calls
	// authentication routes

	// frontend routes =========================================================
	// route to handle all angular requests

	app.get('/', function(req, res) {
		res.sendfile('./public/index.html');
	});

//////////////////////////////////////////////////////////////////
////GAMES/////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////

	app.get('/games',function(req,res){
		Game.find(function(err, games) {
			if (err)
				res.send(err);
			res.json(games);
		});
	});

	app.get('/games/:game_id',function(req, res) {
		Game.findById(req.params.game_id, function(err, game) {
			if (err)
				res.send(err);
			res.json(game);
		});
	});

    app.put('/games/:name/:location/:userId/:start/:end/:people/:courtId',function(req,res){

		var game = new Game();
		game.name = req.params.name;
        game.location = req.params.location;
        game.ownerId = req.params.ownerId;
        game.start = req.params.start;
        game.end = req.params.end;
        game.courtId = req.params.courtId;

		// res.json({message:game.name});

		game.save(function(err){
			if(err)
				res.send(err);
			res.json({message: 'Game created'});
		});
	});

    app.delete('/games/:game_id',function(req,res){
        Game.remove({
 			_id: req.params.game_id
 		}, function(err, game) {
 			if (err)
 				res.send(err);
 			res.json({ message: 'Successfully deleted' });
 		});
    });

//////////////////////////////////////////////////////////////////
////FACILITIES////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////

	app.get('/facilities',function(req,res){
		Facility.find(function(err,facilities){
			if(err)
				res.send(err);
			res.json(facilities);
		});
	});

    app.get('/facilites/:id',function(req,res){
		Facility.find({id: req.params.id},function(err,facility){
			if (err)
				res.send(err);
			res.json(facility);
		});
	});

	app.put('/facilities/:name/:hours/:phone/:id/:image/:url',function(req,res){
        var facility = new Facility();
        facility.name = req.params.name;
        facility.hours = req.params.hours;
        facility.phone = req.params.phone;
        facility.id = req.params.id;
        facility.image = req.params.image;
        facility.url = req.params.url;

        facility.save(function(err){
           if(err)
               res.send(err);
            res.json({message: 'Facility created'});
        });
	});

    app.delete('/facilities/:facility_id',function(req,res){
        Facility.remove({
 			_id: req.params.facility_id
 		}, function(err, user) {
 			if (err)
 				res.send(err);

 			res.json({ message: 'Successfully deleted' });
 		});
    });

//////////////////////////////////////////////////////////////////
////USERS/////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////

	app.get('/users',function(req,res){
        User.find(function(err,users){
			if(err)
				res.send(err);
			res.json(users);
		});
	});

	app.get('/users/:user_id',function(req,res){
		User.find({fbUserId: req.params.user_id},function(err,user){
			if (err)
				res.send(err);
			res.json(user);
		});
	});

	app.post('/users/update/:fbUserId/:email/:phone',function(req,res){
 		User.find({fbUserId: req.params.fbUserId}, function(err, user) {

 			if (err)
 				res.send(err);

 			user.email = req.body.email;
 			user.phone = req.body.phone;
 			user.save(function(err) {
 				if (err)
 					res.send(err);

 				res.json({ message: 'User updated!' });
 			});

 		});
 	});

		/*User.remove({
 			_id: req.params.fbUserId
 		}, function(err, user) {
 			if (err)
 				res.send(err);
 		});

		var user = new User();
        user.firstName = req.params.firstName;
        user.lastName = req.params.lastName;
        user.email = req.params.email;
        user.phone = req.params.phone;
        user.picture = req.params.picture;
        user.loggedIn = req.params.loggedIn;
        user.fbUserId = req.params.fbUserId;

        user.save(function(err){
           if(err)
               res.send(err);
            res.json({message: 'User updated'});
        });*/

		/*User.update({ fbUserId: req.params.fbUserId},
		{
			$set: {
				email: req.params.email,
				phone: req.params.phone
			}
		},
		{ upsert: true }
		);
		res.json({message: 'User updated'});*/

    app.put('/users/:firstName/:lastName/:email/:phone/:picture/:loggedIn/:fbUserId',function(req,res){
        var user = new User();
        user.firstName = req.params.firstName;
        user.lastName = req.params.lastName;
        user.email = req.params.email;
        user.phone = req.params.phone;
        user.picture = req.params.picture;
        user.loggedIn = req.params.loggedIn;
        user.fbUserId = req.params.fbUserId;

        user.save(function(err){
           if(err)
               res.send(err);
            res.json({message: 'User created'});
        });
    });

    app.delete('/users/:user_id',function(req,res){
        User.remove({
 			_id: req.params.user_id
 		}, function(err, user) {
 			if (err)
 				res.send(err);

 			res.json({ message: 'Successfully deleted' });
 		});
    });

//////////////////////////////////////////////////////////////////
////COURTS/////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
    app.get('/courts',function(req,res){
      Court.find(function(err,courts){
			if(err)
				res.send(err);
			res.json(courts);
		});
	});

    app.get('/courts/:court_id',function(req,res){
		Court.findById(req.params.court_id,function(err,court){
			if (err)
				res.send(err);
			res.json(court);
		});
	});

    app.get('/courts/fac/:facId',function(req,res){
        Court.find({facId : req.params.facId},function(err,court){
			if (err)
				res.send(err);
			res.json(court);
		});
    });

    app.put('/courts/:name/:facId/:image',function(req,res){
        var court = new Court();
        court.name = req.params.name;
        court.facId = req.params.facId;
        court.image = req.params.image;

        court.save(function(err){
           if(err)
               res.send(err);
            res.json({message: 'Court created'});
        });
    });

    app.delete('/courts/:court_id',function(req,res){
        Court.remove({
 			_id: req.params.court_id
 		}, function(err, court) {
 			if (err)
 				res.send(err);

 			res.json({ message: 'Successfully deleted' });
 		});
    });

// app.get('/', function(req, res) {
// 	res.json({ message: 'hooray! welcome to our api!' });
// });

// // on routes that end in /bears
// // ----------------------------------------------------
// router.route('/bears')

// 	// create a bear (accessed at POST http://localhost:8080/bears)
// 	.post(function(req, res) {

// 		var bear = new Bear();		// create a new instance of the Bear model
// 		bear.name = req.body.name;  // set the bears name (comes from the request)

// 		bear.save(function(err) {
// 			if (err)
// 				res.send(err);

// 			res.json({ message: 'Bear created!' });
// 		});

// 	})

// 	// get all the bears (accessed at GET http://localhost:8080/api/bears)
// 	.get(function(req, res) {
// 		Bear.find(function(err, bears) {
// 			if (err)
// 				res.send(err);

// 			res.json(bears);
// 		});
// 	});

// // on routes that end in /bears/:bear_id
// // ----------------------------------------------------
// router.route('/bears/:bear_id')

// 	// get the bear with that id
// 	.get(function(req, res) {
// 		Bear.findById(req.params.bear_id, function(err, bear) {
// 			if (err)
// 				res.send(err);
// 			res.json(bear);
// 		});
// 	})

// 	// update the bear with this id
// 	.put(function(req, res) {
// 		Bear.findById(req.params.bear_id, function(err, bear) {

// 			if (err)
// 				res.send(err);

// 			bear.name = req.body.name;
// 			bear.save(function(err) {
// 				if (err)
// 					res.send(err);

// 				res.json({ message: 'Bear updated!' });
// 			});

// 		});
// 	})

// 	// delete the bear with this id
// 	.delete(function(req, res) {
// 		Bear.remove({
// 			_id: req.params.bear_id
// 		}, function(err, bear) {
// 			if (err)
// 				res.send(err);

// 			res.json({ message: 'Successfully deleted' });
// 		});
// 	});

};<commit_msg>fixed error<commit_after>
var Game     = require('./models/game');
var Facility = require('./models/facility');
var User = require('./models/user');
var Court = require('./models/court');

module.exports = function(app) {

	// server routes ===========================================================
	// handle things like api calls
	// authentication routes

	// frontend routes =========================================================
	// route to handle all angular requests

	app.get('/', function(req, res) {
		res.sendfile('./public/index.html');
	});

//////////////////////////////////////////////////////////////////
////GAMES/////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////

	app.get('/games',function(req,res){
		Game.find(function(err, games) {
			if (err)
				res.send(err);
			res.json(games);
		});
	});

	app.get('/games/:game_id',function(req, res) {
		Game.findById(req.params.game_id, function(err, game) {
			if (err)
				res.send(err);
			res.json(game);
		});
	});

    app.put('/games/:name/:location/:userId/:start/:end/:people/:courtId',function(req,res){

		var game = new Game();
		game.name = req.params.name;
        game.location = req.params.location;
        game.ownerId = req.params.ownerId;
        game.start = req.params.start;
        game.end = req.params.end;
        game.courtId = req.params.courtId;

		// res.json({message:game.name});

		game.save(function(err){
			if(err)
				res.send(err);
			res.json({message: 'Game created'});
		});
	});

    app.delete('/games/:game_id',function(req,res){
        Game.remove({
 			_id: req.params.game_id
 		}, function(err, game) {
 			if (err)
 				res.send(err);
 			res.json({ message: 'Successfully deleted' });
 		});
    });

//////////////////////////////////////////////////////////////////
////FACILITIES////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////

	app.get('/facilities',function(req,res){
		Facility.find(function(err,facilities){
			if(err)
				res.send(err);
			res.json(facilities);
		});
	});

    app.get('/facilites/:id',function(req,res){
		Facility.find({id: req.params.id},function(err,facility){
			if (err)
				res.send(err);
			res.json(facility);
		});
	});

	app.put('/facilities/:name/:hours/:phone/:id/:image/:url',function(req,res){
        var facility = new Facility();
        facility.name = req.params.name;
        facility.hours = req.params.hours;
        facility.phone = req.params.phone;
        facility.id = req.params.id;
        facility.image = req.params.image;
        facility.url = req.params.url;

        facility.save(function(err){
           if(err)
               res.send(err);
            res.json({message: 'Facility created'});
        });
	});

    app.delete('/facilities/:facility_id',function(req,res){
        Facility.remove({
 			_id: req.params.facility_id
 		}, function(err, user) {
 			if (err)
 				res.send(err);

 			res.json({ message: 'Successfully deleted' });
 		});
    });

//////////////////////////////////////////////////////////////////
////USERS/////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////

	app.get('/users',function(req,res){
        User.find(function(err,users){
			if(err)
				res.send(err);
			res.json(users);
		});
	});

	app.get('/users/:user_id',function(req,res){
		User.find({fbUserId: req.params.user_id},function(err,user){
			if (err)
				res.send(err);
			res.json(user);
		});
	});

	app.post('/users/update/:fbUserId/:email/:phone',function(req,res){
 		User.find({fbUserId: req.params.fbUserId}, function(err, user) {

 			if (err)
 				res.send('1'+err);

 			user.email = req.body.email;
 			user.phone = req.body.phone;
 			user.save(function(err) {
 				if (err)
 					res.send('2'+err);

 				res.json({ message: 'User updated!' });
 			});

 		});
 	});

		/*User.remove({
 			_id: req.params.fbUserId
 		}, function(err, user) {
 			if (err)
 				res.send(err);
 		});

		var user = new User();
        user.firstName = req.params.firstName;
        user.lastName = req.params.lastName;
        user.email = req.params.email;
        user.phone = req.params.phone;
        user.picture = req.params.picture;
        user.loggedIn = req.params.loggedIn;
        user.fbUserId = req.params.fbUserId;

        user.save(function(err){
           if(err)
               res.send(err);
            res.json({message: 'User updated'});
        });*/

		/*User.update({ fbUserId: req.params.fbUserId},
		{
			$set: {
				email: req.params.email,
				phone: req.params.phone
			}
		},
		{ upsert: true }
		);
		res.json({message: 'User updated'});*/

    app.put('/users/:firstName/:lastName/:email/:phone/:picture/:loggedIn/:fbUserId',function(req,res){
        var user = new User();
        user.firstName = req.params.firstName;
        user.lastName = req.params.lastName;
        user.email = req.params.email;
        user.phone = req.params.phone;
        user.picture = req.params.picture;
        user.loggedIn = req.params.loggedIn;
        user.fbUserId = req.params.fbUserId;

        user.save(function(err){
           if(err)
               res.send(err);
            res.json({message: 'User created'});
        });
    });

    app.delete('/users/:user_id',function(req,res){
        User.remove({
 			_id: req.params.user_id
 		}, function(err, user) {
 			if (err)
 				res.send(err);

 			res.json({ message: 'Successfully deleted' });
 		});
    });

//////////////////////////////////////////////////////////////////
////COURTS/////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
    app.get('/courts',function(req,res){
      Court.find(function(err,courts){
			if(err)
				res.send(err);
			res.json(courts);
		});
	});

    app.get('/courts/:court_id',function(req,res){
		Court.findById(req.params.court_id,function(err,court){
			if (err)
				res.send(err);
			res.json(court);
		});
	});

    app.get('/courts/fac/:facId',function(req,res){
        Court.find({facId : req.params.facId},function(err,court){
			if (err)
				res.send(err);
			res.json(court);
		});
    });

    app.put('/courts/:name/:facId/:image',function(req,res){
        var court = new Court();
        court.name = req.params.name;
        court.facId = req.params.facId;
        court.image = req.params.image;

        court.save(function(err){
           if(err)
               res.send(err);
            res.json({message: 'Court created'});
        });
    });

    app.delete('/courts/:court_id',function(req,res){
        Court.remove({
 			_id: req.params.court_id
 		}, function(err, court) {
 			if (err)
 				res.send(err);

 			res.json({ message: 'Successfully deleted' });
 		});
    });

// app.get('/', function(req, res) {
// 	res.json({ message: 'hooray! welcome to our api!' });
// });

// // on routes that end in /bears
// // ----------------------------------------------------
// router.route('/bears')

// 	// create a bear (accessed at POST http://localhost:8080/bears)
// 	.post(function(req, res) {

// 		var bear = new Bear();		// create a new instance of the Bear model
// 		bear.name = req.body.name;  // set the bears name (comes from the request)

// 		bear.save(function(err) {
// 			if (err)
// 				res.send(err);

// 			res.json({ message: 'Bear created!' });
// 		});

// 	})

// 	// get all the bears (accessed at GET http://localhost:8080/api/bears)
// 	.get(function(req, res) {
// 		Bear.find(function(err, bears) {
// 			if (err)
// 				res.send(err);

// 			res.json(bears);
// 		});
// 	});

// // on routes that end in /bears/:bear_id
// // ----------------------------------------------------
// router.route('/bears/:bear_id')

// 	// get the bear with that id
// 	.get(function(req, res) {
// 		Bear.findById(req.params.bear_id, function(err, bear) {
// 			if (err)
// 				res.send(err);
// 			res.json(bear);
// 		});
// 	})

// 	// update the bear with this id
// 	.put(function(req, res) {
// 		Bear.findById(req.params.bear_id, function(err, bear) {

// 			if (err)
// 				res.send(err);

// 			bear.name = req.body.name;
// 			bear.save(function(err) {
// 				if (err)
// 					res.send(err);

// 				res.json({ message: 'Bear updated!' });
// 			});

// 		});
// 	})

// 	// delete the bear with this id
// 	.delete(function(req, res) {
// 		Bear.remove({
// 			_id: req.params.bear_id
// 		}, function(err, bear) {
// 			if (err)
// 				res.send(err);

// 			res.json({ message: 'Successfully deleted' });
// 		});
// 	});

};<|endoftext|>


<commit_before>var Todo = require('./models/todo');

function getTodos(res) {
    Todo.find(function (err, todos) {

        // if there is an error retrieving, send the error. nothing after res.send(err) will execute
        if (err) {
            res.send(err);
        }

        res.json(todos); // return all todos in JSON format
    });
};

module.exports = function (app) {

    // api ---------------------------------------------------------------------
    // get all todos
    app.get('/api/todos', function (req, res) {
        // use mongoose to get all todos in the database
        getTodos(res);
    });

    // create todo and send back all todos after creation
    app.post('/api/todos', function (req, res) {

        // create a todo, information comes from AJAX request from Angular
        Todo.create({
            text: req.body.text,
            done: false
        }, function (err, todo) {
            if (err)
                res.send(err);

            // get and return all the todos after you create another
            getTodos(res);
        });

    });

    // delete a todo
    app.delete('/api/todos/:todo_id', function (req, res) {
        Todo.remove({
            _id: req.params.todo_id
        }, function (err, todo) {
            if (err)
                res.send(err);

            getTodos(res);
        });
    });

    // application -------------------------------------------------------------
    app.get('*', function (req, res) {
        res.sendFile(__dirname + '/public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
    });
};
<commit_msg>Update routes.js<commit_after>var Todo = require('./models/todo');

if ('dev' == process.env.DEPLOY_ENV){
    Todo.remove({}, callback)
}

function getTodos(res) {
    Todo.find(function (err, todos) {

        // if there is an error retrieving, send the error. nothing after res.send(err) will execute
        if (err) {
            res.send(err);
        }

        res.json(todos); // return all todos in JSON format
    });
};

module.exports = function (app) {

    // api ---------------------------------------------------------------------
    // get all todos
    app.get('/api/todos', function (req, res) {
        // use mongoose to get all todos in the database
        getTodos(res);
    });

    // create todo and send back all todos after creation
    app.post('/api/todos', function (req, res) {

        // create a todo, information comes from AJAX request from Angular
        Todo.create({
            text: req.body.text,
            done: false
        }, function (err, todo) {
            if (err)
                res.send(err);

            // get and return all the todos after you create another
            getTodos(res);
        });

    });

    // delete a todo
    app.delete('/api/todos/:todo_id', function (req, res) {
        Todo.remove({
            _id: req.params.todo_id
        }, function (err, todo) {
            if (err)
                res.send(err);

            getTodos(res);
        });
    });

    // application -------------------------------------------------------------
    app.get('*', function (req, res) {
        res.sendFile(__dirname + '/public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
    });
};
<|endoftext|>


<commit_before>//add two buffers,
//putting least significant at left will be simplest.
//iterate over buffers from lsb to msb
//and add each byte & 0xff, carrying overflow.

var fromInt = exports.fromInt = function (int, length) {
  var b = new Buffer(Math.max(length || 0, 4))
  b.fill()
  b.writeInt32LE(int, 0)
  return b
}

var isZero = exports.isZero = function (v) {
  var l = v.length
  while(l--) if(v[l]) return false
  return true
}

var isOne = exports.isOne = function (v) {
  var l = v.length
  while(l--) {
    if(l === 0)   return v[0] === 1
    else if(v[l]) return false
  }
  return true
}

//okay, need addShift(a, b, n)
//a + (b<<n)

var add = exports.add = function (a, b, c) {
  var l = Math.max(a.length, b.length)

  if(a.length == b.length && (a[l-1] + b[l-1])>>1)
    l ++

  if(!c) { c = new Buffer(l); c.fill() }
  var carry = 0
  for(var i = 0; i < l; i++) {
    var v = (a[i] || 0) + (b[i] || 0) + carry
    c[i] = v & 0xff
    carry = v >> 8
  }
  if(carry)//check if last item is a carry.
    c[l] = carry
  return c
}

// m = a + (b << shift)
var addShift = exports.addShift = function (a, b, shift, c) {
 var l = Math.max(a.length, b.length)

  if(a.length == b.length && (a[l-1] + b[l-1])>>1)
    l ++

  var sbits = shift & 7
  var sbytes = shift >> 3

  if(!c) { c = new Buffer(l); c.fill() }
  var carry = 0, byte = 0
  for(var i = 0; i < l; i++) {
//    console.log( ((b[i - sbytes] || 0) << sbits).toString(2), (byte >> 8).toString(2))
    byte = ((b[i - sbytes] || 0) << sbits) | (byte >> 8)
//    console.log(i, sbytes, byte.toString(2))
    var v = (a[i] || 0) + (byte&0xff) + carry
    c[i] = v & 0xff
    carry = v >> 8
  }
  if(carry)//check if last item is a carry.
    c[l] = carry
  return c
}

//there are no negatives, so make sure A is larger.
//basically the reverse of add.

var subtract = exports.sub =
exports.subtract = function (a, b, c) {
  var l = Math.max(a.length, b.length)
  if(!c) { c = new Buffer(l); c.fill() }
  var carry = 0
  for(var i = 0; i < l; i++) {
    var A = (a[i] || 0), B = (b[i] || 0) + carry
    if(A < B) {
      A += 256; carry = 1
    } else
      carry = 0
    c[i] = A - B
  }
  return c
}

// a % n (where n is < 2^31)
// this uses Buffer#readInt32LE
// so, buffers length must be multiple of 4.
// should also be able to adapt this to divide by int,
// which would be useful for converting to different bases (like base 10, or 58)

exports.modInt = function (a, n) {
  var l = a.length, w = 0
  while(l--) w = (w << 8 | a[l]) % n
  return w
}

//return -1, 0, or 1 if a < b, a == b, a > b

var compare = exports.compare = function (a, b) {
  var l = Math.max(a.length, b.length)
  while(l--) {
    var x = a[l] || 0
    var y = b[l] || 0
    if(x !== y)
      return x < y ? -1 : 1
  }
  return 0
}

var shift = exports.shift = function (a, n, c) {
  //if the shift is larger than a byte, iterate.
  //aha! just shift n%8, and then shift (n - (n%8))/8 bytes.

  var bits  = n%8
  var bytes =  (n - bits)/8
  if(!c) { c = new Buffer(a.length); c.fill() }

  var carry = 0
  if(n > 0) {
    for(var i = a.length - 1; i >= -bytes; i--) {
      var v = a[i] << bits
      c[i + bytes + 1] = carry | v >> 8
      carry = c[i + bytes] = v & 0xff
    }
  } else {
    var bits = -1*bits
    for(var i = bytes; i <= a.length; i++) {
      // shift into the second byte,
      // so that we have a chance to grab the carry.
      var v = (a[i] << 8) >> bits
      c[i + bytes - 1] = v & 0xff | carry
      carry = c[i + bytes] = v >> 8
    }
  }
  return c
}

//multiply, using shift + add

var multiply = exports.mul =
exports.multiply = function (a, b, m) {
  var l = a.length + b.length, prev = 0
  var w = new Buffer(l); w.fill()

  ;(Array.isArray(b) ? new Buffer(b) : b).copy(w)

  if(!m) m = new Buffer(l)
  if(a !== m) m.fill() //m must be zeros, or it will affect stuff.

  var bits = l<<3
  for(var i = 0; i < bits; i++)
    if(getBit(a, i)) addShift(m, w, i, m)
  return m
}

function _msb (x) {
  return (
    x & 0xF0
    ? x & 0xC0 ? x & 0x80 ? 8 : 7 : x & 0x20 ? 6 : 5
    : x & 0x0C ? x & 0x08 ? 4 : 3 : x & 0x02 ? 2 : x
  )
}

var mostSignificantBit
var msb = mostSignificantBit = exports.msb =
exports.mostSignificantBit = function (a) {
  var l = a.length
  while(l--)
    if(a[l]) return ((l)*8)+_msb(a[l])
  return 0
}
var getBit =
exports.getBit = function (q, bit) {
  return q[bit>>3] & 1<<(bit%8)
}

var divide = exports.divide = exports.div = function (a, b, q, r) {
  if(!q) q = new Buffer(a.length)
  if(!r) r = new Buffer(a.length)
  q.fill(); r.fill()
  //if b is larger, then a is the remainder
  if(compare(b, a) > 1) {
    q.fill()
    ;(Array.isArray(r) ? new Buffer(r) : r).copy(a) //remainder is the same
    return {quotient: q, remainder: r}
  }
  var mA = msb(a), mB = msb(b)

  var _b  = new Buffer(a.length)
  var _b2 = new Buffer(a.length)
  var _r  = new Buffer(a.length)
  _b.fill()
  ;(Array.isArray(a) ? new Buffer(a) : a ).copy(r)

  //shift b to line up with a.
  shift(b, mA - mB, _b)

  // instead of shifting this along 1 bit at a time
  // it would probably be more performant to find the
  // next most significant bit and move that far.
  // at least in sparse numbers.

  var bit = mA - mB
  while(bit >= 0) {
    if(compare(_b, r) <= 0) {
      subtract(r, _b, _r)
      var t = r; r = _r; _r = t
      //set 1 bit of quotent!
      q[bit>>3] |= 1<<(bit%8)
    }

    shift(_b, -1, _b)
    bit--
  }
  return {remainder: r, quotient: q}
}

// to base:
// b.unshift(_a = (a % 10)); a = (a - _a) / 10; b

var square = exports.square = function (a, m) {
  return multiply(a, a, m)
}

//exports.exponent
//http://en.wikipedia.org/wiki/Modular_exponentiation#Right-to-left_binary_method

var pow = exports.pow =
exports.power = function (base, exp, mod) {
  var result = new Buffer(exp.length)
  result.fill()
  result[0] = 1

  var modulus = mod ? function (v) {
    return divide(v, mod).remainder
  } : function (id) { return id }

  var msb = mostSignificantBit(exp)
  for(var i = 0; i < msb; i++) {
    if(getBit(exp, i))
      result = modulus(multiply(result, base))
    base = modulus(square(base))
  }

  return result
}

// greatest common divisor
// http://en.wikipedia.org/wiki/Binary_GCD_algorithm

exports.gcd = function (u, v, mutate) {
  if(!mutate) {
    u = new Buffer(u)
    v = new Buffer(v)
  }

  var shifts = 0;

  //GCD(0,v) == v; GCD(u,0) == u, GCD(0,0) == 0
  if (isZero(u)) return v;
  if (isZero(v)) return u;

  // if u and v are divisible by 2, then gcd must be 2*something.
  // gcd(v, u) == gcd(v/2, u/2)*2
  // shift out a factor of two, and we'll add it back at the end.
  for (shifts = 0; ((u[0] | v[0]) & 1) == 0; ++shifts) {
     shift(u, -1, u)
     shift(v, -1, v)
  }

  //NOTE:  v & 1 == isEven
  //      ~v & 1 == isOdd (~ flips the last 0 into 1, then ands it with 1)

  //while u is even, divide by two.
  while (isEven(u)) {
    shift(u, -1, u)
  }

  //From here on, u is always odd.
  do {
   //if v is even, 2 cannot be a divisor.
   while (isEven(v)) shift(v, -1, v)

   // Now u and v are both odd.
   // swap so that v is larger, so that we can safely subtract v - u
    if (compare(u, v) > 0) {
      var t = v; v = u; u = t;
    }
    v = subtract(v, u)
    //v is now even, because even = odd1 - odd2
  } while (!isZero(v))

  //multiply by the factors of 2 we removed at line 240
  return shift(u, shifts, u)
}

var isOdd = exports.isOdd = function (p) {
  return !!(p[0] & 1)
}

var isEven = exports.isEven = function (p) {
  return !(p[0] & 1)
}

exports.inverse = function (n, p) {
  var a = fromInt(1, n.length), b = fromInt(0, n.length)
  var x = new Buffer(n), y = new Buffer(p)
  var tmp, i, nz=1;

  if(isEven(p))
    throw new Error("inverse: p must be odd"+p);

  // invariant: y is odd
  do {
    if (isOdd(x)) {
      if (compare(x, y) < 0) {
        // x < y; swap everything
        tmp = x; x = y; y = tmp;
        tmp = a; a = b; b = tmp;
      }

      subtract(x, y, x)
      if(compare(a, b) < 0) add(a, p, a)
      subtract(a, b, a)
    }

    // cut everything in half
    shift(x, -1, x)
    if (isOdd(a)) add(a, p, a)
    shift(a, -1, a)
  } while(!isZero(x))

  if (!isOne(y)) throw new Error("inverseMod: p and x must be relatively prime")
  return b;
}

function _lsb (x) {
  if(x == 0) return -1
  return (
    x & 0x0F
    ? x & 0x03 ? x & 0x01 ? 0 : 1 : x & 0x04 ? 2 : 3
    : x & 0x30 ? x & 0x10 ? 4 : 5 : x & 0x20 ? 6 : 7
  )
}

var lowestSetBit = exports.lowestSetBit = function (n) {
  for(var i = 0; i < n.length; i++)
    if(n[i]) return i + _lsb(n[i])
  return -1
}

<commit_msg>AWESOME - made power usable by having divide truncate the modulus buffer to correct size!<commit_after>//add two buffers,
//putting least significant at left will be simplest.
//iterate over buffers from lsb to msb
//and add each byte & 0xff, carrying overflow.

var fromInt = exports.fromInt = function (int, length) {
  var b = new Buffer(Math.max(length || 0, 4))
  b.fill()
  b.writeInt32LE(int, 0)
  return b
}

var isZero = exports.isZero = function (v) {
  var l = v.length
  while(l--) if(v[l]) return false
  return true
}

var isOne = exports.isOne = function (v) {
  var l = v.length
  while(l--) {
    if(l === 0)   return v[0] === 1
    else if(v[l]) return false
  }
  return true
}

//okay, need addShift(a, b, n)
//a + (b<<n)

var add = exports.add = function (a, b, c) {
  var l = Math.max(a.length, b.length)

  if(a.length == b.length && (a[l-1] + b[l-1])>>1)
    l ++

  if(!c) { c = new Buffer(l); c.fill() }
  var carry = 0
  for(var i = 0; i < l; i++) {
    var v = (a[i] || 0) + (b[i] || 0) + carry
    c[i] = v & 0xff
    carry = v >> 8
  }
  if(carry)//check if last item is a carry.
    c[l] = carry
  return c
}

// m = a + (b << shift)
var addShift = exports.addShift = function (a, b, shift, c) {
 var l = Math.max(a.length, b.length)

  if(a.length == b.length && (a[l-1] + b[l-1])>>1)
    l ++

  var sbits = shift & 7
  var sbytes = shift >> 3

  if(!c) { c = new Buffer(l); c.fill() }
  var carry = 0, byte = 0
  for(var i = 0; i < l; i++) {
//    console.log( ((b[i - sbytes] || 0) << sbits).toString(2), (byte >> 8).toString(2))
    byte = ((b[i - sbytes] || 0) << sbits) | (byte >> 8)
//    console.log(i, sbytes, byte.toString(2))
    var v = (a[i] || 0) + (byte&0xff) + carry
    c[i] = v & 0xff
    carry = v >> 8
  }
  if(carry)//check if last item is a carry.
    c[l] = carry
  return c
}

//there are no negatives, so make sure A is larger.
//basically the reverse of add.

var subtract = exports.sub =
exports.subtract = function (a, b, c) {
  var l = Math.max(a.length, b.length)
  if(!c) { c = new Buffer(l); c.fill() }
  var carry = 0
  for(var i = 0; i < l; i++) {
    var A = (a[i] || 0), B = (b[i] || 0) + carry
    if(A < B) {
      A += 256; carry = 1
    } else
      carry = 0
    c[i] = A - B
  }
  return c
}

// a % n (where n is < 2^31)
// this uses Buffer#readInt32LE
// so, buffers length must be multiple of 4.
// should also be able to adapt this to divide by int,
// which would be useful for converting to different bases (like base 10, or 58)

exports.modInt = function (a, n) {
  var l = a.length, w = 0
  while(l--) w = (w << 8 | a[l]) % n
  return w
}

//return -1, 0, or 1 if a < b, a == b, a > b

var compare = exports.compare = function (a, b) {
  var l = Math.max(a.length, b.length)
  while(l--) {
    var x = a[l] || 0
    var y = b[l] || 0
    if(x !== y)
      return x < y ? -1 : 1
  }
  return 0
}

var shift = exports.shift = function (a, n, c) {
  //if the shift is larger than a byte, iterate.
  //aha! just shift n%8, and then shift (n - (n%8))/8 bytes.

  var bits  = n%8
  var bytes =  (n - bits)/8
  if(!c) { c = new Buffer(a.length); c.fill() }

  var carry = 0
  if(n > 0) {
    for(var i = a.length - 1; i >= -bytes; i--) {
      var v = a[i] << bits
      c[i + bytes + 1] = carry | v >> 8
      carry = c[i + bytes] = v & 0xff
    }
  } else {
    var bits = -1*bits
    for(var i = bytes; i <= a.length; i++) {
      // shift into the second byte,
      // so that we have a chance to grab the carry.
      var v = (a[i] << 8) >> bits
      c[i + bytes - 1] = v & 0xff | carry
      carry = c[i + bytes] = v >> 8
    }
  }
  return c
}

//multiply, using shift + add

var multiply = exports.mul =
exports.multiply = function (a, b, m) {
  var l = a.length + b.length, prev = 0
  var w = new Buffer(l); w.fill()

  ;(Array.isArray(b) ? new Buffer(b) : b).copy(w)

  if(!m) m = new Buffer(l)
  if(a !== m) m.fill() //m must be zeros, or it will affect stuff.

  var bits = l<<3
  for(var i = 0; i < bits; i++)
    if(getBit(a, i)) addShift(m, w, i, m)
  return m
}

function _msb (x) {
  return (
    x & 0xF0
    ? x & 0xC0 ? x & 0x80 ? 8 : 7 : x & 0x20 ? 6 : 5
    : x & 0x0C ? x & 0x08 ? 4 : 3 : x & 0x02 ? 2 : x
  )
}

var mostSignificantBit
var msb = mostSignificantBit = exports.msb =
exports.mostSignificantBit = function (a) {
  var l = a.length
  while(l--)
    if(a[l]) return ((l)*8)+_msb(a[l])
  return 0
}
var getBit =
exports.getBit = function (q, bit) {
  return q[bit>>3] & 1<<(bit%8)
}

var divide = exports.divide = exports.div = function (a, b, q, r) {
  if(!q && q !== false) {q = new Buffer(a.length); q.fill()}
  if(!r) r = new Buffer(a.length)
  r.fill()
  //if b is larger, then a is the remainder
  if(compare(b, a) > 1) {
    q.fill()
    ;(Array.isArray(r) ? new Buffer(r) : r).copy(a) //remainder is the same
    return {quotient: q, remainder: r}
  }
  var mA = msb(a), mB = msb(b)

  var _b  = new Buffer(a.length)
  var _r  = _r //new Buffer(a.length)
  _b.fill()
  ;(Array.isArray(a) ? new Buffer(a) : a ).copy(r)

  //shift b to line up with a.
  shift(b, mA - mB, _b)

  // instead of shifting this along 1 bit at a time
  // it would probably be more performant to find the
  // next most significant bit and move that far.
  // at least in sparse numbers.

  var bit = mA - mB
  while(bit >= 0) {
    if(compare(_b, r) <= 0) {
      subtract(r, _b, r)
      //set 1 bit of quotent!
      if(q) q[bit>>3] |= 1<<(bit%8)
    }

    shift(_b, -1, _b)
    bit--
  }
  var _r = new Buffer(b.length + 8)
  _r.fill()
  r.copy(_r)
  return {remainder: _r, quotient: q}
}

// to base:
// b.unshift(_a = (a % 10)); a = (a - _a) / 10; b

var square = exports.square = function (a, m) {
  return multiply(a, a, m)
}

//exports.exponent
//http://en.wikipedia.org/wiki/Modular_exponentiation#Right-to-left_binary_method

var pow = exports.pow =
exports.power = function (base, exp, mod) {
  var result = new Buffer(exp.length)
  result.fill()
  result[0] = 1

  var modulus = mod ? function (v) {
    return divide(v, mod, false).remainder
  } : function (id) { return id }

  var msb = mostSignificantBit(exp)
  for(var i = 0; i < msb; i++) {
    if(getBit(exp, i))
      result = modulus(multiply(result, base))
    base = modulus(square(modulus(base)))
  }

  return result
}

// greatest common divisor
// http://en.wikipedia.org/wiki/Binary_GCD_algorithm

exports.gcd = function (u, v, mutate) {
  if(!mutate) {
    u = new Buffer(u)
    v = new Buffer(v)
  }

  var shifts = 0;

  //GCD(0,v) == v; GCD(u,0) == u, GCD(0,0) == 0
  if (isZero(u)) return v;
  if (isZero(v)) return u;

  // if u and v are divisible by 2, then gcd must be 2*something.
  // gcd(v, u) == gcd(v/2, u/2)*2
  // shift out a factor of two, and we'll add it back at the end.
  for (shifts = 0; ((u[0] | v[0]) & 1) == 0; ++shifts) {
     shift(u, -1, u)
     shift(v, -1, v)
  }

  //NOTE:  v & 1 == isEven
  //      ~v & 1 == isOdd (~ flips the last 0 into 1, then ands it with 1)

  //while u is even, divide by two.
  while (isEven(u)) {
    shift(u, -1, u)
  }

  //From here on, u is always odd.
  do {
   //if v is even, 2 cannot be a divisor.
   while (isEven(v)) shift(v, -1, v)

   // Now u and v are both odd.
   // swap so that v is larger, so that we can safely subtract v - u
    if (compare(u, v) > 0) {
      var t = v; v = u; u = t;
    }
    v = subtract(v, u)
    //v is now even, because even = odd1 - odd2
  } while (!isZero(v))

  //multiply by the factors of 2 we removed at line 240
  return shift(u, shifts, u)
}

var isOdd = exports.isOdd = function (p) {
  return !!(p[0] & 1)
}

var isEven = exports.isEven = function (p) {
  return !(p[0] & 1)
}

exports.inverse = function (n, p) {
  var a = fromInt(1, n.length), b = fromInt(0, n.length)
  var x = new Buffer(n), y = new Buffer(p)
  var tmp, i, nz=1;

  if(isEven(p))
    throw new Error("inverse: p must be odd"+p);

  // invariant: y is odd
  do {
    if (isOdd(x)) {
      if (compare(x, y) < 0) {
        // x < y; swap everything
        tmp = x; x = y; y = tmp;
        tmp = a; a = b; b = tmp;
      }

      subtract(x, y, x)
      if(compare(a, b) < 0) add(a, p, a)
      subtract(a, b, a)
    }

    // cut everything in half
    shift(x, -1, x)
    if (isOdd(a)) add(a, p, a)
    shift(a, -1, a)
  } while(!isZero(x))

  if (!isOne(y)) throw new Error("inverseMod: p and x must be relatively prime")
  return b;
}

function _lsb (x) {
  if(x == 0) return -1
  return (
    x & 0x0F
    ? x & 0x03 ? x & 0x01 ? 0 : 1 : x & 0x04 ? 2 : 3
    : x & 0x30 ? x & 0x10 ? 4 : 5 : x & 0x20 ? 6 : 7
  )
}

var lowestSetBit = exports.lowestSetBit = function (n) {
  for(var i = 0; i < n.length; i++)
    if(n[i]) return i + _lsb(n[i])
  return -1
}

<|endoftext|>


<commit_before>// These are the pages you can go to.
// They are all wrapped in the App component, which should contain the navbar etc
// See http://blog.mxstbr.com/2016/01/react-apps-with-pages for more information
// about the code splitting business
import { getAsyncInjectors } from 'utils/asyncInjectors';
import ContactUs from 'containers/ContactUs/sagas';
import EmailTools from 'containers/EmailTools/sagas';
import NewsFeed from 'containers/NewsFeed/sagas';
import Tools from 'containers/Tools/sagas';
import TranslatableStaticText from 'containers/TranslatableStaticText/sagas';
import SubmitNewsFeed from 'containers/SubmitNewsFeed/sagas';
import HomePage from 'containers/HomePage/sagas';
import WhatsHappening from 'containers/WhatsHappening/sagas';
import SubmitResource from 'containers/SubmitResource/sagas';
import {changeLocale} from 'containers/LanguageProvider/actions';
const errorLoading = (err) => {
  console.error('Dynamic page loading failed', err); // eslint-disable-line no-console
};

const loadModule = (cb) => (componentModule) => {
  cb(null, componentModule.default);
};

export default function createRoutes(store) {
  // Create reusable async injectors using getAsyncInjectors factory
  const { injectReducer, injectSagas } = getAsyncInjectors(store); // eslint-disable-line no-unused-vars
  injectSagas(ContactUs);

  injectSagas(WhatsHappening);

  //enable email everywhere
  injectSagas(EmailTools);

  //for HomePage
  injectSagas(HomePage);

  //get news feed
  injectSagas(NewsFeed);

  //close tools when changing locs
  injectSagas(Tools);

  injectSagas(TranslatableStaticText);

  injectSagas(SubmitNewsFeed);

  // TODO Re-examine this
  // injectSagas(LanguageProvider);

  const getHomePageComponent = (nextState, cb) => {
    const importModules = Promise.all([
      import('containers/HomePage/reducer'),
      // import('containers/SearchField/sagas'),
      import('containers/HomePage'),
      import('containers/ToolsViewOptions/reducer'),
      import('containers/ToolsSortOptions/reducer'),
    ]);

    const renderRoute = loadModule(cb);

    importModules.then(([reducer, /*searchSagas,*/ component,
          toolsViewOptionsReducer, toolsSortOptionsReducer]) => {
      injectReducer('homePage', reducer.default);
      // injectSagas(searchSagas.default);

      injectReducer('toolsView', toolsViewOptionsReducer.default);
      injectReducer('toolsSort', toolsSortOptionsReducer.default)

      renderRoute(component);
    });

    importModules.catch(errorLoading);
  };

  return [
    {
      path: '/',
      name: 'homePage',
      getComponent: getHomePageComponent,
    },
    {
      path: '/whats-happening',
      name: 'whats-happening',
      ignoreScrollBehavior: true, //for useScroll
      getComponent(nextState, cb) {

          const importModules = Promise.all([
            import('containers/WhatsHappening'),
          ]);

          const renderRoute = loadModule(cb);

          importModules.then(([component]) => {
            renderRoute(component);
          });

          importModules.catch(errorLoading);

      },
    },
    {
      path: '/tool(/:label)*',
      name: 'tool',
      scrollToTop: true,
      getComponent(nextState, cb) {

          const importModules = Promise.all([
            import('containers/ToolPage/reducer'),
            import('containers/ToolPage/sagas'),
            import('containers/SubmitRealWorldExample/sagas'),
            import('containers/AskTheContributor/sagas'),
            import('containers/ToolPage'),
          ]);

          const renderRoute = loadModule(cb);

          importModules.then(([reducer, toolPageSagas, worldExampleSagas, askContributor, component]) => {
            injectReducer('tool', reducer.default);
            injectSagas(toolPageSagas.default);
            injectSagas(worldExampleSagas.default);
            injectSagas(askContributor.default);
            renderRoute(component);
          });

          importModules.catch(errorLoading);

      },
    },
    {
      path: '/about(/:section)*',
      name: 'about',
      ignoreScrollBehavior: true, //for useScroll
      getComponent(nextState, cb) {

          const importModules = Promise.all([
            import('containers/AboutPage'),
          ]);

          const renderRoute = loadModule(cb);

          importModules.then(([component]) => {
            renderRoute(component);
          });

          importModules.catch(errorLoading);

      },
    },
    {
      path: '/contribute(/:section)*',
      name: 'contribute',
      ignoreScrollBehavior: true, //for useScroll
      getComponent(nextState, cb) {

          const importModules = Promise.all([
            import('containers/ContributePage'),
          ]);

          const renderRoute = loadModule(cb);

          importModules.then(([component]) => {
            renderRoute(component);
          });

          importModules.catch(errorLoading);

      },
    },
    {
      path: '/resources(/:section)*',
      name: 'resources',
      ignoreScrollBehavior: true, //for useScroll
      getComponent(nextState, cb) {

          const importModules = Promise.all([
            import('containers/TrainingPage'),
            import('containers/SubmitResource/sagas'),
          ]);

          const renderRoute = loadModule(cb);
          importModules.then(([component, submitResourceSagas]) => {
            injectSagas(submitResourceSagas.default);
            renderRoute(component);
          });
          importModules.catch(errorLoading);
      },
    },
    {
      path: '/platforms(/:section)*',
      name: 'platforms',
      ignoreScrollBehavior: true, //for useScroll
      getComponent(nextState, cb) {

          const importModules = Promise.all([
            import('containers/PlatformsPage'),
          ]);

          const renderRoute = loadModule(cb);
          importModules.then(([component]) => {
            renderRoute(component);
          });
          importModules.catch(errorLoading);
      },
    },
    // Entrance
    {
      path: '/ar(/:items)*',
      name: 'arabic',
      onEnter: function(nextState, replace, next) {
        const nextPath = nextState.params.items ? `/${nextState.params.items}${nextState.params.splat}` : '/';
        replace(nextPath);
        setTimeout(function() {
          store.dispatch(changeLocale("ar"));
          next();
        }, 50);      }
    },
    {
      path: '/en(/:items)*',
      name: 'english',
      onEnter: function(nextState, replace, next){
        const nextPath = nextState.params.items ? `/${nextState.params.items}${nextState.params.splat}` : '/';
        replace(nextPath);
        setTimeout(function() {
          store.dispatch(changeLocale("en"));
          next();
        }, 50);
      }
    },
    {
      path: '/es(/:items)*',
      name: 'homePage',
      onEnter: function(nextState, replace, next) {
        const nextPath = nextState.params.items ? `/${nextState.params.items}${nextState.params.splat}` : '/';

        replace(nextPath);
        setTimeout(function() {
          store.dispatch(changeLocale("es"));
          next();
        }, 50);
      },
    },
    {
      path: '/:filter(type|tag|search)(/:label(/:region)*)*',
      name: 'homePage',
      getComponent: getHomePageComponent,
    },
    {
      path: '*',
      name: 'notfound',
      getComponent(nextState, cb) {
        import('containers/NotFoundPage')
          .then(loadModule(cb))
          .catch(errorLoading);
      },
    },
  ];
}
<commit_msg>Add Portuguese route prefix<commit_after>// These are the pages you can go to.
// They are all wrapped in the App component, which should contain the navbar etc
// See http://blog.mxstbr.com/2016/01/react-apps-with-pages for more information
// about the code splitting business
import { getAsyncInjectors } from 'utils/asyncInjectors';
import ContactUs from 'containers/ContactUs/sagas';
import EmailTools from 'containers/EmailTools/sagas';
import NewsFeed from 'containers/NewsFeed/sagas';
import Tools from 'containers/Tools/sagas';
import TranslatableStaticText from 'containers/TranslatableStaticText/sagas';
import SubmitNewsFeed from 'containers/SubmitNewsFeed/sagas';
import HomePage from 'containers/HomePage/sagas';
import WhatsHappening from 'containers/WhatsHappening/sagas';
import SubmitResource from 'containers/SubmitResource/sagas';
import {changeLocale} from 'containers/LanguageProvider/actions';
const errorLoading = (err) => {
  console.error('Dynamic page loading failed', err); // eslint-disable-line no-console
};

const loadModule = (cb) => (componentModule) => {
  cb(null, componentModule.default);
};

export default function createRoutes(store) {
  // Create reusable async injectors using getAsyncInjectors factory
  const { injectReducer, injectSagas } = getAsyncInjectors(store); // eslint-disable-line no-unused-vars
  injectSagas(ContactUs);

  injectSagas(WhatsHappening);

  //enable email everywhere
  injectSagas(EmailTools);

  //for HomePage
  injectSagas(HomePage);

  //get news feed
  injectSagas(NewsFeed);

  //close tools when changing locs
  injectSagas(Tools);

  injectSagas(TranslatableStaticText);

  injectSagas(SubmitNewsFeed);

  // TODO Re-examine this
  // injectSagas(LanguageProvider);

  const getHomePageComponent = (nextState, cb) => {
    const importModules = Promise.all([
      import('containers/HomePage/reducer'),
      // import('containers/SearchField/sagas'),
      import('containers/HomePage'),
      import('containers/ToolsViewOptions/reducer'),
      import('containers/ToolsSortOptions/reducer'),
    ]);

    const renderRoute = loadModule(cb);

    importModules.then(([reducer, /*searchSagas,*/ component,
          toolsViewOptionsReducer, toolsSortOptionsReducer]) => {
      injectReducer('homePage', reducer.default);
      // injectSagas(searchSagas.default);

      injectReducer('toolsView', toolsViewOptionsReducer.default);
      injectReducer('toolsSort', toolsSortOptionsReducer.default)

      renderRoute(component);
    });

    importModules.catch(errorLoading);
  };

  return [
    {
      path: '/',
      name: 'homePage',
      getComponent: getHomePageComponent,
    },
    {
      path: '/whats-happening',
      name: 'whats-happening',
      ignoreScrollBehavior: true, //for useScroll
      getComponent(nextState, cb) {

          const importModules = Promise.all([
            import('containers/WhatsHappening'),
          ]);

          const renderRoute = loadModule(cb);

          importModules.then(([component]) => {
            renderRoute(component);
          });

          importModules.catch(errorLoading);

      },
    },
    {
      path: '/tool(/:label)*',
      name: 'tool',
      scrollToTop: true,
      getComponent(nextState, cb) {

          const importModules = Promise.all([
            import('containers/ToolPage/reducer'),
            import('containers/ToolPage/sagas'),
            import('containers/SubmitRealWorldExample/sagas'),
            import('containers/AskTheContributor/sagas'),
            import('containers/ToolPage'),
          ]);

          const renderRoute = loadModule(cb);

          importModules.then(([reducer, toolPageSagas, worldExampleSagas, askContributor, component]) => {
            injectReducer('tool', reducer.default);
            injectSagas(toolPageSagas.default);
            injectSagas(worldExampleSagas.default);
            injectSagas(askContributor.default);
            renderRoute(component);
          });

          importModules.catch(errorLoading);

      },
    },
    {
      path: '/about(/:section)*',
      name: 'about',
      ignoreScrollBehavior: true, //for useScroll
      getComponent(nextState, cb) {

          const importModules = Promise.all([
            import('containers/AboutPage'),
          ]);

          const renderRoute = loadModule(cb);

          importModules.then(([component]) => {
            renderRoute(component);
          });

          importModules.catch(errorLoading);

      },
    },
    {
      path: '/contribute(/:section)*',
      name: 'contribute',
      ignoreScrollBehavior: true, //for useScroll
      getComponent(nextState, cb) {

          const importModules = Promise.all([
            import('containers/ContributePage'),
          ]);

          const renderRoute = loadModule(cb);

          importModules.then(([component]) => {
            renderRoute(component);
          });

          importModules.catch(errorLoading);

      },
    },
    {
      path: '/resources(/:section)*',
      name: 'resources',
      ignoreScrollBehavior: true, //for useScroll
      getComponent(nextState, cb) {

          const importModules = Promise.all([
            import('containers/TrainingPage'),
            import('containers/SubmitResource/sagas'),
          ]);

          const renderRoute = loadModule(cb);
          importModules.then(([component, submitResourceSagas]) => {
            injectSagas(submitResourceSagas.default);
            renderRoute(component);
          });
          importModules.catch(errorLoading);
      },
    },
    {
      path: '/platforms(/:section)*',
      name: 'platforms',
      ignoreScrollBehavior: true, //for useScroll
      getComponent(nextState, cb) {

          const importModules = Promise.all([
            import('containers/PlatformsPage'),
          ]);

          const renderRoute = loadModule(cb);
          importModules.then(([component]) => {
            renderRoute(component);
          });
          importModules.catch(errorLoading);
      },
    },
    // Entrance
    {
      path: '/ar(/:items)*',
      name: 'arabic',
      onEnter: function(nextState, replace, next) {
        const nextPath = nextState.params.items ? `/${nextState.params.items}${nextState.params.splat}` : '/';
        replace(nextPath);
        setTimeout(function() {
          store.dispatch(changeLocale("ar"));
          next();
        }, 50);      }
    },
    {
      path: '/en(/:items)*',
      name: 'english',
      onEnter: function(nextState, replace, next){
        const nextPath = nextState.params.items ? `/${nextState.params.items}${nextState.params.splat}` : '/';
        replace(nextPath);
        setTimeout(function() {
          store.dispatch(changeLocale("en"));
          next();
        }, 50);
      }
    },
    {
      path: '/es(/:items)*',
      name: 'spanish',
      onEnter: function(nextState, replace, next) {
        const nextPath = nextState.params.items ? `/${nextState.params.items}${nextState.params.splat}` : '/';
        replace(nextPath);
        setTimeout(function() {
          store.dispatch(changeLocale("es"));
          next();
        }, 50);
      },
    },
    {
      path: '/pt(/:items)*',
      name: 'portuguese',
      onEnter: function(nextState, replace, next) {
        const nextPath = nextState.params.items ? `/${nextState.params.items}${nextState.params.splat}` : '/';
        replace(nextPath);
        setTimeout(function() {
          store.dispatch(changeLocale("pt"));
          next();
        }, 50);
      },
    },
    {
      path: '/:filter(type|tag|search)(/:label(/:region)*)*',
      name: 'homePage',
      getComponent: getHomePageComponent,
    },
    {
      path: '*',
      name: 'notfound',
      getComponent(nextState, cb) {
        import('containers/NotFoundPage')
          .then(loadModule(cb))
          .catch(errorLoading);
      },
    },
  ];
}
<|endoftext|>


<commit_before>module.exports = {
  bind : function (app) {

    app.get('/', function (req, res) {
      res.render('index');
    });

    // add your routes here

    // v2 step 1 - create case

    var display = {
      property: false,
      borrower_1: false,
      borrower_2: false
    };

    app.get('/v2/step1/login', function (req, res) {
      // make sure EVERYTHING is set to FALSE again
      display.property = false;
      display.borrower_1 = false;
      display.borrower_2 = false;
      res.render('v2/step1/login');
    });

    // property is now found and should be displayed
    app.get('/v2/step1/case-property-selected', function (req, res) {
      display.property = true;
      res.redirect('/v2/step1/case-base');
    });

    // first borrower addition
    app.get('/v2/step1/case-add-borrower-1', function (req, res) {
      display.borrower_1 = true;
      res.redirect('/v2/step1/case-base');
    });

    // second borrower addition
    app.get('/v2/step1/case-add-borrower-2', function (req, res) {
      display.borrower_2 = true;
      res.redirect('/v2/step1/case-base');
    });

    app.get('/v2/step1/case-base', function (req, res) {
      res.render('v2/step1/case-base', {
        "property": display.property,
        "borrower_1": display.borrower_1,
        "borrower_2": display.borrower_2
      });
    });

    // borrowers form page needs the variables too
    app.get('/v2/step1/add-borrower', function (req, res) {
      res.render('v2/step1/add-borrower', {
        "property": display.property,
        "borrower_1": display.borrower_1,
        "borrower_2": display.borrower_2
      });
    });

    // finally, case list needs just one of the variables
    app.get('/v2/step1/case-list', function (req, res) {
      res.render('v2/step1/case-list', {
        "borrower_2": display.borrower_2
      });
    });

  }
};
<commit_msg>Route variables to session instead<commit_after>module.exports = {
  bind : function (app) {

    app.get('/', function (req, res) {
      res.render('index');
    });

    // add your routes here

    // v2 step 1 - create case

    app.get('/v2/step1/*', function(req, res, next) {

      var n = req.session.views || 0;
      req.session.views = ++n;

      console.log('views: ' + req.session.views);
      console.log('displayProperty: ' + req.session.displayProperty);
      console.log('displayBorrower_1: ' + req.session.displayBorrower_1);
      console.log('displayBorrower_2: ' + req.session.displayBorrower_2);
      console.log('\n');

      next();
    });

    app.get('/v2/step1/login', function (req, res) {
      // destroy the session:
      req.session = null;
      res.render('v2/step1/login');
    });

    // property is now found and should be displayed
    app.get('/v2/step1/case-property-selected', function (req, res) {
      req.session.displayProperty = true;
      res.redirect('/v2/step1/case-base');
    });

    // first borrower addition
    app.get('/v2/step1/case-add-borrower-1', function (req, res) {
      req.session.displayBorrower_1 = true;
      res.redirect('/v2/step1/case-base');
    });

    // second borrower addition
    app.get('/v2/step1/case-add-borrower-2', function (req, res) {
      req.session.displayBorrower_2 = true;
      res.redirect('/v2/step1/case-base');
    });

    app.get('/v2/step1/case-base', function (req, res) {
      res.render('v2/step1/case-base', {
        "property": req.session.displayProperty,
        "borrower_1": req.session.displayBorrower_1,
        "borrower_2": req.session.displayBorrower_2
      });
    });

    // borrowers form page needs the variables too
    app.get('/v2/step1/add-borrower', function (req, res) {
      res.render('v2/step1/add-borrower', {
        "property": req.session.displayProperty,
        "borrower_1": req.session.displayBorrower_1,
        "borrower_2": req.session.displayBorrower_2
      });
    });

    // finally, case list needs just one of the variables
    app.get('/v2/step1/case-list', function (req, res) {
      res.render('v2/step1/case-list', {
        "borrower_2": req.session.displayBorrower_2
      });
    });

  }
};
<|endoftext|>


<commit_before>var http = require('http'),
    Route = require('routes-router'),
    levelup = require('levelup'),
    leveldown = require('leveldown'),
    fs = require('fs'),
    key = require('./lib/key.js');

var level = {};

function debug(x){
    process.stderr.write(x + '\n');
}

var router = Route();
var headers = {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'POST, GET',
    'Access-Control-Allow-Credentials': false,
    'Access-Control-Max-Age': '86400'
};
var port = 3001;
var lockperiod = 10*60;

var dbs = fs.readdirSync('./ldb/').filter(function(item) {
   return item.indexOf('.ldb') > -1;
});

dbs.forEach(function(ldb, idx) {
    debug('-- Loading db ' + ldb);
    levelup('./ldb/' + ldb, {
        createIfMissing: false,
        max_open_files: 500
    }, function(err, db) {
        if (err) debug('ERROR: ' + err);
        level[ldb] = db;
        loaded_db_count++;
        if (idx >= dbs.length-1) runPostInit();
    });
});

function runPostInit(){
    if (process.argv[2] === '--fixed') {
        fixed = {};
        var num_fixed = 0;
        Object.keys(level).forEach(function(db){
            fixed[db] = [];

            level[db].createReadStream({lt: '0001'})
                .on('data', function(data) {
                    fixed[db].push(key.decompose(data.key).hash);
                })
                .on('end', function(err) {
                    num_fixed++;
                    if (num_fixed === Object.keys(level).length) {
                        process.stdout.write(JSON.stringify(fixed));
                    }
                });
        });
    } else {
        http.createServer(router).listen(port, function() {
            debug('running on port ' + port);
        });
    }
}

router.addRoute('/error/:error', {
    POST: function(req, res, opts) {
        var body = '';
        req.on('data', function(data) {
            body += data;
        });
        req.on('end', function() {
            body = JSON.parse(body);
            getNextItem(opts.params.error, res, function(err, kv) {
                if (err) {
                    debug('/error route', err);
                    return error(res, 500, err);
                }
                track(opts.params.error, body.user, 'got', {_id: kv.key});
                res.writeHead(200, headers);
                return res.end(JSON.stringify(kv));
            });
        });
    }
});

router.addRoute('/fixed/:error', {
    POST: function(req, res, opts) {
        var body = '';
        req.on('data', function(data) {
            body += data;
        });
        req.on('end', function() {
            body = JSON.parse(body);
            if (body.user && body.state._id) {
                track(opts.params.error, body.user, 'fixed', body.state);

                // check that submitted error type exists
                var db = level[opts.params.error + '.ldb'];
                if (!db) return error(res, 500, opts.params.error + ' is not a valid error type');

                // retrieve the record's current state -- we can't trust the submitted state
                // not to have been modified by the clientside JS
                db.get(body.state._id, function(err, value) {
                    if (err) {
                        debug('error fetching key value', body.state._id);
                        return error(rs, 500, 'error fetching key value ' + body.state._id);
                    }

                    // delete the record from positive skipval keyspace
                    db.del(body.state._id, function(err) {
                        if (err){
                            debug('error deleting', err);
                            return error(rs, 500, 'error deleting key value ' + body.state._id);
                        }

                        // move record into skipval=0 keyspace, meaning it's fixed
                        var oldID = key.decompose(body.state._id);
                        var newID = key.compose(0, oldID.hash);
                        db.put(newID, value);
                    });

                    res.writeHead(200, headers);
                    return res.end('');

                });
            }
        });
    }
});

function getNextItem(error, res, callback) {
    if (error === (undefined || 'undefined')) {
        return callback('db type cannot be undefined');
    } else {
        var db = level[error + '.ldb'];
        if (!db) {
            return callback('Database \'' + error + '\' not loaded');
        } else {
            db.createReadStream({limit: 1, gt: '0001'})
                .on('data', function(data) {
                    var task_data = JSON.parse(data.value);
                    if (task_data.ignore) {
                        debug('Empty task database for error ' + error);
                        return callback('No valid tasks available for this error type.');
                    } else {
                        db.del(data.key, function() {
                            var oldID = key.decompose(data.key);
                            var newID = key.compose((oldID.skipval + 1), oldID.hash);

                            db.put(newID, JSON.stringify(task_data), function(err) {
                                if (err) debug('put', err);
                                data.key = newID;
                                data.value = JSON.parse(data.value);
                                return callback(null, data);
                            });
                        });
                    }
                })
                .on('error', function(err) {
                    debug('CreateReadStream error', err);
                    return callback('Something wrong with the database for error type \'' + err + '\'');
                });
        }
    }
}

function track(error, user, action, value) {
    // value must be an object
    var key = +new Date() + ':' + user;
    value._action = action;
    value._hash = key.decompose(value._id).hash;
    value = JSON.stringify(value);

    var db = level[error + '-tracking.ldb'];

    if (db) {
        db.put(key, value, function(err) {
            if (err) debug('put', err);
        });
    } else {
        debug('could not track: database does not exist for', error);
    }
}

function error(res, code, errString) {
    res.writeHead(code, headers);
    return res.end(errString);
}
<commit_msg>Remove legacy<commit_after>var http = require('http'),
    Route = require('routes-router'),
    levelup = require('levelup'),
    leveldown = require('leveldown'),
    fs = require('fs'),
    key = require('./lib/key.js');

var level = {};

function debug(x){
    process.stderr.write(x + '\n');
}

var router = Route();
var headers = {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'POST, GET',
    'Access-Control-Allow-Credentials': false,
    'Access-Control-Max-Age': '86400'
};
var port = 3001;
var lockperiod = 10*60;

var dbs = fs.readdirSync('./ldb/').filter(function(item) {
   return item.indexOf('.ldb') > -1;
});

dbs.forEach(function(ldb, idx) {
    debug('-- Loading db ' + ldb);
    levelup('./ldb/' + ldb, {
        createIfMissing: false,
        max_open_files: 500
    }, function(err, db) {
        if (err) debug('ERROR: ' + err);
        level[ldb] = db;
        if (idx >= dbs.length-1) runPostInit();
    });
});

function runPostInit(){
    if (process.argv[2] === '--fixed') {
        fixed = {};
        var num_fixed = 0;
        Object.keys(level).forEach(function(db){
            fixed[db] = [];

            level[db].createReadStream({lt: '0001'})
                .on('data', function(data) {
                    fixed[db].push(key.decompose(data.key).hash);
                })
                .on('end', function(err) {
                    num_fixed++;
                    if (num_fixed === Object.keys(level).length) {
                        process.stdout.write(JSON.stringify(fixed));
                    }
                });
        });
    } else {
        http.createServer(router).listen(port, function() {
            debug('running on port ' + port);
        });
    }
}

router.addRoute('/error/:error', {
    POST: function(req, res, opts) {
        var body = '';
        req.on('data', function(data) {
            body += data;
        });
        req.on('end', function() {
            body = JSON.parse(body);
            getNextItem(opts.params.error, res, function(err, kv) {
                if (err) {
                    debug('/error route', err);
                    return error(res, 500, err);
                }
                track(opts.params.error, body.user, 'got', {_id: kv.key});
                res.writeHead(200, headers);
                return res.end(JSON.stringify(kv));
            });
        });
    }
});

router.addRoute('/fixed/:error', {
    POST: function(req, res, opts) {
        var body = '';
        req.on('data', function(data) {
            body += data;
        });
        req.on('end', function() {
            body = JSON.parse(body);
            if (body.user && body.state._id) {
                track(opts.params.error, body.user, 'fixed', body.state);

                // check that submitted error type exists
                var db = level[opts.params.error + '.ldb'];
                if (!db) return error(res, 500, opts.params.error + ' is not a valid error type');

                // retrieve the record's current state -- we can't trust the submitted state
                // not to have been modified by the clientside JS
                db.get(body.state._id, function(err, value) {
                    if (err) {
                        debug('error fetching key value', body.state._id);
                        return error(rs, 500, 'error fetching key value ' + body.state._id);
                    }

                    // delete the record from positive skipval keyspace
                    db.del(body.state._id, function(err) {
                        if (err){
                            debug('error deleting', err);
                            return error(rs, 500, 'error deleting key value ' + body.state._id);
                        }

                        // move record into skipval=0 keyspace, meaning it's fixed
                        var oldID = key.decompose(body.state._id);
                        var newID = key.compose(0, oldID.hash);
                        db.put(newID, value);
                    });

                    res.writeHead(200, headers);
                    return res.end('');

                });
            }
        });
    }
});

function getNextItem(error, res, callback) {
    if (error === (undefined || 'undefined')) {
        return callback('db type cannot be undefined');
    } else {
        var db = level[error + '.ldb'];
        if (!db) {
            return callback('Database \'' + error + '\' not loaded');
        } else {
            db.createReadStream({limit: 1, gt: '0001'})
                .on('data', function(data) {
                    var task_data = JSON.parse(data.value);
                    if (task_data.ignore) {
                        debug('Empty task database for error ' + error);
                        return callback('No valid tasks available for this error type.');
                    } else {
                        db.del(data.key, function() {
                            var oldID = key.decompose(data.key);
                            var newID = key.compose((oldID.skipval + 1), oldID.hash);

                            db.put(newID, JSON.stringify(task_data), function(err) {
                                if (err) debug('put', err);
                                data.key = newID;
                                data.value = JSON.parse(data.value);
                                return callback(null, data);
                            });
                        });
                    }
                })
                .on('error', function(err) {
                    debug('CreateReadStream error', err);
                    return callback('Something wrong with the database for error type \'' + err + '\'');
                });
        }
    }
}

function track(error, user, action, value) {
    // value must be an object
    var key = +new Date() + ':' + user;
    value._action = action;
    value._hash = key.decompose(value._id).hash;
    value = JSON.stringify(value);

    var db = level[error + '-tracking.ldb'];

    if (db) {
        db.put(key, value, function(err) {
            if (err) debug('put', err);
        });
    } else {
        debug('could not track: database does not exist for', error);
    }
}

function error(res, code, errString) {
    res.writeHead(code, headers);
    return res.end(errString);
}
<|endoftext|>


<commit_before>// boilerplate includes
var config = require("../config/config"),
    helpers = require("./helpers"),
    elasticsearch = require("elasticsearch"),
    es = new elasticsearch.Client({
      host: config.elasticsearch,
      log: 'debug'
    });

module.exports = {

  // The homepage. A temporary search page.
  index: function(req, res) {
    res.render("index.html", {
      reportCount: reportCount,
      inspector: null
    });
  },

  // search/results
  reports: function(req, res) {
    var query;
    if (req.query.query) {
      query = req.query.query;
      if (query.charAt(0) != "\"" || query.charAt(query.length-1) != "\"")
        query = "\"" + query + "\"";
    }
    else
      query = "*";

    var inspector = req.query.inspector || null;
    var page = req.query.page || 1;

    search(query, inspector, page).then(function(results) {
      res.render("reports.html", {
        reportCount: reportCount,
        results: results,
        query: req.query.query,
        inspector: inspector,
        page: page
      });
    }, function(err) {
      console.log("Noooo!");
      res.status(500);
      res.render("reports.html", {
        reportCount: reportCount,
        results: null,
        query: null
      });
    });
  },

  reports_xml: function(req, res) {
    var query;
    if (req.query.query) {
      query = req.query.query;
      if (query.charAt(0) != "\"" || query.charAt(query.length-1) != "\"")
        query = "\"" + query + "\"";
    }
    else
      query = "*";

    var inspector = req.query.inspector || null;
    var page = req.query.page || 1;

    search(query, inspector, page).then(function(results) {
      res.type("atom");
      res.render("reports.xml.ejs", {
        results: results,
        query: req.query.query,
        inspector: inspector,
        page: page,
        self_url: req.url
      });
    }, function(err) {
      console.log("Noooo!");
      res.status(500);
      res.type("atom");
      res.send("Server error");
    });
  },

  inspectors: function(req, res) {
    res.render("inspectors.html", {
      reportCount: reportCount,
      inspectorReportCounts: inspectorReportCounts
    });
  },

  inspector: function(req, res) {
    var metadata = helpers.inspector_info(req.params.inspector);
    if (metadata) {
      var inspectorReportCount;
      if (inspectorReportCounts) {
        inspectorReportCount = inspectorReportCounts[req.params.inspector] || 0;
      } else {
        inspectorReportCount = null;
      }
      search("*", req.params.inspector, 1).then(function(results) {
        res.render("inspector.html", {
          reportCount: reportCount,
          inspector: req.params.inspector,
          metadata: metadata,
          inspectorReportCount: inspectorReportCount,
          results: results
        });
      }, function(err) {
        console.log("Noooo!");
        res.render("inspector.html", {
          reportCount: reportCount,
          inspector: req.params.inspector,
          metadata: metadata,
          results: []
        });
      });
    } else {
      res.status(404);
      res.render("inspector.html", {
        reportCount: reportCount,
        metadata: null
      });
    }
  },

  report: function(req, res) {
    get(req.params.inspector, req.params.report_id).then(function(result) {
      res.render("report.html", {
        reportCount: reportCount,
        report: result._source
      });
    }, function(err) {
      console.log("Nooooo! " + err);
      res.status(500);
      res.render("report.html", {
        reportCount: reportCount,
        report: null
      });
    });
  }

};

function get(inspector, report_id) {
  return es.get({
    index: 'oversight',
    type: 'reports',
    id: inspector + '-' + report_id
  });
}

function search(query, inspector, page) {
  var size = 10;
  var from = (page - 1) * size;
  var body = {
    "from": from,
    "size": size,
    "query": {
      "filtered": {
        "query": {
          "query_string": {
            "query": query,
            "default_operator": "AND",
            "use_dis_max": true,
            "fields": ["text", "title", "summary"]
          }
        }
      }
    },
    "sort": [{
      "published_on": "desc"
    }],
    "highlight": {
      "encoder": "html",
      "pre_tags": [""],
      "post_tags": [""],
      "fields": {
        "*": {}
      },
      "order": "score",
      "fragment_size": 500
    },
    "_source": ["report_id", "year", "inspector", "agency", "title", "agency_name", "url", "landing_url", "inspector_url", "published_on", "type", "file_type"]
  };

  if (inspector) {
    body.query.filtered.filter = {
      "term": {
        "inspector": inspector
      }
    };
  }

  return es.search({
    index: 'oversight',
    type: 'reports',
    body: body
  });
}

var reportCount = null;
var inspectorReportCounts = null;

function updateReportCounts() {
  es.count({
    index: "oversight",
    type: "reports"
  }).then(function(result) {
    reportCount = result.count;
  }, function(err) {
    console.log("Nooooo! " + err);
    reportCount = null;
  });
  es.search({
    index: "oversight",
    type: "reports",
    searchType: "count",
    body: {
      aggregations: {
        inspector_agg: {
          terms: {
            field: "inspector",
            size: 0
          }
        }
      }
    }
  }).then(function(result) {
    var buckets = result.aggregations.inspector_agg.buckets;
    inspectorReportCounts = {};
    for (var i = 0; i < buckets.length; i++) {
      inspectorReportCounts[buckets[i].key] = buckets[i].doc_count;
    }
  }, function(err) {
    console.log("Nooooo! " + err);
    inspectorReportCounts = null;
  });
}

setInterval(updateReportCounts, 1000 * 60 * 60);
updateReportCounts();
<commit_msg>Fix rendering of error messages<commit_after>// boilerplate includes
var config = require("../config/config"),
    helpers = require("./helpers"),
    elasticsearch = require("elasticsearch"),
    es = new elasticsearch.Client({
      host: config.elasticsearch,
      log: 'debug'
    });

module.exports = {

  // The homepage. A temporary search page.
  index: function(req, res) {
    res.render("index.html", {
      reportCount: reportCount,
      inspector: null
    });
  },

  // search/results
  reports: function(req, res) {
    var query;
    if (req.query.query) {
      query = req.query.query;
      if (query.charAt(0) != "\"" || query.charAt(query.length-1) != "\"")
        query = "\"" + query + "\"";
    }
    else
      query = "*";

    var inspector = req.query.inspector || null;
    var page = req.query.page || 1;

    search(query, inspector, page).then(function(results) {
      res.render("reports.html", {
        reportCount: reportCount,
        results: results,
        query: req.query.query,
        inspector: inspector,
        page: page
      });
    }, function(err) {
      console.log("Noooo!");
      res.status(500);
      res.render("reports.html", {
        reportCount: reportCount,
        results: null,
        query: null,
        inspector: inspector,
        page: null
      });
    });
  },

  reports_xml: function(req, res) {
    var query;
    if (req.query.query) {
      query = req.query.query;
      if (query.charAt(0) != "\"" || query.charAt(query.length-1) != "\"")
        query = "\"" + query + "\"";
    }
    else
      query = "*";

    var inspector = req.query.inspector || null;
    var page = req.query.page || 1;

    search(query, inspector, page).then(function(results) {
      res.type("atom");
      res.render("reports.xml.ejs", {
        results: results,
        query: req.query.query,
        inspector: inspector,
        page: page,
        self_url: req.url
      });
    }, function(err) {
      console.log("Noooo!");
      res.status(500);
      res.type("text");
      res.send("Server error");
    });
  },

  inspectors: function(req, res) {
    res.render("inspectors.html", {
      reportCount: reportCount,
      inspectorReportCounts: inspectorReportCounts
    });
  },

  inspector: function(req, res) {
    var metadata = helpers.inspector_info(req.params.inspector);
    if (metadata) {
      var inspectorReportCount;
      if (inspectorReportCounts) {
        inspectorReportCount = inspectorReportCounts[req.params.inspector] || 0;
      } else {
        inspectorReportCount = null;
      }
      search("*", req.params.inspector, 1).then(function(results) {
        res.render("inspector.html", {
          reportCount: reportCount,
          inspector: req.params.inspector,
          metadata: metadata,
          inspectorReportCount: inspectorReportCount,
          results: results
        });
      }, function(err) {
        console.log("Noooo!");
        res.render("inspector.html", {
          reportCount: reportCount,
          inspector: req.params.inspector,
          metadata: metadata,
          inspectorReportCount: inspectorReportCount,
          results: []
        });
      });
    } else {
      res.status(404);
      res.render("inspector.html", {
        reportCount: reportCount,
        metadata: null
      });
    }
  },

  report: function(req, res) {
    get(req.params.inspector, req.params.report_id).then(function(result) {
      res.render("report.html", {
        reportCount: reportCount,
        report: result._source
      });
    }, function(err) {
      console.log("Nooooo! " + err);
      res.status(500);
      res.render("report.html", {
        reportCount: reportCount,
        report: null
      });
    });
  }

};

function get(inspector, report_id) {
  return es.get({
    index: 'oversight',
    type: 'reports',
    id: inspector + '-' + report_id
  });
}

function search(query, inspector, page) {
  var size = 10;
  var from = (page - 1) * size;
  var body = {
    "from": from,
    "size": size,
    "query": {
      "filtered": {
        "query": {
          "query_string": {
            "query": query,
            "default_operator": "AND",
            "use_dis_max": true,
            "fields": ["text", "title", "summary"]
          }
        }
      }
    },
    "sort": [{
      "published_on": "desc"
    }],
    "highlight": {
      "encoder": "html",
      "pre_tags": [""],
      "post_tags": [""],
      "fields": {
        "*": {}
      },
      "order": "score",
      "fragment_size": 500
    },
    "_source": ["report_id", "year", "inspector", "agency", "title", "agency_name", "url", "landing_url", "inspector_url", "published_on", "type", "file_type"]
  };

  if (inspector) {
    body.query.filtered.filter = {
      "term": {
        "inspector": inspector
      }
    };
  }

  return es.search({
    index: 'oversight',
    type: 'reports',
    body: body
  });
}

var reportCount = null;
var inspectorReportCounts = null;

function updateReportCounts() {
  es.count({
    index: "oversight",
    type: "reports"
  }).then(function(result) {
    reportCount = result.count;
  }, function(err) {
    console.log("Nooooo! " + err);
    reportCount = null;
  });
  es.search({
    index: "oversight",
    type: "reports",
    searchType: "count",
    body: {
      aggregations: {
        inspector_agg: {
          terms: {
            field: "inspector",
            size: 0
          }
        }
      }
    }
  }).then(function(result) {
    var buckets = result.aggregations.inspector_agg.buckets;
    inspectorReportCounts = {};
    for (var i = 0; i < buckets.length; i++) {
      inspectorReportCounts[buckets[i].key] = buckets[i].doc_count;
    }
  }, function(err) {
    console.log("Nooooo! " + err);
    inspectorReportCounts = null;
  });
}

setInterval(updateReportCounts, 1000 * 60 * 60);
updateReportCounts();
<|endoftext|>


<commit_before>(function(){
  'use strict';
  var tree = require('no-promise-dir-tree');
  var dir = process.cwd();

  console.log(dir);
  tree(dir, function(err, result){
    console.log(result);
  });

})();
<commit_msg>:fried_shrimp: use new walker<commit_after>(function(){
  'use strict';
  var tree = require('./walker');
  var dir = process.cwd();
  var output = '';

  var parseElement = function(element) {

  };
  tree(dir, function(err, result){

  });

})();
<|endoftext|>


<commit_before>var server = require("./server");
var router = require("./router");
var requestHandlers = require("./requestHandlers");

var handle = {};
// requests
handle["/"] = requestHandlers.start;
handle["/addissue"] = requestHandlers.addissue;
handle["/addissue/"] = requestHandlers.addissue;
handle["/comment"] = requestHandlers.comment;
handle["/comment/"] = requestHandlers.comment;
handle["/id"] = requestHandlers.id;
handle["/id/"] = requestHandlers.id;
handle["/issue"] = requestHandlers.issue;
handle["/issue/"] = requestHandlers.issue;
handle["/start"] = requestHandlers.start;
handle["/start/"] = requestHandlers.start;
handle["/submit"] = requestHandlers.submit;
handle["/submit/"] = requestHandlers.submit;
handle["/template"] = requestHandlers.template;
handle["/template/"] = requestHandlers.template;

//view requests
handle["/sciencelocal"] = requestHandlers.sciencelocal;
handle["/sciencelocal/"] = requestHandlers.sciencelocal;
handle["/scienceregional"] = requestHandlers.scienceregional;
handle["/scienceregional/"] = requestHandlers.scienceregional;
handle["/sciencenational"] = requestHandlers.sciencenational;
handle["/sciencenational/"] = requestHandlers.sciencenational;
handle["/scienceglobal"] = requestHandlers.scienceglobal;
handle["/scienceglobal/"] = requestHandlers.scienceglobal;
handle["/politicslocal"] = requestHandlers.politicslocal;
handle["/politicslocal/"] = requestHandlers.politicslocal;
handle["/politicsregional"] = requestHandlers.politicsregional;
handle["/politicsregional/"] = requestHandlers.politicsregional;
handle["/politicsnational"] = requestHandlers.politicsnational;
handle["/politicsnational/"] = requestHandlers.politicsnational;
handle["/politicsglobal"] = requestHandlers.politicsglobal;
handle["/politicsglobal/"] = requestHandlers.politicsglobal;
handle["/lifelocal"] = requestHandlers.lifelocal;
handle["/lifelocal/"] = requestHandlers.lifelocal;
handle["/liferegional"] = requestHandlers.liferegional;
handle["/liferegional/"] = requestHandlers.liferegional;
handle["/lifenational"] = requestHandlers.lifenational;
handle["/lifenational/"] = requestHandlers.lifenational;
handle["/lifeglobal"] = requestHandlers.lifeglobal;
handle["/lifeglobal/"] = requestHandlers.lifeglobal;
handle["/otherlocal"] = requestHandlers.otherlocal;
handle["/otherlocal/"] = requestHandlers.otherlocal;
handle["/otherregional"] = requestHandlers.otherregional;
handle["/otherregional/"] = requestHandlers.otherregional;
handle["/othernational"] = requestHandlers.othernational;
handle["/othernational/"] = requestHandlers.othernational;
handle["/otherglobal"] = requestHandlers.otherglobal;
handle["/otherglobal/"] = requestHandlers.otherglobal;

server.start(router.route, handle);
<commit_msg>added /getcomments/<commit_after>var server = require("./server");
var router = require("./router");
var requestHandlers = require("./requestHandlers");

var handle = {};
// requests
handle["/"] = requestHandlers.start;
handle["/addissue"] = requestHandlers.addissue;
handle["/addissue/"] = requestHandlers.addissue;
handle["/comment"] = requestHandlers.comment;
handle["/comment/"] = requestHandlers.comment;
handle["/id"] = requestHandlers.id;
handle["/id/"] = requestHandlers.id;
handle["/issue"] = requestHandlers.issue;
handle["/issue/"] = requestHandlers.issue;
handle["/getcomments"] = requestHandlers.getcomments;
handle["/getcomments/"] = requestHandlers.getcomments;
handle["/start"] = requestHandlers.start;
handle["/start/"] = requestHandlers.start;
handle["/submit"] = requestHandlers.submit;
handle["/submit/"] = requestHandlers.submit;
handle["/template"] = requestHandlers.template;
handle["/template/"] = requestHandlers.template;

//view requests
handle["/sciencelocal"] = requestHandlers.sciencelocal;
handle["/sciencelocal/"] = requestHandlers.sciencelocal;
handle["/scienceregional"] = requestHandlers.scienceregional;
handle["/scienceregional/"] = requestHandlers.scienceregional;
handle["/sciencenational"] = requestHandlers.sciencenational;
handle["/sciencenational/"] = requestHandlers.sciencenational;
handle["/scienceglobal"] = requestHandlers.scienceglobal;
handle["/scienceglobal/"] = requestHandlers.scienceglobal;
handle["/politicslocal"] = requestHandlers.politicslocal;
handle["/politicslocal/"] = requestHandlers.politicslocal;
handle["/politicsregional"] = requestHandlers.politicsregional;
handle["/politicsregional/"] = requestHandlers.politicsregional;
handle["/politicsnational"] = requestHandlers.politicsnational;
handle["/politicsnational/"] = requestHandlers.politicsnational;
handle["/politicsglobal"] = requestHandlers.politicsglobal;
handle["/politicsglobal/"] = requestHandlers.politicsglobal;
handle["/lifelocal"] = requestHandlers.lifelocal;
handle["/lifelocal/"] = requestHandlers.lifelocal;
handle["/liferegional"] = requestHandlers.liferegional;
handle["/liferegional/"] = requestHandlers.liferegional;
handle["/lifenational"] = requestHandlers.lifenational;
handle["/lifenational/"] = requestHandlers.lifenational;
handle["/lifeglobal"] = requestHandlers.lifeglobal;
handle["/lifeglobal/"] = requestHandlers.lifeglobal;
handle["/otherlocal"] = requestHandlers.otherlocal;
handle["/otherlocal/"] = requestHandlers.otherlocal;
handle["/otherregional"] = requestHandlers.otherregional;
handle["/otherregional/"] = requestHandlers.otherregional;
handle["/othernational"] = requestHandlers.othernational;
handle["/othernational/"] = requestHandlers.othernational;
handle["/otherglobal"] = requestHandlers.otherglobal;
handle["/otherglobal/"] = requestHandlers.otherglobal;

server.start(router.route, handle);
<|endoftext|>