<commit_before>var Post = require('../../models/post');
function startDateFromYear(year) {
  return Date.UTC(year, 8, 1);
}
function endDateFromYear(year) {
  return Date.UTC(year, 10, 30);
}
var thisYear = (new Date()).getFullYear();

module.exports = function (tableSvc, azure, TABLE_NAME) {
  var entityGenerator = azure.TableUtilities.entityGenerator;
  return {
    list: function (request, reply) {
      var ttl = 1;
      var year = request.query.year ? parseInt(request.query.year, 10) : thisYear;
      if (isNaN(year)) { year = thisYear; }
      var start = startDateFromYear(year);
      var end = endDateFromYear(year);

      var query = new azure.TableQuery().where('PartitionKey eq ?', 'post');
      if (request.query.limit) {
        query.top(request.query.limit);
      }
      // you can either search for a link or just page by date
      if (request.query.link) {
        query.and('link eq ?', request.query.link);
      } else if(request.query.url) {
        query.and('url eq ?', request.query.url);
      } else {
        // cache these results for an hour
        ttl = 60 * 60 * 1000;
        query.and('published le ' + end + 'l').and('published ge ' + start + 'l');
      }

      var continuationToken = null;
      var results = [];
      function get() {
        tableSvc.queryEntities(TABLE_NAME, query, continuationToken, function(error, result) {
          if (error) {
            return reply(error);
          }

          result.entries.map(function (entity) {
            var post = Post.fromEntity(entity);
            results.push(post.toJSON());
          });

          if (result.continuationToken) {
            continuationToken = result.continuationToken();
            get();
          } else {
            reply(results).ttl(ttl);
          }
        });
      }
      get();
    },
    create: function (request, reply) {
      var post = new Post(request.payload);
      tableSvc.insertEntity(
        TABLE_NAME,
        post.toEntity(entityGenerator),
        function (error, result) {
          if (error) {
            return reply(error);
          }
          reply(post.toJSON()).code(201).etag(result['.metadata'].etag);
      });
    },
    get: function (request, reply) {
      var id = request.params.id;
      reply(new Error("Not implemented yet GET:" + id)).takeover();
    },
    update: function (request, reply) {
      var id = request.params.id;
      reply(new Error("Not implemented yet UPDATE:" + id)).takeover();
    }
  };
};<commit_msg>limit recent posts to 200<commit_after>var Post = require('../../models/post');
function startDateFromYear(year) {
  return Date.UTC(year, 8, 1);
}
function endDateFromYear(year) {
  return Date.UTC(year, 10, 30);
}
var thisYear = (new Date()).getFullYear();

module.exports = function (tableSvc, azure, TABLE_NAME) {
  var entityGenerator = azure.TableUtilities.entityGenerator;
  return {
    list: function (request, reply) {
      var ttl = 1;
      var year = request.query.year ? parseInt(request.query.year, 10) : thisYear;
      if (isNaN(year)) { year = thisYear; }
      var start = startDateFromYear(year);
      var end = endDateFromYear(year);

      var query = new azure.TableQuery().where('PartitionKey eq ?', 'post');
      if (request.query.limit) {
        query.top(request.query.limit);
      }
      // you can either search for a link or just page by date
      if (request.query.link) {
        query.and('link eq ?', request.query.link);
      } else if(request.query.url) {
        query.and('url eq ?', request.query.url);
      } else {
        // cache these results for an hour
        ttl = 60 * 60 * 1000;
        query.and('published le ' + end + 'l').and('published ge ' + start + 'l');
      }

      var continuationToken = null;
      var results = [];
      function get() {
        tableSvc.queryEntities(TABLE_NAME, query, continuationToken, function(error, result) {
          if (error) {
            return reply(error);
          }

          result.entries.map(function (entity) {
            var post = Post.fromEntity(entity);
            results.push(post.toJSON());
          });

          if (results.length < 200 && result.continuationToken) {
            continuationToken = result.continuationToken();
            get();
          } else {
            reply(results).ttl(ttl);
          }
        });
      }
      get();
    },
    create: function (request, reply) {
      var post = new Post(request.payload);
      tableSvc.insertEntity(
        TABLE_NAME,
        post.toEntity(entityGenerator),
        function (error, result) {
          if (error) {
            return reply(error);
          }
          reply(post.toJSON()).code(201).etag(result['.metadata'].etag);
      });
    },
    get: function (request, reply) {
      var id = request.params.id;
      reply(new Error("Not implemented yet GET:" + id)).takeover();
    },
    update: function (request, reply) {
      var id = request.params.id;
      reply(new Error("Not implemented yet UPDATE:" + id)).takeover();
    }
  };
};<|endoftext|>


<commit_before><commit_msg>documented a known bug with ngRoute and active tab display<commit_after><|endoftext|>


<commit_before><commit_msg>20160906-1002<commit_after><|endoftext|>


<commit_before><commit_msg>fixed 3 lab<commit_after><|endoftext|>


<commit_before>/*eslint-env browser */
/*globals code m materialComponentsMithril*/

var button = materialComponentsMithril.button;

m.mount(document.querySelector("#buttons"), {
    view: () => [
        m(button, "Flat"),
        m(code, 'm(button, "Flat")'),
        m(button, {disabled: true}, "Disabled"),
        m(code, 'm(button, {disabled: true}, "Disabled")'),
        m(button, {mdcButtonRaised: true}, "Raised"),
        m(code, 'm(button, {mdcButtonRaised: true}, "Raised")'),
        m(button, {disabled: true, mdcButtonRaised: true}, "Disabled and Raised"),
        m(code, 'm(button, {disabled: true, mdcButtonRaised: true}, "Disabled and Raised")'),
        m(button, {mdcButtonDense: true}, "Dense"),
        m(code, 'm(button, {mdcButtonDense: true}, "Dense")'),
        m(button, {mdcButtonDense: true, disabled: true}, "Dense and Disabled"),
        m(code, 'm(button, {mdcButtonDense: true, disabled: true}, "Dense and Disabled")'),
        m(button, {mdcButtonDense: true, mdcButtonRaised: true}, "Dense and Raised"),
        m(code, 'm(button, {mdcButtonDense: true, mdcButtonRaised: true}, "Dense and Raised")'),
        m(button, {mdcButtonDense: true, disabled: true, mdcButtonRaised: true}, "Dense, Disabled and Raised"),
        m(code, 'm(button, {mdcButtonDense: true, disabled: true, mdcButtonRaised: true}, "Dense, Disabled and Raised")'),
        m(button, {mdcButtonCompact: true}, "Compact"),
        m(code, 'm(button, {mdcButtonCompact: true}, "Compact")'),
        m(button, {mdcButtonCompact: true, disabled: true}, "Compact and Disabled"),
        m(code, 'm(button, {mdcButtonCompact: true, disabled: true}, "Compact and Disabled")'),
        m(button, {mdcButtonCompact: true, mdcButtonRaised: true}, "Compact and Raised"),
        m(code, 'm(button, {mdcButtonCompact: true, mdcButtonRaised: true}, "Compact and Raised")'),
        m(button, {mdcButtonCompact: true, disabled: true, mdcButtonRaised: true}, "Compact, Disabled and Raised"),
        m(code, 'm(button, {mdcButtonCompact: true, disabled: true, mdcButtonRaised: true}, "Compact, Disabled and Raised")'),
        m(button, {mdcButtonPrimary: true}, "Primary colored"),
        m(code, 'm(button, {mdcButtonPrimary: true}, "Primary colored")'),
        m(button, {mdcButtonPrimary: true, disabled: true}, "Primary colored and Disabled"),
        m(code, 'm(button, {mdcButtonPrimary: true, disabled: true}, "Primary colored and Disabled")'),
        m(button, {mdcButtonPrimary: true, mdcButtonRaised: true}, "Primary colored and Raised"),
        m(code, 'm(button, {mdcButtonPrimary: true, mdcButtonRaised: true}, "Primary colored and Raised")'),
        m(button, {mdcButtonPrimary: true, disabled: true, mdcButtonRaised: true}, "Primary colored, Disabled and Raised"),
        m(code, 'm(button, {mdcButtonPrimary: true, disabled: true, mdcButtonRaised: true}, "Primary colored, Disabled and Raised")'),
        m(button, {mdcButtonAccent: true}, "Accent colored"),
        m(code, 'm(button, {mdcButtonAccent: true}, "Accent colored")'),
        m(button, {mdcButtonAccent: true, disabled: true}, "Accent colored and Disabled"),
        m(code, 'm(button, {mdcButtonAccent: true, disabled: true}, "Accent colored and Disabled")'),
        m(button, {mdcButtonAccent: true, mdcButtonRaised: true}, "Accent colored and Raised"),
        m(code, 'm(button, {mdcButtonAccent: true, mdcButtonRaised: true}, "Accent colored and Raised")'),
        m(button, {mdcButtonAccent: true, disabled: true, mdcButtonRaised: true}, "Accent colored, Disabled and Raised"),
        m(code, 'm(button, {mdcButtonAccent: true, disabled: true, mdcButtonRaised: true}, "Accent colored, Disabled and Raised")'),
        m(button, {tagName: "div"}, "Div"),
        m(code, 'm(button, {tagName: "div"}, "Div")'),
        m(button, {tagName: "a", href: "#"}, "Link"),
        m(code, 'm(button, {tagName: "a", href: "#"}, "Link")')
    ]
});<commit_msg>Not to use single quotes.<commit_after>/*eslint-env browser */
/*globals code m materialComponentsMithril*/

var button = materialComponentsMithril.button;

m.mount(document.querySelector("#buttons"), {
    view: () => [
        m(button, "Flat"),
        m(code, `m(button, "Flat")`),
        m(button, {disabled: true}, "Disabled"),
        m(code, `m(button, {disabled: true}, "Disabled")`),
        m(button, {mdcButtonRaised: true}, "Raised"),
        m(code, `m(button, {mdcButtonRaised: true}, "Raised")`),
        m(button, {disabled: true, mdcButtonRaised: true}, "Disabled and Raised"),
        m(code, `m(button, {disabled: true, mdcButtonRaised: true}, "Disabled and Raised")`),
        m(button, {mdcButtonDense: true}, "Dense"),
        m(code, `m(button, {mdcButtonDense: true}, "Dense")`),
        m(button, {mdcButtonDense: true, disabled: true}, "Dense and Disabled"),
        m(code, `m(button, {mdcButtonDense: true, disabled: true}, "Dense and Disabled")`),
        m(button, {mdcButtonDense: true, mdcButtonRaised: true}, "Dense and Raised"),
        m(code, `m(button, {mdcButtonDense: true, mdcButtonRaised: true}, "Dense and Raised")`),
        m(button, {mdcButtonDense: true, disabled: true, mdcButtonRaised: true}, "Dense, Disabled and Raised"),
        m(code, `m(button, {mdcButtonDense: true, disabled: true, mdcButtonRaised: true}, "Dense, Disabled and Raised")`),
        m(button, {mdcButtonCompact: true}, "Compact"),
        m(code, `m(button, {mdcButtonCompact: true}, "Compact")`),
        m(button, {mdcButtonCompact: true, disabled: true}, "Compact and Disabled"),
        m(code, `m(button, {mdcButtonCompact: true, disabled: true}, "Compact and Disabled")`),
        m(button, {mdcButtonCompact: true, mdcButtonRaised: true}, "Compact and Raised"),
        m(code, `m(button, {mdcButtonCompact: true, mdcButtonRaised: true}, "Compact and Raised")`),
        m(button, {mdcButtonCompact: true, disabled: true, mdcButtonRaised: true}, "Compact, Disabled and Raised"),
        m(code, `m(button, {mdcButtonCompact: true, disabled: true, mdcButtonRaised: true}, "Compact, Disabled and Raised")`),
        m(button, {mdcButtonPrimary: true}, "Primary colored"),
        m(code, `m(button, {mdcButtonPrimary: true}, "Primary colored")`),
        m(button, {mdcButtonPrimary: true, disabled: true}, "Primary colored and Disabled"),
        m(code, `m(button, {mdcButtonPrimary: true, disabled: true}, "Primary colored and Disabled")`),
        m(button, {mdcButtonPrimary: true, mdcButtonRaised: true}, "Primary colored and Raised"),
        m(code, `m(button, {mdcButtonPrimary: true, mdcButtonRaised: true}, "Primary colored and Raised")`),
        m(button, {mdcButtonPrimary: true, disabled: true, mdcButtonRaised: true}, "Primary colored, Disabled and Raised"),
        m(code, `m(button, {mdcButtonPrimary: true, disabled: true, mdcButtonRaised: true}, "Primary colored, Disabled and Raised")`),
        m(button, {mdcButtonAccent: true}, "Accent colored"),
        m(code, `m(button, {mdcButtonAccent: true}, "Accent colored")`),
        m(button, {mdcButtonAccent: true, disabled: true}, "Accent colored and Disabled"),
        m(code, `m(button, {mdcButtonAccent: true, disabled: true}, "Accent colored and Disabled")`),
        m(button, {mdcButtonAccent: true, mdcButtonRaised: true}, "Accent colored and Raised"),
        m(code, `m(button, {mdcButtonAccent: true, mdcButtonRaised: true}, "Accent colored and Raised")`),
        m(button, {mdcButtonAccent: true, disabled: true, mdcButtonRaised: true}, "Accent colored, Disabled and Raised"),
        m(code, `m(button, {mdcButtonAccent: true, disabled: true, mdcButtonRaised: true}, "Accent colored, Disabled and Raised")`),
        m(button, {tagName: "div"}, "Div"),
        m(code, `m(button, {tagName: "div"}, "Div")`),
        m(button, {tagName: "a", href: "#"}, "Link"),
        m(code, `m(button, {tagName: "a", href: "#"}, "Link")`)
    ]
});<|endoftext|>


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

var cluster = require('cluster')
  , numCPUs = require('os').cpus().length
  , express = require('express')
  , Sequelize = require('sequelize')
  , mongoose = require('mongoose')
  , conn = mongoose.connect('mongodb://localhost/hello_world')
  , async = require('async');

// Middleware
var bodyParser = require('body-parser')
  , methodOverride = require('method-override')
  , errorHandler = require('errorhandler');

var Schema = mongoose.Schema
  , ObjectId = Schema.ObjectId;

var WorldSchema = new mongoose.Schema({
    id          : Number,
    randomNumber: Number
  }, {
    collection: 'world'
  }),
  MWorld = conn.model('World', WorldSchema);

var sequelize = new Sequelize('hello_world', 'benchmarkdbuser', 'benchmarkdbpass', {
  host: 'localhost',
  dialect: 'mysql',
  logging: false
});

var World = sequelize.define('World', {
  id: {
    type: 'Sequelize.INTEGER'
  },
  randomNumber: {
    type: 'Sequelize.INTEGER'
  }
}, {
  timestamps: false,
  freezeTableName: true
});
var Fortune = sequelize.define('Fortune', {
  id: {
    type: 'Sequelize.INTEGER'
  },
  message: {
    type: 'Sequelize.STRING'
  }
}, {
  timestamps: false,
  freezeTableName: true
});

if (cluster.isMaster) {
  // Fork workers.
  for (var i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', function(worker, code, signal) {
    console.log('worker ' + worker.pid + ' died');
  });
} else {
  var app = module.exports = express();

  // Configuration
  // https://github.com/expressjs/method-override#custom-logic
  app.use(bodyParser.urlencoded({extended: true}));
  app.use(methodOverride(function(req, res){
    if (req.body && typeof req.body === 'object' && '_method' in req.body) {
      // look in urlencoded POST bodies and delete it
      var method = req.body._method
      delete req.body._method
      return method
    }
  }));

  // Set headers for all routes
  app.use(function(req, res, next) {
    res.setHeader("Server", "Express");
    return next();
  });

  app.set('view engine', 'jade');
  app.set('views', __dirname + '/views');

  // Check Node env.
  var env = process.env.NODE_ENV || 'development';
  if ('development' == env) {
    app.use(errorHandler({ dumpExceptions: true, showStack: true }));
  }
  if ('production' == env) {
    app.use(errorHandler());
  }

  // Routes

  app.get('/json', function(req, res) {
    res.send({ message: 'Hello, World!' });
  });

  app.get('/plaintext', function(req, res) {
    res.header('Content-Type', 'text/plain').send('Hello, World!');
  });

  app.get('/mongoose', function(req, res) {
    var queries = isNaN(req.query.queries) ? 1 : parseInt(req.query.queries, 10)
      , queryFunctions = [];

    queries = Math.min(Math.max(queries, 1), 500);

    for (var i = 1; i <= queries; i++ ) {
      queryFunctions.push(function(callback) {
        MWorld.findOne({ id: (Math.floor(Math.random() * 10000) + 1) }).exec(callback);
      });
    }

    async.parallel(queryFunctions, function(err, results) {
      if (!req.query.queries) {
        results = results[0];
      }
      res.send(results);
    });
  });

  app.get('/mysql-orm', function(req, res) {
    var queriesRaw = parseInt(req.query.queries, 10)
      , queries = isNaN(queriesRaw) ? 1 : queriesRaw
      , queryFunctions = [];

    queries = Math.min(Math.max(queries, 1), 500);

    for (var i = 1; i <= queries; i++ ) {
      queryFunctions.push(function(callback) {
        World.findOne({
          where: {
            id: Math.floor(Math.random() * 10000) + 1}
          }
        ).then(function(world) {
            callback(null, world);
        });
      });
    }

    async.parallel(queryFunctions, function(err, results) {
      if (req.query.queries == undefined) {
        results = results[0];
      }
      res.setHeader("Content-Type", "application/json");
      res.send(results);
    });
  });

  app.get('/mongoose-fortune', function(req, res) {
    MFortune.find({}, function(err, fortunes) {
      var newFortune = {id: 0, message: "Additional fortune added at request time."};
      fortunes.push(newFortune);
      fortunes.sort(function (a, b) {
        return (a.message < b.message) ? -1 : 1;
      });

      res.render('fortunes', {fortunes: fortunes});
    });
  });

  app.get('/mysql-orm-fortune', function(req, res) {
    Fortune.findAll().then(function (fortunes) {
      var newFortune = {id: 0, message: "Additional fortune added at request time."};
      fortunes.push(newFortune);
      fortunes.sort(function (a, b) {
        return (a.message < b.message) ? -1 : 1;
      });

      res.render('fortunes', {fortunes: fortunes});
    });
  });

  app.get('/mongoose-update', function(req, res) {
    var queries = isNaN(req.query.queries) ? 1 : parseInt(req.query.queries, 10)
      , selectFunctions = [];

    queries = Math.min(queries, 500);

    for (var i = 1; i <= queries; i++ ) {
      selectFunctions.push(function(callback) {
        MWorld.findOne({ id: Math.floor(Math.random() * 10000) + 1 }).exec(callback);
      });
    }

    async.parallel(selectFunctions, function(err, worlds) {
      var updateFunctions = [];

      for (var i = 0; i < queries; i++) {
        (function(i){
          updateFunctions.push(function(callback){
            worlds[i].randomNumber = Math.ceil(Math.random() * 10000);
            MWorld.update({
              id: worlds[i]
            }, {
              randomNumber: worlds[i].randomNumber
            }, callback);
          });
        })(i);
      }

      async.parallel(updateFunctions, function(err, updates) {
        res.send(worlds);
      });
    });
  });

  app.get('/mysql-orm-update', function(req, res) {
    var queries = isNaN(req.query.queries) ? 1 : parseInt(req.query.queries, 10)
      , selectFunctions = [];

    queries = Math.max(Math.min(queries, 500), 1);

    for (var i = 1; i <= queries; i++ ) {
      selectFunctions.push(function(callback) {
        World.findOne({
          where: {
            id: Math.floor(Math.random() * 10000) + 1}
          }
        ).then(function(world) {
          callback(null, world);
        });
      });
    }

    async.parallel(selectFunctions, function(err, worlds) {
      var updateFunctions = [];

      for (var i = 0; i < queries; i++) {
        (function(i){
          updateFunctions.push(function(callback){
            worlds[i].randomNumber = Math.ceil(Math.random() * 10000);
            worlds[i].save().then(callback());
          });
        })(i);
      }

      async.parallel(updateFunctions, function(err, updates) {
        res.send(worlds);
      });
    });

  });

  app.listen(8080);
}
<commit_msg>express fix<commit_after>
/**
 * Module dependencies.
 */

var cluster = require('cluster')
  , numCPUs = require('os').cpus().length
  , express = require('express')
  , Sequelize = require('sequelize')
  , mongoose = require('mongoose')
  , conn = mongoose.connect('mongodb://localhost/hello_world')
  , async = require('async');

// Middleware
var bodyParser = require('body-parser')
  , methodOverride = require('method-override')
  , errorHandler = require('errorhandler');

var Schema = mongoose.Schema
  , ObjectId = Schema.ObjectId;

var WorldSchema = new mongoose.Schema({
    id          : Number,
    randomNumber: Number
  }, {
    collection: 'world'
  }),
  MWorld = conn.model('World', WorldSchema);

var FortuneSchema = new mongoose.Schema({
    id          : Number,
    message     : String
  }, {
    collection: 'fortune'
  }),
  MFortune = conn.model('Fortune', FortuneSchema);

var sequelize = new Sequelize('hello_world', 'benchmarkdbuser', 'benchmarkdbpass', {
  host: 'localhost',
  dialect: 'mysql',
  logging: false
});

var World = sequelize.define('World', {
  id: {
    type: 'Sequelize.INTEGER'
  },
  randomNumber: {
    type: 'Sequelize.INTEGER'
  }
}, {
  timestamps: false,
  freezeTableName: true
});
var Fortune = sequelize.define('Fortune', {
  id: {
    type: 'Sequelize.INTEGER'
  },
  message: {
    type: 'Sequelize.STRING'
  }
}, {
  timestamps: false,
  freezeTableName: true
});

if (cluster.isMaster) {
  // Fork workers.
  for (var i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', function(worker, code, signal) {
    console.log('worker ' + worker.pid + ' died');
  });
} else {
  var app = module.exports = express();

  // Configuration
  // https://github.com/expressjs/method-override#custom-logic
  app.use(bodyParser.urlencoded({extended: true}));
  app.use(methodOverride(function(req, res){
    if (req.body && typeof req.body === 'object' && '_method' in req.body) {
      // look in urlencoded POST bodies and delete it
      var method = req.body._method
      delete req.body._method
      return method
    }
  }));

  // Set headers for all routes
  app.use(function(req, res, next) {
    res.setHeader("Server", "Express");
    return next();
  });

  app.set('view engine', 'jade');
  app.set('views', __dirname + '/views');

  // Check Node env.
  var env = process.env.NODE_ENV || 'development';
  if ('development' == env) {
    app.use(errorHandler({ dumpExceptions: true, showStack: true }));
  }
  if ('production' == env) {
    app.use(errorHandler());
  }

  // Routes

  app.get('/json', function(req, res) {
    res.send({ message: 'Hello, World!' });
  });

  app.get('/plaintext', function(req, res) {
    res.header('Content-Type', 'text/plain').send('Hello, World!');
  });

  app.get('/mongoose', function(req, res) {
    var queries = isNaN(req.query.queries) ? 1 : parseInt(req.query.queries, 10)
      , queryFunctions = [];

    queries = Math.min(Math.max(queries, 1), 500);

    for (var i = 1; i <= queries; i++ ) {
      queryFunctions.push(function(callback) {
        MWorld.findOne({ id: (Math.floor(Math.random() * 10000) + 1) }).exec(callback);
      });
    }

    async.parallel(queryFunctions, function(err, results) {
      if (!req.query.queries) {
        results = results[0];
      }
      res.send(results);
    });
  });

  app.get('/mysql-orm', function(req, res) {
    var queriesRaw = parseInt(req.query.queries, 10)
      , queries = isNaN(queriesRaw) ? 1 : queriesRaw
      , queryFunctions = [];

    queries = Math.min(Math.max(queries, 1), 500);

    for (var i = 1; i <= queries; i++ ) {
      queryFunctions.push(function(callback) {
        World.findOne({
          where: {
            id: Math.floor(Math.random() * 10000) + 1}
          }
        ).then(function(world) {
            callback(null, world);
        });
      });
    }

    async.parallel(queryFunctions, function(err, results) {
      if (req.query.queries == undefined) {
        results = results[0];
      }
      res.setHeader("Content-Type", "application/json");
      res.send(results);
    });
  });

  app.get('/mongoose-fortune', function(req, res) {
    MFortune.find({}, function(err, fortunes) {
      var newFortune = {id: 0, message: "Additional fortune added at request time."};
      fortunes.push(newFortune);
      fortunes.sort(function (a, b) {
        return (a.message < b.message) ? -1 : 1;
      });

      res.render('fortunes', {fortunes: fortunes});
    });
  });

  app.get('/mysql-orm-fortune', function(req, res) {
    Fortune.findAll().then(function (fortunes) {
      var newFortune = {id: 0, message: "Additional fortune added at request time."};
      fortunes.push(newFortune);
      fortunes.sort(function (a, b) {
        return (a.message < b.message) ? -1 : 1;
      });

      res.render('fortunes', {fortunes: fortunes});
    });
  });

  app.get('/mongoose-update', function(req, res) {
    var queries = isNaN(req.query.queries) ? 1 : parseInt(req.query.queries, 10)
      , selectFunctions = [];

    queries = Math.min(queries, 500);

    for (var i = 1; i <= queries; i++ ) {
      selectFunctions.push(function(callback) {
        MWorld.findOne({ id: Math.floor(Math.random() * 10000) + 1 }).exec(callback);
      });
    }

    async.parallel(selectFunctions, function(err, worlds) {
      var updateFunctions = [];

      for (var i = 0; i < queries; i++) {
        (function(i){
          updateFunctions.push(function(callback){
            worlds[i].randomNumber = Math.ceil(Math.random() * 10000);
            MWorld.update({
              id: worlds[i]
            }, {
              randomNumber: worlds[i].randomNumber
            }, callback);
          });
        })(i);
      }

      async.parallel(updateFunctions, function(err, updates) {
        res.send(worlds);
      });
    });
  });

  app.get('/mysql-orm-update', function(req, res) {
    var queries = isNaN(req.query.queries) ? 1 : parseInt(req.query.queries, 10)
      , selectFunctions = [];

    queries = Math.max(Math.min(queries, 500), 1);

    for (var i = 1; i <= queries; i++ ) {
      selectFunctions.push(function(callback) {
        World.findOne({
          where: {
            id: Math.floor(Math.random() * 10000) + 1}
          }
        ).then(function(world) {
          callback(null, world);
        });
      });
    }

    async.parallel(selectFunctions, function(err, worlds) {
      var updateFunctions = [];

      for (var i = 0; i < queries; i++) {
        (function(i){
          updateFunctions.push(function(callback){
            worlds[i].randomNumber = Math.ceil(Math.random() * 10000);
            worlds[i].save().then(callback());
          });
        })(i);
      }

      async.parallel(updateFunctions, function(err, updates) {
        res.send(worlds);
      });
    });

  });

  app.listen(8080);
}
<|endoftext|>


<commit_before>// ==========================================================================
// Project:   SproutCore - JavaScript Application Framework
// Copyright: ©2006-2009 Sprout Systems, Inc. and contributors.
//            Portions ©2008-2009 Apple Inc. All rights reserved.
// License:   Licened under MIT license (see license.js)
// ==========================================================================

/**
  @class

  Displays a progress bar.  You can display both a defined and an
  indeterminate progressbar.  The progress bar itself is designed to be styled
  using CSS classes with the following structure:

  The outer can form the boundary of the bar while the inner will be adjusted
  to fit the percentage of the progress.

  Creating a ProgressView accepts a number of properties, for example:
  {
    value: 50,
    minimum: 0,
    maximum: 100,
    isIndeterminate: NO,
    isEnabled: YES
  }

  Default isEnabled value is YES.

  @extends SC.View
  @extends SC.Control
  @since SproutCore 1.0
*/
SC.ProgressView = SC.View.extend(SC.Control, {

  // ........................................
  // PROPERTIES
  //

  /**
    Bind this to the current value of the progress bar.  Note that by default
    an empty value will disable the progress bar and a multiple value will make
    it indeterminate.
  */
  value: 0.50,
  valueBindingDefault: SC.Binding.single().notEmpty(),

  /**
    The minimum value of the progress.
  */
  minimum: 0,
  minimumBindingDefault: SC.Binding.single().notEmpty(),

  /**
    Optionally specify the key used to extract the minimum progress value
    from the content object.  If this is set to null then the minimum value
    will not be derived from the content object.

    @property {String}
  */
  contentMinimumKey: null,

  /**
    The maximum value of the progress bar.
  */
  maximum: 1.0,
  maximumBindingDefault: SC.Binding.single().notEmpty(),

  /**
    The value of the progress inner offset range. Should be the same as width
    of image. Default it to 24

    @type Integer
  */
  offsetRange: 24,

  /**
    Optionally specify the key used to extract the maximum progress value
    from the content object.  If this is set to null then the maximum value
    will not be derived from the content object.

    @property {String}
  */
  contentMaximumKey: null,

  /**
    Set to true if the item in progress is indeterminate.  This may be
    overridden by the actual value.
    @returns {Boolean}
  */
  isIndeterminate: NO,
  isIndeterminateBindingDefault: SC.Binding.bool(),

  /**
    Set to YES when the process is currently running.  This will cause the
    progress bar to animate, especially if it is indeterminate.
  */
  isRunning: NO,
  isRunningBindingDefault: SC.Binding.bool(),

  /**
    Set to the matrix used for background image position for animation.
    [1st image y-location, offset, total number of images]
    @property {Array}
  */
  animatedBackgroundMatrix: [],

  /**
    Optionally specify the key used to extract the isIndeterminate value
    from the content object.  If this is set to null then the isIndeterminate
    value will not be derived from the content object.

    @property {String}
  */
  contentIsIndeterminateKey: null,

  // ........................................
  // STRUCTURE
  //

  classNames: 'sc-progress-view',

  // ........................................
  // INTERNAL SUPPORT
  //

  _backgroundOffset: 0,
  _currentBackground: 1,
  _nextBackground: 1,

  // start animating at the end of the init() method.  note that we call this
  // here because we want this to make sure this function is called anytime
  // the progress view is instantiated.
  init: function() {
    sc_super();
    this.animateProgressBar(); // start animating...
  },

  // start/stop running animation based on isRunning state.
  animateProgressBar: function() {
    if (this.get('isRunning') && this.get('isVisibleInWindow')) {
      this._animateProgressBar(500); // wait to start to avoid probs
    }
  }.observes('isRunning', 'isVisibleInWindow'),

  _animateProgressBar: function(delay) {
    if (delay===0) delay = 1000/30;
    if (this.get('isRunning') && this.get('isVisibleInWindow')) {
      this.displayDidChange();
      this.invokeLater(this._animateProgressBar, delay, 0);
    }
  },

  displayProperties: 'value minimum maximum isIndeterminate'.w(),

  render: function(context, firstTime) {

    var isIndeterminate = this.get('isIndeterminate');
    var isRunning = this.get('isRunning');
    var isEnabled = this.get('isEnabled');
    var offsetRange = this.get('offsetRange');

    var offset = (isIndeterminate && isRunning) ? (Math.floor(Date.now()/75)%offsetRange-offsetRange) : 0;

    // compute value for setting the width of the inner progress
    var value;
    if (!isEnabled) {
      value = "0%" ;
    } else if (isIndeterminate) {
      value = "120%";
    } else {
      var minimum = this.get('minimum') || 0.0;
      var maximum = this.get('maximum') || 1.0;
      value = this.get('value') || 0.0;
      value = (value - minimum) / (maximum - minimum);
      if (value > 1.0) value = 1.0;

      if(isNaN(value)) value = 0.0;
      // cannot be smaller then minimum
      if(value<minimum) value = 0.0;
      // cannot be larger then maximum
      if(value>maximum) value = 1.0;
      value = (value * 100) + "%";
    }

    var classNames = {
      'sc-indeterminate': isIndeterminate,
      'sc-empty': (value <= 0),
      'sc-complete': (value >= 100)
    };

    if(firstTime) {
      var classString = this._createClassNameString(classNames);
      context.push('
');
      context.push('

');
    }
    else {
      context.setClass(classNames);
      this.$('.sc-inner').css('width', value).css('left',offset);
      if (this.get('animatedBackgroundMatrix').length === 3 ) {
        this.$('.sc-inner').css('backgroundPosition', '0px -'+
        (this.get('animatedBackgroundMatrix')[0] +
        this.get('animatedBackgroundMatrix')[1]*this._currentBackground)+'px');
        if(this._currentBackground===this.get('animatedBackgroundMatrix')[2]-1
           || this._currentBackground===0)
          this._nextBackground *= -1;
        this._currentBackground += this._nextBackground;
      }
    }

  },

  contentPropertyDidChange: function(target, key) {
    var content = this.get('content');
    this.beginPropertyChanges()
      .updatePropertyFromContent('value', key, 'contentValueKey', content)
      .updatePropertyFromContent('minimum', key, 'contentMinimumKey', content)
      .updatePropertyFromContent('maximum', key, 'contentMaximumKey', content)
      .updatePropertyFromContent('isIndeterminate', key, 'contentIsIndeterminateKey', content)
    .endPropertyChanges();
  },

  _createClassNameString: function(classNames) {
    var classNameArray = [], key;
    for(key in classNames) {
      if(!classNames.hasOwnProperty(key)) continue;
      if(classNames[key]) classNameArray.push(key);
    }
    return classNameArray.join(" ");
  }

}) ;<commit_msg>Perf improvements for ProgressView<commit_after>// ==========================================================================
// Project:   SproutCore - JavaScript Application Framework
// Copyright: ©2006-2009 Sprout Systems, Inc. and contributors.
//            Portions ©2008-2009 Apple Inc. All rights reserved.
// License:   Licened under MIT license (see license.js)
// ==========================================================================

/**
  @class

  Displays a progress bar.  You can display both a defined and an
  indeterminate progressbar.  The progress bar itself is designed to be styled
  using CSS classes with the following structure:

  The outer can form the boundary of the bar while the inner will be adjusted
  to fit the percentage of the progress.

  Creating a ProgressView accepts a number of properties, for example:
  {
    value: 50,
    minimum: 0,
    maximum: 100,
    isIndeterminate: NO,
    isEnabled: YES
  }

  Default isEnabled value is YES.

  @extends SC.View
  @extends SC.Control
  @since SproutCore 1.0
*/
SC.ProgressView = SC.View.extend(SC.Control, {

  // ........................................
  // PROPERTIES
  //

  /**
    Bind this to the current value of the progress bar.  Note that by default
    an empty value will disable the progress bar and a multiple value will make
    it indeterminate.
  */
  value: 0.50,
  valueBindingDefault: SC.Binding.single().notEmpty(),

  /**
    The minimum value of the progress.
  */
  minimum: 0,
  minimumBindingDefault: SC.Binding.single().notEmpty(),

  /**
    Optionally specify the key used to extract the minimum progress value
    from the content object.  If this is set to null then the minimum value
    will not be derived from the content object.

    @property {String}
  */
  contentMinimumKey: null,

  /**
    The maximum value of the progress bar.
  */
  maximum: 1.0,
  maximumBindingDefault: SC.Binding.single().notEmpty(),

  /**
    The value of the progress inner offset range. Should be the same as width
    of image. Default it to 24

    @type Integer
  */
  offsetRange: 24,

  /**
    Optionally specify the key used to extract the maximum progress value
    from the content object.  If this is set to null then the maximum value
    will not be derived from the content object.

    @property {String}
  */
  contentMaximumKey: null,

  /**
    Set to true if the item in progress is indeterminate.  This may be
    overridden by the actual value.
    @returns {Boolean}
  */
  isIndeterminate: NO,
  isIndeterminateBindingDefault: SC.Binding.bool(),

  /**
    Set to YES when the process is currently running.  This will cause the
    progress bar to animate, especially if it is indeterminate.
  */
  isRunning: NO,
  isRunningBindingDefault: SC.Binding.bool(),

  /**
    Set to the matrix used for background image position for animation.
    [1st image y-location, offset, total number of images]
    @property {Array}
  */
  animatedBackgroundMatrix: [],

  /**
    Optionally specify the key used to extract the isIndeterminate value
    from the content object.  If this is set to null then the isIndeterminate
    value will not be derived from the content object.

    @property {String}
  */
  contentIsIndeterminateKey: null,

  // ........................................
  // STRUCTURE
  //

  classNames: 'sc-progress-view',

  // ........................................
  // INTERNAL SUPPORT
  //

  _backgroundOffset: 0,
  _currentBackground: 1,
  _nextBackground: 1,

  // start animating at the end of the init() method.  note that we call this
  // here because we want this to make sure this function is called anytime
  // the progress view is instantiated.
  init: function() {
    sc_super();
    this.animateProgressBar(); // start animating...
  },

  // start/stop running animation based on isRunning state.
  animateProgressBar: function() {
    if (this.get('isRunning') && this.get('isVisibleInWindow')) {
      this._animateProgressBar(500); // wait to start to avoid probs
    }
  }.observes('isRunning', 'isVisibleInWindow'),

  _animateProgressBar: function(delay) {
    if (delay===0) delay = 1000/30;
    if (this.get('isRunning') && this.get('isVisibleInWindow')) {
      this.displayDidChange();
      this.invokeLater(this._animateProgressBar, delay, 0);
    }
  },

  displayProperties: 'value minimum maximum isIndeterminate'.w(),

  render: function(context, firstTime) {
    var inner, animatedBackground;
    var isIndeterminate = this.get('isIndeterminate');
    var isRunning = this.get('isRunning');
    var isEnabled = this.get('isEnabled');
    var offsetRange = this.get('offsetRange');

    var offset = (isIndeterminate && isRunning) ? (Math.floor(Date.now()/75)%offsetRange-offsetRange) : 0;

    // compute value for setting the width of the inner progress
    var value;
    if (!isEnabled) {
      value = "0%" ;
    } else if (isIndeterminate) {
      value = "120%";
    } else {
      var minimum = this.get('minimum') || 0.0;
      var maximum = this.get('maximum') || 1.0;
      value = this.get('value') || 0.0;
      value = (value - minimum) / (maximum - minimum);
      if (value > 1.0) value = 1.0;

      if(isNaN(value)) value = 0.0;
      // cannot be smaller then minimum
      if(value<minimum) value = 0.0;
      // cannot be larger then maximum
      if(value>maximum) value = 1.0;
      value = (value * 100) + "%";
    }

    var classNames = {
      'sc-indeterminate': isIndeterminate,
      'sc-empty': (value <= 0),
      'sc-complete': (value >= 100)
    };

    if(firstTime) {
      var classString = this._createClassNameString(classNames);
      context.push('
');
      context.push('

');
    }
    else {
      context.setClass(classNames);
      inner = this.$('.sc-inner');
      animatedBackground = this.get('animatedBackgroundMatrix');
      inner.css('width', value).css('left',offset);
      if (animatedBackground.length === 3 ) {
        inner.css('backgroundPosition', '0px -'+
        (animatedBackground[0] +
        animatedBackground[1]*this._currentBackground)+'px');
        if(this._currentBackground===animatedBackground[2]-1
           || this._currentBackground===0){
          this._nextBackground *= -1;
        }
        this._currentBackground += this._nextBackground;
      }
    }

  },

  contentPropertyDidChange: function(target, key) {
    var content = this.get('content');
    this.beginPropertyChanges()
      .updatePropertyFromContent('value', key, 'contentValueKey', content)
      .updatePropertyFromContent('minimum', key, 'contentMinimumKey', content)
      .updatePropertyFromContent('maximum', key, 'contentMaximumKey', content)
      .updatePropertyFromContent('isIndeterminate', key, 'contentIsIndeterminateKey', content)
    .endPropertyChanges();
  },

  _createClassNameString: function(classNames) {
    var classNameArray = [], key;
    for(key in classNames) {
      if(!classNames.hasOwnProperty(key)) continue;
      if(classNames[key]) classNameArray.push(key);
    }
    return classNameArray.join(" ");
  }

}) ;<|endoftext|>


<commit_before>// NodeJS input setup
const input = require('readline').createInterface({
      input: process.stdin,
      output: process.stdout
})

input.question("Enter a Sorted, Space Separated list of numbers: ", (listString) => {
      list = listString.split(' ').map(element => parseFloat(element))

      input.question("Enter Search element: ", (searchElement) => {
            // Reads input and calls the main function
            binarySearch(list, parseFloat(searchElement))

            input.close()
      })
})

// Main function
function binarySearch(list, searchElement) {
      /*
            Args:
            `list`: A sorted list of numbers (floats)
            `searchElement`: The search element as a number (float)
      */

      // left and right are pointers to the left and right most indices that the element might be present within, since the array is sorted.
      var left = 0
      var right = list.length - 1

      while (left <= right) {
            // mid is the pointer that points to the mid point between left and right
            var mid = parseInt((left + right) / 2)

            if (list[mid] == searchElement) {
                  console.log(`Search Element found!\nAt index: ${mid} in the Array`)
                  return
            }
            else {
                  if (list[mid] < searchElement) {
                        // searchElement is present after mid
                        left = mid + 1
                  } else {
                        // searchElement is present before mid
                        right = mid - 1
                  }
            }
      }

      // if the function didn't exit at line #22 and the execution reaches line #30, searchElement is not present in the array
      console.log(`Search Element ${searchElement} not found in the List`)
}<commit_msg>delete binarySearch.js<commit_after><|endoftext|>


<commit_before>class DataListWrapper {
  constructor(data, index = null) {
    this._data = data;
    this._indexMap = index;
  }

  // The callback is used for triggering re-rendering
  setCallback(cb, id = 'wrapper') {
    if (this._data.setCallback) {
      this._data.setCallback(cb, id);
    }
  }

  getSize() {
    if (this._indexMap === null) {
      return this._data.getSize();
    }

    return this._indexMap.length;
  }

  getObjectAt(index) {
    if (this._indexMap === null) {
      return this._data.getObjectAt(index);
    }

    return this._data.getObjectAt(
      this._indexMap[index]
    );
  }
}

export default DataListWrapper;
<commit_msg>Minor eslint change<commit_after>class DataListWrapper {
  constructor(data, index = null) {
    this._data = data;
    this._indexMap = index;
  }

  // The callback is used for triggering re-rendering
  setCallback(cb, id = 'wrapper') {
    if (this._data.setCallback) {
      this._data.setCallback(cb, id);
    }
  }

  getSize() {
    if (this._indexMap === null) {
      return this._data.getSize();
    }

    return this._indexMap.length;
  }

  getObjectAt(index) {
    if (this._indexMap === null) {
      return this._data.getObjectAt(index);
    }

    return this._data.getObjectAt(
      this._indexMap[index],
    );
  }
}

export default DataListWrapper;
<|endoftext|>


<commit_before>'use strict';

const assert = require('../support/assert');
const TestClient = require('../support/test-client');

describe('SQL api metric headers', function () {
    const publicSQL = 'select * from untitle_table_4';

    it('should get client header if client param is present', function (done) {
        this.testClient = new TestClient();
        const params = { client: 'test' };

        this.testClient.getResult(publicSQL, params, (err, result, headers) => {
            assert.ifError(err);
            assert.strictEqual(result.length, 6);
            assert.strictEqual(headers['carto-client'], 'test');
            done();
        });
    });

    it('should not get the client header if no client is provided', function (done) {
        this.testClient = new TestClient();

        this.testClient.getResult(publicSQL, (err, result, headers) => {
            assert.ifError(err);
            assert.strictEqual(result.length, 6);
            assert.strictEqual(headers['carto-client'], undefined);
            done();
        });
    });

    it('should not get the user id in the response header', function (done) {
        this.testClient = new TestClient();

        this.testClient.getResult(publicSQL, (err, result, headers) => {
            assert.ifError(err);
            assert.strictEqual(result.length, 6);
            assert.strictEqual(headers['carto-user-id'], '1');
            done();
        });
    });
});
<commit_msg>change test description<commit_after>'use strict';

const assert = require('../support/assert');
const TestClient = require('../support/test-client');

describe('SQL api metric headers', function () {
    const publicSQL = 'select * from untitle_table_4';

    it('should get client header if client param is present', function (done) {
        this.testClient = new TestClient();
        const params = { client: 'test' };

        this.testClient.getResult(publicSQL, params, (err, result, headers) => {
            assert.ifError(err);
            assert.strictEqual(result.length, 6);
            assert.strictEqual(headers['carto-client'], 'test');
            done();
        });
    });

    it('should not get the client header if no client is provided', function (done) {
        this.testClient = new TestClient();

        this.testClient.getResult(publicSQL, (err, result, headers) => {
            assert.ifError(err);
            assert.strictEqual(result.length, 6);
            assert.strictEqual(headers['carto-client'], undefined);
            done();
        });
    });

    it('should get the user id in the response header', function (done) {
        this.testClient = new TestClient();

        this.testClient.getResult(publicSQL, (err, result, headers) => {
            assert.ifError(err);
            assert.strictEqual(result.length, 6);
            assert.strictEqual(headers['carto-user-id'], '1');
            done();
        });
    });
});
<|endoftext|>


<commit_before><commit_msg>Fix chibirex demo<commit_after><|endoftext|>


<commit_before>/*
 * Copyright 2010 ITA Software, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// Execute setup code when page loads
$(document).ready(function() {
    /******* AJAX Helpers ******/
    $('body').ajaxStart(function() {
        if ($('#cursor').length == 0) {
            $('body').append('<images id="cursor" src="/railroad-static/' +
                'images/loading.gif" style="position: absolute;"/>');
            $('body').mousemove(function(e) {
                $('#cursor').css('top', e.clientY).css('left', e.clientX+7);
            });
            $('body').trigger('mousemove');
        }
    });

    $('body').ajaxStop(function() {
        $('#cursor').remove();
    });

    /**** GRAPH SETUP ****/

    // Bind the graph time range selection buttons
    $('.options input[type=button]').live('click', function() {
        var dates = $(this).parent().siblings('.daterange');

        if ($('#sync').prop('checked')) {
            var from = $('input[name=from]');
            var to = $('input[name=to]');
        } else {
            var from = $(dates).children('[name=from]');
            var to = $(dates).children('[name=to]');
        }

        to.datepicker('setDate', new Date());
        from.datepicker('setDate', new Date());

        if ($(this).attr('name') == 'week') {
            from.datepicker('setDate', '-1w');
        } else if ($(this).attr('name') == 'month') {
            from.datepicker('setDate', '-1m');
        } else if ($(this).attr('name') == 'year') {
            from.datepicker('setDate', '-1y');
        }

        to.datepicker('refresh')
        from.datepicker('refresh')
        updateZoom(from,to);
    });

    // Initialize the data for any graphs already on the page
    ajaxcall = [];
    $('.graph').each(function (index, element) {
        ajaxcall.push(getGraphDataByDiv(element));
    });
    ajaxcall = JSON.stringify(ajaxcall);
    $.ajax({
        dataType: 'json',
        url: '/railroad/graphs',
        data: {'graphs': ajaxcall},
        type: 'POST',
        success: function (data, textStatus, XMLHttpRequest) {
            for (var i=0; i < data.length; i++) {
                var element;
                if (data[i]['uniq']) {
                    element = $('.{0}#{1}'.format(data[i]['slug'],
                                                  data[i]['uniq']));
                } else {
                    element = $('.{0}'.format(data[i]['slug']));
                }
                drawGraph(element, data[i]);
            }

            $('#stats #graph_count').html('{0} graphs'.format($('.service_row').length));
        },
        error: function (XMLHttpRequest, textStatus, error) {
            alert ("There was an error preloading the graphs");
        }
    });

    /**** CONFIGURATOR SETUP ****/
	// TODO: delete remnants (most of it) carefully!

    $('#debug_check').prop('checked', localStorageGet('debug'));
    updateDebug();

    $('#debug_check').change(function () {
        localStorageSet('debug', $('#debug_check').prop('checked'));
        updateDebug();
    });

    $('#debug a').live('click', function() {
        localStorageClear();
    });

    /*** Persistent form settings ***/
    /* Anything in #configurator with a class of "... persist ..."
     * will get persistence.
     */
    $('#configurator').change(function() {
        var store = {};
        var value = null;
        $(this).find('.persist').each(function() {
            if ($(this).is('input')) {
                if ($(this).attr('type') == 'checkbox') {
                    value = $(this).prop('checked');
                } else if ($(this).attr('type') == 'radio') {
                    value = $(this).prop('checked');
                }
            } else if ($(this).is('select')) {
                value = $(this).val();
            }

            if (value != null) {
                store[$(this).attr('id')] = value;
            }
        });
        localStorageSet('form_configurator', store);
    });

    // Restore persisted objects
    var form_store = localStorageGet('form_configurator');
    for (key in form_store) {
        element = $('#configurator').find('#' + key);
        if ($(element).is('input')) {
            if ($(element).attr('type') == 'checkbox') {
                $(element).prop('checked', form_store[key]);
            } else if ($(element).attr('type') == 'radio') {
                $(element).prop('checked', form_store[key]);
            }
        } else if ($(element).is('select')) {
            $(element).val(form_store[key]);
        }
    }

    // Autocomplete anything with class = "... autocomplete ..."
    $('.autocomplete').each(function () {
        $(this).autocomplete ( { source : "/railroad/ajax/autocomplete/" +
            $(this).attr('name' ), minLength : 1, autoFocus: true})
    });

    $('#cleargraphs').click(function () {
        $('.service_row').remove();
    });

    $('#clearform').bind('click', function () {
        $('#host').val("");
        $('#group').val("");
        $('#service').val("");
    });

    $('#localtime, #utc').bind('change', function() {
        // Guarantee that localstorage gets the change before redrawing graphs
        $('#configurator').trigger('change');
        graphs = $('.graph');
        graphs.each(function(index, element) {
            if ($(element).data('data')) {
                redrawGraph(element, $(element).data('data'));
            }
        });
    });

    // Handle configurator form submissions
    $('#configurator').submit(function() {

        fields = $('#configurator').formSerialize();
        $.ajax({
            data: fields,
            dataType: 'json',
            url: '/railroad/graphs',
            success: function(data, textStatus, XMLHttpRequest) {
                //reset_fields();
                $('#clearform').trigger('click');
                createGraphs(data);
                //sortGraphs();
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                // TODO: Indicate error somehow, probably
            }
        });
        $('#configurator').data('changed', true);
        return false;
    });

    // *************************** Row manipulations ***************************
    // Expand all/of type buttons
    $('#expansion_by_type').find('input').bind('change', function() {
        auto_expansion();
        //To shorten the else if line below to < 80 chars
        var allCheckboxes = $(this).parent().siblings().children('input');
        if (! $(this).prop('checked')) {
            $('#expandall').prop('checked', false);
        } else if ($(allCheckBoxes).not(':checked').length == 0) {
            // If all inputs are checked
            $('#expandall').prop('checked', true);
        }
    });

    $('#expandall').change(function() {
        var state = $(this).prop('checked');
        $('#expansion_by_type input').prop('checked', state);
        auto_expansion();
    });

    // expand one buttons
    $('.collapse_row').live('click', function() {
        collapse_row($(this).parents().parents().first());
    });
    $('.expand_row').live('click', function() {
        expand_row($(this).parents().parents().first());
    });
    // remove 1 buttons
    $('.remove_row').live('click', function() {
        var tr = $(this).parents().parents().first();
        tr.hide(0, function() {
            $(tr).remove();
        });
    });

    // Start the AJAX graph refreshes
    setTimeout(autoFetchData, 600 * 1000);

    /******* Hint System *******/
    $('.hint').append('');

    $('.hint .hide_hint').bind('click',
        function() {
            var hint_id = $(this).parent().attr('id');
            var hints_hidden = localStorageGet('hints_hidden');
            if (hints_hidden == null) {
                hints_hidden = {};
            }
            hints_hidden[hint_id] = true;
            localStorageSet('hints_hidden', hints_hidden);
            $(this).parent().remove();
        });

    $('#hide_all_hints').change(function () {
        var hints_hidden = localStorageGet('hints_hidden');
        if (!hints_hidden) {
            hints_hidden = {};
        }
        hints_hidden['hide_all_hints'] = $(this).prop('checked');
        localStorageSet('hints_hidden', hints_hidden);
        if ($(this).prop('checked')) {
            var hints = $('.hint .hide_hint');
            hints.each(function (index,element) {
                $(element).trigger('click');
            });
        }
    });

    var hints_hidden = localStorageGet('hints_hidden');
    if (hints_hidden == null) {
        hints_hidden = {};
    }
    $('.hint').each(function() {
        if (! hints_hidden[$(this).attr('id')] &&
            ! hints_hidden["hide_all_hints"]) {
            $(this).css('display', 'block');
        }
    });

    /******** Sorting *********/
    $('#sortby').bind('change', sortGraphs);
    $('#reverse_sort').bind('change', sortGraphs);

    /****** Tool bar stuff *****/
    $('#check_controls input[type=checkbox]').bind('click', function(event) {
        $('.service_row .controls input[type=checkbox]').prop('checked', $(this).prop('checked'));
        // Don't trigger the click event of the parent
        event.stopPropagation();
    });

    var allChecked = function(func) {
        $('.service_row').each(function(index, elem) {
            if ($(elem).children('.controls').children('input').prop('checked')) {
                func(elem);
            }
        });
        $('.service_row .controls input[type=checkbox]').prop('checked', false);
        $('#checkall input').prop('checked', false);
    }
    $('#checkall').bind('click', function() {
        $('#selectall.menu').toggle();
    });
    $('#remove_checked').bind('click', function() {
        allChecked(function(elem) {$(elem).remove();});
    });
    $('#expand_checked').bind('click', function() {
        allChecked(expand_row);
    });
    $('#collapse_checked').bind('click', function() {
        allChecked(collapse_row);
    });

    $('#selectall.menu li').bind('click', function(e) {
        switch ($(this).attr('name')) {
            case 'all':
                $('.service_row .controls input[type=checkbox]').prop('checked', true);
                break;
            case 'none':
                $('.service_row .controls input[type=checkbox]').prop('checked', false);
                break;
            case 'state_ok':
            case 'state_warning':
            case 'state_critical':
            case 'state_unknown':
                var button = this;
                $('.service_row').each(function(index, elem) {
                    if ($(elem).children('.status_text').hasClass($(button).attr('name'))) {
                        $(elem).children('.controls').children('input').prop('checked', true);
                    }
                });
                break;
        }
        $('#selectall.menu').hide();
    });

    /******** Quicklook view ********/
    $('#quicklook .status_text, .host').bind('click', function() {
        $(this).siblings('ul').toggle();
    });
    $('#quicklook .status_text.state_ok').siblings('ul').hide();
    $('#quicklook .host').siblings('ul').hide();

});
<commit_msg>counting service_rows is bad, count .graph instead<commit_after>/*
 * Copyright 2010 ITA Software, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// Execute setup code when page loads
$(document).ready(function() {
    /******* AJAX Helpers ******/
    $('body').ajaxStart(function() {
        if ($('#cursor').length == 0) {
            $('body').append('<images id="cursor" src="/railroad-static/' +
                'images/loading.gif" style="position: absolute;"/>');
            $('body').mousemove(function(e) {
                $('#cursor').css('top', e.clientY).css('left', e.clientX+7);
            });
            $('body').trigger('mousemove');
        }
    });

    $('body').ajaxStop(function() {
        $('#cursor').remove();
    });

    /**** GRAPH SETUP ****/

    // Bind the graph time range selection buttons
    $('.options input[type=button]').live('click', function() {
        var dates = $(this).parent().siblings('.daterange');

        if ($('#sync').prop('checked')) {
            var from = $('input[name=from]');
            var to = $('input[name=to]');
        } else {
            var from = $(dates).children('[name=from]');
            var to = $(dates).children('[name=to]');
        }

        to.datepicker('setDate', new Date());
        from.datepicker('setDate', new Date());

        if ($(this).attr('name') == 'week') {
            from.datepicker('setDate', '-1w');
        } else if ($(this).attr('name') == 'month') {
            from.datepicker('setDate', '-1m');
        } else if ($(this).attr('name') == 'year') {
            from.datepicker('setDate', '-1y');
        }

        to.datepicker('refresh')
        from.datepicker('refresh')
        updateZoom(from,to);
    });

    // Initialize the data for any graphs already on the page
    ajaxcall = [];
    $('.graph').each(function (index, element) {
        ajaxcall.push(getGraphDataByDiv(element));
    });
    ajaxcall = JSON.stringify(ajaxcall);
    $.ajax({
        dataType: 'json',
        url: '/railroad/graphs',
        data: {'graphs': ajaxcall},
        type: 'POST',
        success: function (data, textStatus, XMLHttpRequest) {
            for (var i=0; i < data.length; i++) {
                var element;
                if (data[i]['uniq']) {
                    element = $('.{0}#{1}'.format(data[i]['slug'],
                                                  data[i]['uniq']));
                } else {
                    element = $('.{0}'.format(data[i]['slug']));
                }
                drawGraph(element, data[i]);
            }

            $('#stats #graph_count').html('{0} graphs'.format(
                $('.graph').length));
        },
        error: function (XMLHttpRequest, textStatus, error) {
            alert ("There was an error preloading the graphs");
        }
    });

    /**** CONFIGURATOR SETUP ****/
	// TODO: delete remnants (most of it) carefully!

    $('#debug_check').prop('checked', localStorageGet('debug'));
    updateDebug();

    $('#debug_check').change(function () {
        localStorageSet('debug', $('#debug_check').prop('checked'));
        updateDebug();
    });

    $('#debug a').live('click', function() {
        localStorageClear();
    });

    /*** Persistent form settings ***/
    /* Anything in #configurator with a class of "... persist ..."
     * will get persistence.
     */
    $('#configurator').change(function() {
        var store = {};
        var value = null;
        $(this).find('.persist').each(function() {
            if ($(this).is('input')) {
                if ($(this).attr('type') == 'checkbox') {
                    value = $(this).prop('checked');
                } else if ($(this).attr('type') == 'radio') {
                    value = $(this).prop('checked');
                }
            } else if ($(this).is('select')) {
                value = $(this).val();
            }

            if (value != null) {
                store[$(this).attr('id')] = value;
            }
        });
        localStorageSet('form_configurator', store);
    });

    // Restore persisted objects
    var form_store = localStorageGet('form_configurator');
    for (key in form_store) {
        element = $('#configurator').find('#' + key);
        if ($(element).is('input')) {
            if ($(element).attr('type') == 'checkbox') {
                $(element).prop('checked', form_store[key]);
            } else if ($(element).attr('type') == 'radio') {
                $(element).prop('checked', form_store[key]);
            }
        } else if ($(element).is('select')) {
            $(element).val(form_store[key]);
        }
    }

    // Autocomplete anything with class = "... autocomplete ..."
    $('.autocomplete').each(function () {
        $(this).autocomplete ( { source : "/railroad/ajax/autocomplete/" +
            $(this).attr('name' ), minLength : 1, autoFocus: true})
    });

    $('#cleargraphs').click(function () {
        $('.service_row').remove();
    });

    $('#clearform').bind('click', function () {
        $('#host').val("");
        $('#group').val("");
        $('#service').val("");
    });

    $('#localtime, #utc').bind('change', function() {
        // Guarantee that localstorage gets the change before redrawing graphs
        $('#configurator').trigger('change');
        graphs = $('.graph');
        graphs.each(function(index, element) {
            if ($(element).data('data')) {
                redrawGraph(element, $(element).data('data'));
            }
        });
    });

    // Handle configurator form submissions
    $('#configurator').submit(function() {

        fields = $('#configurator').formSerialize();
        $.ajax({
            data: fields,
            dataType: 'json',
            url: '/railroad/graphs',
            success: function(data, textStatus, XMLHttpRequest) {
                //reset_fields();
                $('#clearform').trigger('click');
                createGraphs(data);
                //sortGraphs();
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                // TODO: Indicate error somehow, probably
            }
        });
        $('#configurator').data('changed', true);
        return false;
    });

    // *************************** Row manipulations ***************************
    // Expand all/of type buttons
    $('#expansion_by_type').find('input').bind('change', function() {
        auto_expansion();
        //To shorten the else if line below to < 80 chars
        var allCheckboxes = $(this).parent().siblings().children('input');
        if (! $(this).prop('checked')) {
            $('#expandall').prop('checked', false);
        } else if ($(allCheckBoxes).not(':checked').length == 0) {
            // If all inputs are checked
            $('#expandall').prop('checked', true);
        }
    });

    $('#expandall').change(function() {
        var state = $(this).prop('checked');
        $('#expansion_by_type input').prop('checked', state);
        auto_expansion();
    });

    // expand one buttons
    $('.collapse_row').live('click', function() {
        collapse_row($(this).parents().parents().first());
    });
    $('.expand_row').live('click', function() {
        expand_row($(this).parents().parents().first());
    });
    // remove 1 buttons
    $('.remove_row').live('click', function() {
        var tr = $(this).parents().parents().first();
        tr.hide(0, function() {
            $(tr).remove();
        });
    });

    // Start the AJAX graph refreshes
    setTimeout(autoFetchData, 600 * 1000);

    /******* Hint System *******/
    $('.hint').append('');

    $('.hint .hide_hint').bind('click',
        function() {
            var hint_id = $(this).parent().attr('id');
            var hints_hidden = localStorageGet('hints_hidden');
            if (hints_hidden == null) {
                hints_hidden = {};
            }
            hints_hidden[hint_id] = true;
            localStorageSet('hints_hidden', hints_hidden);
            $(this).parent().remove();
        });

    $('#hide_all_hints').change(function () {
        var hints_hidden = localStorageGet('hints_hidden');
        if (!hints_hidden) {
            hints_hidden = {};
        }
        hints_hidden['hide_all_hints'] = $(this).prop('checked');
        localStorageSet('hints_hidden', hints_hidden);
        if ($(this).prop('checked')) {
            var hints = $('.hint .hide_hint');
            hints.each(function (index,element) {
                $(element).trigger('click');
            });
        }
    });

    var hints_hidden = localStorageGet('hints_hidden');
    if (hints_hidden == null) {
        hints_hidden = {};
    }
    $('.hint').each(function() {
        if (! hints_hidden[$(this).attr('id')] &&
            ! hints_hidden["hide_all_hints"]) {
            $(this).css('display', 'block');
        }
    });

    /******** Sorting *********/
    $('#sortby').bind('change', sortGraphs);
    $('#reverse_sort').bind('change', sortGraphs);

    /****** Tool bar stuff *****/
    $('#check_controls input[type=checkbox]').bind('click', function(event) {
        $('.service_row .controls input[type=checkbox]').prop('checked', $(this).prop('checked'));
        // Don't trigger the click event of the parent
        event.stopPropagation();
    });

    var allChecked = function(func) {
        $('.service_row').each(function(index, elem) {
            if ($(elem).children('.controls').children('input').prop('checked')) {
                func(elem);
            }
        });
        $('.service_row .controls input[type=checkbox]').prop('checked', false);
        $('#checkall input').prop('checked', false);
    }
    $('#checkall').bind('click', function() {
        $('#selectall.menu').toggle();
    });
    $('#remove_checked').bind('click', function() {
        allChecked(function(elem) {$(elem).remove();});
    });
    $('#expand_checked').bind('click', function() {
        allChecked(expand_row);
    });
    $('#collapse_checked').bind('click', function() {
        allChecked(collapse_row);
    });

    $('#selectall.menu li').bind('click', function(e) {
        switch ($(this).attr('name')) {
            case 'all':
                $('.service_row .controls input[type=checkbox]').prop('checked', true);
                break;
            case 'none':
                $('.service_row .controls input[type=checkbox]').prop('checked', false);
                break;
            case 'state_ok':
            case 'state_warning':
            case 'state_critical':
            case 'state_unknown':
                var button = this;
                $('.service_row').each(function(index, elem) {
                    if ($(elem).children('.status_text').hasClass($(button).attr('name'))) {
                        $(elem).children('.controls').children('input').prop('checked', true);
                    }
                });
                break;
        }
        $('#selectall.menu').hide();
    });

    /******** Quicklook view ********/
    $('#quicklook .status_text, .host').bind('click', function() {
        $(this).siblings('ul').toggle();
    });
    $('#quicklook .status_text.state_ok').siblings('ul').hide();
    $('#quicklook .host').siblings('ul').hide();

});
<|endoftext|>


<commit_before>// The query module returns connections, and connections are
// used to perform queries against the server.

var Query = (function(){

    // Utility. Appends query parameter to URL.
    function addParameter(url, key, value) {
	return url + (/\?/.exec(url) ? '&' : '?')
	    + encodeURIComponent(key) + '='
	    + encodeURIComponent(value);
    }

    function Connection() {
	this._clock = null;
    }

    Connection.prototype = {

	// Running a query and returns the jQuery deferred object representing the
	// result. This is the meat of the connection class, most other methods
	// simply forward calls to this one.
	//
	// All parameters are expected to be synchronous values.
	query: function(verb, url, data, auth) {

	    var self = this;

	    auth = auth || {};
	    var token = auth.token, as = auth.as;

	    if (!/^\//.exec(url)) url = "/" + url;
	    if (as) url = addParameter(url, 'as', as);
	    if (this._clock) url = addParameter(url, 'at', this._clock);

	    var promise = $.ajax({
		url: url,
		type: verb,
		dataType: 'json',
		contentType: 'application/json',
		data: (verb == 'PUT' || verb == 'POST') ? {} : JSON.stringify(data),
		beforeSend: function(xhr) {
		    if (token) xhr.setRequestHeader('Authorization', 'RUNORG token=' + token);
		}
	    });

	    promise.always(function(data,status) {
		if (status != 'success' || ! ('at' in data)) return;

		var c = self.clock ? JSON.parse(self.clock) : [], i, j, at = data.at;

		// Merge the new clock value with the old one
		for (i = 0; i < at.length; ++i) {
		    for (j = 0; j < c.length; ++j)
			if (c[j][0] == at[i][0]) { c[j][1] = at[i][1]; break; }
		    if (j == c.length)
			c.push(at[i]);
		}

		self.clock = JSON.stringify(c);
	    });

	    return promise;
	},

	// Like 'query', but applies Async.wait to all parameters (except the verb).
	// If the URL is an array (or has a join function), uses url.join('').
	queryAsync: function(verb,url,data,auth) {
	    var self = this;
	    $.wait(Async.wait(url),Async.wait(data),Async.wait(auth))
		.then(function(url,data,auth) {
		    if ('join' in url) url = url.join('');
		    return self.query(verb,url,data,auth);
		});
	},

	// Performs a GET request
	get: function(url,token,as) {
	    return this.queryAsync("GET",url,null,auth);
	},

	// Performs a PUT request
	put: function(url,data,auth) {
	    return this.queryAsync("PUT",url,data,auth);
	},

	// Performs a POST request
	post: function(url,data,auth) {
	    return this.queryAsync("POST",url,data,auth);
	},

	// Performs a DELETE request
	del: function(url,auth) {
	    return this.queryAsync("DELETE",url,null,auth);
	},

	// Authenticate as a server administrator.
	asServerAdmin: function() {
	    return {
		token: this.post("test/auth",{}).always(function(data){ return data.token; }),
		id:    void(0)
	    };
	},

	// Create a brand new database and return the id.
	mkdb: function() {
	    var auth = this.asServerAdmin();
	    return this.post("db/create",{label:"Test database " + new Date()},auth);
	},

	// Authenticate with a specific database
	auth: function(db,admin,email) {

	    var result = this.post(["db/",db,"/test/auth"],{
		email : (email || void(0)),
		admin : (admin === false ? false : true)
	    }).always(function(data) { return data; })

	    return {
		token : result.then(function(r) { return r.token; }),
		id    : result.then(function(r) { return r.id; })
	    };
	}
    };

    return {
	create: function() { return new Connection(); }
    };

})();

<commit_msg>Apply convention<commit_after>// The query module returns connections, and connections are
// used to perform queries against the server.

var Query = (function(){

    // Utility. Appends query parameter to URL.
    function addParameter(url, key, value) {
	return url + (/\?/.exec(url) ? '&' : '?')
	    + encodeURIComponent(key) + '='
	    + encodeURIComponent(value);
    }

    function Connection() {
	this._clock = null;
    }

    Connection.prototype = {

	// Running a query and returns the jQuery deferred object representing the
	// result. This is the meat of the connection class, most other methods
	// simply forward calls to this one.
	//
	// All parameters are expected to be synchronous values.
	query: function(verb, url, data, auth) {

	    var self = this;

	    auth = auth || {};
	    var token = auth.token, as = auth.as;

	    if (!/^\//.exec(url)) url = "/" + url;
	    if (as) url = addParameter(url, 'as', as);
	    if (this._clock) url = addParameter(url, 'at', this._clock);

	    var promise = $.ajax({
		url: url,
		type: verb,
		dataType: 'json',
		contentType: 'application/json',
		data: (verb == 'PUT' || verb == 'POST') ? {} : JSON.stringify(data),
		beforeSend: function(xhr) {
		    if (token) xhr.setRequestHeader('Authorization', 'RUNORG token=' + token);
		}
	    });

	    promise.always(function(data,status) {
		if (status != 'success' || ! ('at' in data)) return;

		var c = self.clock ? JSON.parse(self.clock) : [], i, j, at = data.at;

		// Merge the new clock value with the old one
		for (i = 0; i < at.length; ++i) {
		    for (j = 0; j < c.length; ++j)
			if (c[j][0] == at[i][0]) { c[j][1] = at[i][1]; break; }
		    if (j == c.length)
			c.push(at[i]);
		}

		self.clock = JSON.stringify(c);
	    });

	    return promise;
	},

	// Like 'query', but applies Async.wait to all parameters (except the verb).
	// If the URL is an array (or has a join function), uses url.join('').
	queryAsync: function(verb,url,data,auth) {
	    var self = this;
	    $.wait(Async.wait(url),Async.wait(data),Async.wait(auth))
		.then(function(url,data,auth) {
		    if ('join' in url) url = url.join('');
		    return self.query(verb,url,data,auth);
		});
	},

	// Performs a GET request
	get: function(url,token,as) {
	    return this.queryAsync("GET",url,null,auth);
	},

	// Performs a PUT request
	put: function(url,data,auth) {
	    return this.queryAsync("PUT",url,data,auth);
	},

	// Performs a POST request
	post: function(url,data,auth) {
	    return this.queryAsync("POST",url,data,auth);
	},

	// Performs a DELETE request
	del: function(url,auth) {
	    return this.queryAsync("DELETE",url,null,auth);
	},

	// Authenticate as a server administrator.
	asServerAdmin: function() {
	    return {
		token: this.post("test/auth",{}).always(function(r){ return r.token; }),
		id:    void(0)
	    };
	},

	// Create a brand new database and return the id.
	mkdb: function() {
	    var auth = this.asServerAdmin();
	    return this.post("db/create",{label:"Test database " + new Date()},auth);
	},

	// Authenticate with a specific database
	auth: function(db,admin,email) {

	    var result = this.post(["db/",db,"/test/auth"],{
		email : (email || void(0)),
		admin : (admin === false ? false : true)
	    }).always(function(data) { return data; })

	    return {
		token : result.then(function(r) { return r.token; }),
		id    : result.then(function(r) { return r.id; })
	    };
	}
    };

    return {
	create: function() { return new Connection(); }
    };

})();

<|endoftext|>


<commit_before>var compare = require('../imgCompare.js').compare;
var CronJob = require('cron').CronJob;
var CronJobManager = require('cron-job-manager');
var compareUtils = require('../utils/cron');
var removeUrl = require('./urlController.js').removeUrl;
var Sequelize = require('sequelize');

var manager = new CronJobManager();

module.exports = {
  startAllCron: function() {
    console.log('starting all cronjobs');
    db.User.findAll()
    .then(function(allUsers) {
      for (var i = 0; i < allUsers.length; i++){
        allUsers[i].getUrls()
        .then(function(url) {
          for (var j=0; j<url.length; j++){
             var userUrl = url[j].UserUrl;
             var active = userUrl.status;
             var url = url[j].url;
             if (active) {
               console.log('watching ' + url + ' for ' + userUrl.email)
               module.exports.addCron(userUrl, url);
             }; // if (active)
          }; // for loop iterating over each url for a user
        }); // .then(function(url){
      }; // or (var i = 0; i < allUsers.length; i++){
    }); // .then(function(allUsers) {
  },

  addCron: function(UserUrl, url) {
    UserUrl.status = true;
    var userUrl = UserUrl;
    var key = UserUrl.url_id.toString() + UserUrl.user_id.toString();
    // var freq = UserUrl.frequency;
    var action = UserUrl.compare || 'image';

    // hours
    // var freq = '* * */' + UserUrl.frequency + ' * * *';

    // minutes
    // var freq = '* */' + UserUrl.frequency + ' * * * *';

    var freq = '*/1 * * * * *';
    console.log('filter ', UserUrl.filter);
    // var freq = '* */5 * * * *';
    console.log('comparison ', UserUrl.comparison);

    console.log('Starting cronJob', key, 'for', UserUrl.url, ' with frequency ', freq);

    if (manager.exists(key)) {
      manager.deleteJob(key);
    };
    manager.add(key, freq, function() {
      if (UserUrl.status) {
        // var currentDate = new Date(dateString);
        // console.log('the date is', currentDate);
        console.log('checking', url, 'for', UserUrl.email);
         var oldImg = UserUrl.cropImage;
         var email = UserUrl.email;
         var params = {
          h: UserUrl.cropHeight,
          w: UserUrl.cropWidth,
          x: UserUrl.cropOriginX,
          y: UserUrl.cropOriginY
        };

        UserUrl.lastScrape = compareUtils.getDate();

        console.log(key, 'last checked at', UserUrl.lastScrape);

        if (UserUrl.comparison === 'Text') {
          compareUtils.compareOCR(UserUrl, url, email, params, oldImg, function(oldImg, newImg) {
            // if we enter the anonymous function, we can assume images are not equal
            if (UserUrl.stopAfterChange) {
              // set status to false since we are stopping the cronjob
              UserUrl.status = false;
              // stop cronjob
              module.exports.stopCron(UserUrl.user_id, UserUrl.url_id)
            }
            // if images are not equal, send an email
            compareUtils.sendEmail(url, email, oldImg, newImg);
          });
        } else if (UserUrl.comparison === 'Image') {
          compareUtils.compareScreenShot(UserUrl, url, email, params, oldImg, function(oldImg, newImg) {
            // if we enter the anonymous function, we can assume images are not equal
            if (UserUrl.stopAfterChange) {
              // set status to false since we are stopping the cronjob
              UserUrl.status = false;
              // stop cronjob
              module.exports.stopCron(UserUrl.user_id, UserUrl.url_id)
            }
            // if images are not equal, send an email
            compareUtils.sendEmail(url, email, oldImg, newImg);
          });

        } else {
          compareUtils.compareScreenShot(UserUrl, url, email, params, oldImg, function(oldImg, newImg) {
            // if we enter the anonymous function, we can assume images are not equal
            if (UserUrl.stopAfterChange) {
              // set status to false since we are stopping the cronjob
              UserUrl.status = false;
              // stop cronjob
              module.exports.stopCron(UserUrl.user_id, UserUrl.url_id)
            }
            // if images are not equal, send an email
            compareUtils.sendEmail(url, email, oldImg, newImg);
          });
        }

        UserUrl.numScrapes++;
        console.log('numScrapes', UserUrl.numScrapes);
        console.log('url controller', removeUrl);

        // if (UserUrl.numScrapes >= 100) {
        //   // remove
        //   removeUrl(UserUrl.email, UserUrl.url, function(status) {
        //     if (status) {
        //       console.log('UserUrl deleted!');
        //     }
        //   });
        // }

      } else {
        manager.stop()
      }
    });
    manager.start(key);
  },

  startCron: function(user_id, url_id) {
    var key = url_id.toString() + user_id.toString();
    if (manager.exists(key)) {
      console.log('Starting cronjob', key);
      manager.start(key);
    } else {
      console.log('error, cronjob', key, ' does not exist');
    }
  },

  stopCron: function(user_id, url_id) {
    var key = url_id.toString() + user_id.toString();
    console.log('Stopping cronJob', key);
    manager.stop(key);
  },

  deleteCron: function(user_id, url_id) {
    var key = url_id.toString() + user_id.toString();
    console.log('Deleting cronJob', key);
    manager.deleteJob(key);
  },
};
<commit_msg>[Fix] Refactored code for stopping a cronjob after 100 scrapes<commit_after>var compare = require('../imgCompare.js').compare;
var CronJob = require('cron').CronJob;
var CronJobManager = require('cron-job-manager');
var compareUtils = require('../utils/cron');
var removeUrl = require('./urlController');
var db = require("../db");
var Sequelize = require('sequelize');

var manager = new CronJobManager();

module.exports = {
  startAllCron: function() {
    console.log('starting all cronjobs');
    db.User.findAll()
    .then(function(allUsers) {
      for (var i = 0; i < allUsers.length; i++){
        allUsers[i].getUrls()
        .then(function(url) {
          for (var j=0; j<url.length; j++){
             var userUrl = url[j].UserUrl;
             var active = userUrl.status;
             var url = url[j].url;
             if (active) {
               console.log('watching ' + url + ' for ' + userUrl.email)
               module.exports.addCron(userUrl, url);
             }; // if (active)
          }; // for loop iterating over each url for a user
        }); // .then(function(url){
      }; // or (var i = 0; i < allUsers.length; i++){
    }); // .then(function(allUsers) {
  },

  addCron: function(UserUrl, url) {
    UserUrl.status = true;
    var userUrl = UserUrl;
    var key = UserUrl.url_id.toString() + UserUrl.user_id.toString();
    var freq = UserUrl.frequency;
    var action = UserUrl.compare || 'image';

    // hours
    // var freq = '* * */' + UserUrl.frequency + ' * * *';

    // minutes
    // var freq = '* */' + UserUrl.frequency + ' * * * *';

    // Test values
    // var freq = '*/1 * * * * *';
    // var freq = '* */5 * * * *';

    console.log('Starting cronJob', key, 'for', UserUrl.url, ' with frequency ', freq);

    if (manager.exists(key)) {
      manager.deleteJob(key);
    };
    manager.add(key, freq, function() {
      if (UserUrl.status) {
        // var currentDate = new Date(dateString);
        // console.log('the date is', currentDate);
        console.log('checking', url, 'for', UserUrl.email);
         var oldImg = UserUrl.cropImage;
         var email = UserUrl.email;
         var params = {
          h: UserUrl.cropHeight,
          w: UserUrl.cropWidth,
          x: UserUrl.cropOriginX,
          y: UserUrl.cropOriginY
        };

        UserUrl.lastScrape = compareUtils.getDate();

        console.log(key, 'last checked at', UserUrl.lastScrape);

        if (UserUrl.comparison === 'Text') {
          compareUtils.compareOCR(UserUrl, url, email, params, oldImg, function(oldImg, newImg) {
            // if we enter the anonymous function, we can assume images are not equal
            if (UserUrl.stopAfterChange) {
              // set status to false since we are stopping the cronjob
              UserUrl.status = false;
              // stop cronjob
              module.exports.stopCron(UserUrl.user_id, UserUrl.url_id)
            }
            // if images are not equal, send an email
            compareUtils.sendEmail(url, email, oldImg, newImg);
          });
        } else if (UserUrl.comparison === 'Image') {
          compareUtils.compareScreenShot(UserUrl, url, email, params, oldImg, function(oldImg, newImg) {
            // if we enter the anonymous function, we can assume images are not equal
            if (UserUrl.stopAfterChange) {
              // set status to false since we are stopping the cronjob
              UserUrl.status = false;
              // stop cronjob
              module.exports.stopCron(UserUrl.user_id, UserUrl.url_id)
            }
            // if images are not equal, send an email
            compareUtils.sendEmail(url, email, oldImg, newImg);
          });

        } else {
          compareUtils.compareScreenShot(UserUrl, url, email, params, oldImg, function(oldImg, newImg) {
            // if we enter the anonymous function, we can assume images are not equal
            if (UserUrl.stopAfterChange) {
              // set status to false since we are stopping the cronjob
              UserUrl.status = false;
              // stop cronjob
              module.exports.stopCron(UserUrl.user_id, UserUrl.url_id)
            }
            // if images are not equal, send an email
            compareUtils.sendEmail(url, email, oldImg, newImg);
          });
        }

        UserUrl.numScrapes++;
        console.log('numScrapes', UserUrl.numScrapes);

        if (UserUrl.numScrapes >= 100) {
          // remove

          db.User.findOne({
            where: {
              email: UserUrl.email
            }
          })
          .then(function (userFound) {

            if (userFound) {

              db.Url.findOne({
                where: UserUrl.url
              })
              .then(function(urlFound) {
                if (urlFound) {
                  var key = UserUrl.user_id.toString() + UserUrl.url_id.toString()
                  userFound.removeUrl(urlFound);
                  manager.deleteJob(key);
                  console.log('cronJob stopped!')
                } else {

                  console.log('error. Url not found in cronController')

                } // end urlFound
              }); // end url.findOne then

            } // end if userFound
          }); // end user.findOne then
        }

      } else {
        manager.stop()
      }
    });
    manager.start(key);
  },

  startCron: function(user_id, url_id) {
    var key = url_id.toString() + user_id.toString();
    if (manager.exists(key)) {
      console.log('Starting cronjob', key);
      manager.start(key);
    } else {
      console.log('error, cronjob', key, ' does not exist');
    }
  },

  stopCron: function(user_id, url_id) {
    var key = url_id.toString() + user_id.toString();
    console.log('Stopping cronJob', key);
    manager.stop(key);
  },

  deleteCron: function(user_id, url_id) {
    var key = url_id.toString() + user_id.toString();
    console.log('Deleting cronJob', key);
    manager.deleteJob(key);
  },
};
<|endoftext|>


<commit_before>const axios = require('axios');
const dbController = require('../utils/queries.js')

module.exports = {
  deleteRecipe: (req, res, next) => {
    dbController.deleteRecipe(req.body.data, (err, user) => {
      res.send();
    })
  },

  findUser: (req, res, next) => {
    dbController.findUserId(req.query.ID, (err, data) => {
      if(err) {
    		console.log(err);
    }
    res.send(data);
    })
  },

  createUser: (req, res, next) => {
    const newUser = {
      'name': 'testing',
      'FacebookUserID': req.body.id,
      'InstagramToken': [],
      'FavoriteRecipe': [],
    }
    dbController.insertNewUser(newUser, (err, data) => {
      if(err) {
        console.log(err);
      }
      console.log('server created user', data)
      res.send(data)
    })
  },
  addRecipe: (req, res, next) => {
    let facebookuserid = req.body.facebookuserid
    const saveRecipe = {
      "name": req.body.name,
      "id": req.body.id,
      "image": req.body.image,
      "analyzedInstructions": req.body.analyzedInstructions
    }
    dbController.createRecipe(saveRecipe, (err, newRecipe) => {
      if(err) {
        console.log(err);
      }
      let newR = newRecipe;
      dbController.findUserId(facebookuserid, (err, user) => {
        if(err) {
      		console.log(err);
      	}
        user[0].FavoriteRecipe.push(newR)
        user[0].save(function(err, user, num){
          if(err) {
            console.log(err)
          }
        });
      })
    })
  }
}
<commit_msg>fixed bug where we were not res.sending<commit_after>const axios = require('axios');
const dbController = require('../utils/queries.js')

module.exports = {
  deleteRecipe: (req, res, next) => {
    dbController.deleteRecipe(req.body.data, (err, user) => {
      res.send();
    })
  },

  findUser: (req, res, next) => {
    dbController.findUserId(req.query.ID, (err, data) => {
      if(err) {
    		console.log(err);
    }
    res.send(data);
    })
  },

  createUser: (req, res, next) => {
    const newUser = {
      'name': 'testing',
      'FacebookUserID': req.body.id,
      'InstagramToken': [],
      'FavoriteRecipe': [],
    }
    dbController.insertNewUser(newUser, (err, data) => {
      if(err) {
        console.log(err);
      }
      console.log('server created user', data)
      res.send(data)
    })
  },
  addRecipe: (req, res, next) => {
    let facebookuserid = req.body.facebookuserid
    const saveRecipe = {
      "name": req.body.name,
      "id": req.body.id,
      "image": req.body.image,
      "analyzedInstructions": req.body.analyzedInstructions
    }
    dbController.createRecipe(saveRecipe, (err, newRecipe) => {
      if(err) {
        console.log(err);
      }
      let newR = newRecipe;
      dbController.findUserId(facebookuserid, (err, user) => {
        if(err) {
      		console.log(err);
      	}
        user[0].FavoriteRecipe.push(newR)
        user[0].save(function(err, user, num){
          if(err) {
            console.log(err)
          }
          res.send('ITS DONE');
        });
      })
    })
  }
}
<|endoftext|>