<commit_before>var Waitlist = require('./models/waitlist');

module.exports = function(app, passport) {
  // PROFILE SECTION =========================
  // POST to CREATE
  app.post('/api/waitlists', function (req, res) {
    var course;
    console.log("POST: ");
    console.log(req.body);

    //laundry wash clean
    course = new Waitlist({
      provider: req.body.provider.name,
    });
    course.save(function (err) {
      if (!err) {
        return console.log("created");
      } else {
        return console.log(err);
      }
    });
    return res.send(course);
  });

  // PUT to UPDATE

  // Bulk update
  app.put('/api/waitlists', function (req, res) {
      var i, len = 0;
      console.log("is Array req.body.waitlists");
      console.log(Array.isArray(req.body.waitlists));
      console.log("PUT: (waitlists)");
      console.log(req.body.waitlists);
      if (Array.isArray(req.body.waitlists)) {
          len = req.body.waitlists.length;
      }
      for (i = 0; i < len; i++) {
          Waitlist.update({ "_id": id }, req.body.waitlists[i][id], function (err, numAffected) {
              if (err) {
                  console.log("Error on update");
                  console.log(err);
              } else {
                  console.log("updated num: " + numAffected);
              }
          });
      }
      return res.send(req.body.waitlists);
  });

  // Single update
  app.put('/api/waitlists/:crn', function (req, res) {
    console.log(req.body);
    return Waitlist.find({"crn":req.params.crn}, function (err, data) {
      if (!err) {
        console.log("updated");
        return Waitlist.update({"crn":req.params.crn}, {$set:{"subscribers": JSON.parse(req.body.subscribers)}},  function (err) {
          if (!err) {
            console.log("updated");
          } else {
            console.log(err);
          }
          return res.send("updated");
        });
      } else {
        console.log(err);
        return res.send(err);
      }
      //waitlist.subscribers = req.body.subscribers;
    });
  });

  // GET to READ

  // List waitlists
  app.get('/api/waitlists', function (req, res) {
    return Waitlist.find({"status":"shut"}, function (err, waitlists) {
      if (!err) {

        return res.send(waitlists);
      } else {
        return console.log(err);
      }
    });
  });

  // Single course
  app.get('/api/waitlists/:id', function (req, res) {
    return Waitlist.findById(req.params.id, function (err, course) {
      if (!err) {
        return res.send(course);
      } else {
        return console.log(err);
      }
    });
  });

  // DELETE to DESTROY

  // Bulk destroy all waitlists
  app.delete('/api/waitlists', function (req, res) {
    Waitlist.remove(function (err) {
      if (!err) {
        console.log("removed");
        return res.send('');
      } else {
        console.log(err);
      }
    });
  });

  // remove a single course
  app.delete('/api/waitlists/:id', function (req, res) {
    return Waitlist.findById(req.params.id, function (err, course) {
      return course.remove(function (err) {
        if (!err) {
          console.log("removed");
          return res.send('');
        } else {
          console.log(err);
        }
      });
    });
  });

  //Subsciptions
  app.post('/api/waitlists/subscribe', function (req,res) {
   console.log(req.body);
   return Waitlist.findOne({"crn":req.body.crn}, function (err, course) {
     //save the info
     console.log(course);
     if (course.subscribers.indexOf(req.body.email)>=0){
       res.send("already subscribed redirect");
     }
     course.subscribers.push(req.body.email);
     return course.save(function (err) {
       if (!err){
         console.log("subscribed");
         return res.send('success');
       }
       else {
         console.log(err);
         res.end('error');
       }
     });
   });
 });

 //Subsciptions
 app.post('/api/waitlists/unsubscribe', function (req,res) {
  console.log(req.body);
  return Waitlist.findOne({"crn":req.body.crn}, function (err, course) {
    //save the info
    console.log(course);
    if (course.subscribers.indexOf(req.body.email)<0){
      res.send("you're already unsubscribed ");
    }
    course.subscribers.splice(req.body.email,1);
    return course.save(function (err) {
      if (!err){
        console.log("removed");
        return res.send('success removed');
      }
      else {
        console.log(err);
        res.end('error removing');
      }
    });
  });
});
};
<commit_msg>adding updated put method using id<commit_after>var Waitlist = require('./models/waitlist');

module.exports = function(app, passport) {
  // PROFILE SECTION =========================
  // POST to CREATE
  app.post('/api/waitlists', function (req, res) {
    var course;
    console.log("POST: ");
    console.log(req.body);

    //laundry wash clean
    course = new Waitlist({
      provider: req.body.provider.name,
    });
    course.save(function (err) {
      if (!err) {
        return console.log("created");
      } else {
        return console.log(err);
      }
    });
    return res.send(course);
  });

  // PUT to UPDATE

  // Bulk update
  app.put('/api/waitlists', function (req, res) {
      var i, len = 0;
      console.log("is Array req.body.waitlists");
      console.log(Array.isArray(req.body.waitlists));
      console.log("PUT: (waitlists)");
      console.log(req.body.waitlists);
      if (Array.isArray(req.body.waitlists)) {
          len = req.body.waitlists.length;
      }
      for (i = 0; i < len; i++) {
          Waitlist.update({ "_id": id }, req.body.waitlists[i][id], function (err, numAffected) {
              if (err) {
                  console.log("Error on update");
                  console.log(err);
              } else {
                  console.log("updated num: " + numAffected);
              }
          });
      }
      return res.send(req.body.waitlists);
  });
  // Single update

  // Single update
  app.put('/api/waitlists/:id', function (req, res) {
    //{"crn":req.params.crn}
    return Waitlist.findByIdAndUpdate(req.params.id, req.body, function (err, product) {
      //run over the properties

      ///product.description = req.body.description;
        if (!err) {
          console.log("updated");
        } else {
          console.log(err);
        }
        return res.send(product);
      });
  });

  // Single update
  app.put('/api/waitlists/subscribe/:crn', function (req, res) {
    console.log(req.body);
    return Waitlist.find({"crn":req.params.crn}, function (err, data) {
      if (!err) {
        console.log("updated");
        return Waitlist.update({"crn":req.params.crn}, {$set:{"subscribers": JSON.parse(req.body.subscribers)}},  function (err) {
          if (!err) {
            console.log("updated");
          } else {
            console.log(err);
          }
          return res.send("updated");
        });
      } else {
        console.log(err);
        return res.send(err);
      }
      //waitlist.subscribers = req.body.subscribers;
    });
  });

  // GET to READ

  // List waitlists
  app.get('/api/waitlists', function (req, res) {
    return Waitlist.find({"status":"shut"}, function (err, waitlists) {
      if (!err) {

        return res.send(waitlists);
      } else {
        return console.log(err);
      }
    });
  });

  // Single course
  app.get('/api/waitlists/:id', function (req, res) {
    return Waitlist.findById(req.params.id, function (err, course) {
      if (!err) {
        return res.send(course);
      } else {
        return console.log(err);
      }
    });
  });

  // DELETE to DESTROY

  // Bulk destroy all waitlists
  app.delete('/api/waitlists', function (req, res) {
    Waitlist.remove(function (err) {
      if (!err) {
        console.log("removed");
        return res.send('');
      } else {
        console.log(err);
      }
    });
  });

  // remove a single course
  app.delete('/api/waitlists/:id', function (req, res) {
    return Waitlist.findById(req.params.id, function (err, course) {
      return course.remove(function (err) {
        if (!err) {
          console.log("removed");
          return res.send('');
        } else {
          console.log(err);
        }
      });
    });
  });

  //Subsciptions
  app.post('/api/waitlists/subscribe', function (req,res) {
   console.log(req.body);
   return Waitlist.findOne({"crn":req.body.crn}, function (err, course) {
     //save the info
     console.log(course);
     if (course.subscribers.indexOf(req.body.email)>=0){
       res.send("already subscribed redirect");
     }
     course.subscribers.push(req.body.email);
     return course.save(function (err) {
       if (!err){
         console.log("subscribed");
         return res.send('success');
       }
       else {
         console.log(err);
         res.end('error');
       }
     });
   });
 });

 //Subsciptions
 app.post('/api/waitlists/unsubscribe', function (req,res) {
  console.log(req.body);
  return Waitlist.findOne({"crn":req.body.crn}, function (err, course) {
    //save the info
    console.log(course);
    if (course.subscribers.indexOf(req.body.email)<0){
      res.send("you're already unsubscribed ");
    }
    course.subscribers.splice(req.body.email,1);
    return course.save(function (err) {
      if (!err){
        console.log("removed");
        return res.send('success removed');
      }
      else {
        console.log(err);
        res.end('error removing');
      }
    });
  });
});
};
<|endoftext|>


<commit_before>require("../env");

var vows = require("vows"),
    assert = require("assert");

var suite = vows.describe("d3.transition");

suite.addBatch({
  "transition": {
    topic: function() {
      return d3.transition();
    },
    "selects the document": function(transition) {
      assert.domEqual(transition[0][0].node, document);
    },
    "is an instanceof d3.transition": function(transition) {
      assert.isTrue(transition instanceof d3.transition);
    },
    "subselections are also instanceof d3.transition": function(transition) {
      assert.isTrue(transition.select("body") instanceof d3.transition);
      assert.isTrue(transition.selectAll("body") instanceof d3.transition);
    },
    "transition prototype can be extended": function(transition) {
      var vv = [];
      d3.transition.prototype.foo = function(v) { vv.push(v); return this; };
      transition.select("body").foo(42);
      assert.deepEqual(vv, [42]);
      delete d3.transition.prototype.foo;
    }
  }
});

suite.export(module);

var suite = vows.describe("transition");

// Subtransitions
suite.addBatch({
  "select": require("./transition-test-select"),
  "selectAll": require("./transition-test-selectAll"),
  "transition": require("./transition-test-transition"),
});

// Content
suite.addBatch({
  "attr": require("./transition-test-attr"),
  "attrTween": require("./transition-test-attrTween"),
  "style": require("./transition-test-style"),
  "styleTween": require("./transition-test-styleTween"),
  "text": require("./transition-test-text"),
  "remove": require("./transition-test-remove"),
});

// Animation
suite.addBatch({
  "delay": require("./transition-test-delay"),
  "duration": require("./transition-test-duration"),
});

// Control
suite.addBatch({
  "each": require("./transition-test-each"),
  "call": require("./transition-test-call"),
  "tween": require("./transition-test-tween"),
  "id": require("./transition-test-id"),
  "time": require("./transition-test-time")
});

suite.export(module);
<commit_msg>Remove trailing commas.<commit_after>require("../env");

var vows = require("vows"),
    assert = require("assert");

var suite = vows.describe("d3.transition");

suite.addBatch({
  "transition": {
    topic: function() {
      return d3.transition();
    },
    "selects the document": function(transition) {
      assert.domEqual(transition[0][0].node, document);
    },
    "is an instanceof d3.transition": function(transition) {
      assert.isTrue(transition instanceof d3.transition);
    },
    "subselections are also instanceof d3.transition": function(transition) {
      assert.isTrue(transition.select("body") instanceof d3.transition);
      assert.isTrue(transition.selectAll("body") instanceof d3.transition);
    },
    "transition prototype can be extended": function(transition) {
      var vv = [];
      d3.transition.prototype.foo = function(v) { vv.push(v); return this; };
      transition.select("body").foo(42);
      assert.deepEqual(vv, [42]);
      delete d3.transition.prototype.foo;
    }
  }
});

suite.export(module);

var suite = vows.describe("transition");

// Subtransitions
suite.addBatch({
  "select": require("./transition-test-select"),
  "selectAll": require("./transition-test-selectAll"),
  "transition": require("./transition-test-transition")
});

// Content
suite.addBatch({
  "attr": require("./transition-test-attr"),
  "attrTween": require("./transition-test-attrTween"),
  "style": require("./transition-test-style"),
  "styleTween": require("./transition-test-styleTween"),
  "text": require("./transition-test-text"),
  "remove": require("./transition-test-remove")
});

// Animation
suite.addBatch({
  "delay": require("./transition-test-delay"),
  "duration": require("./transition-test-duration")
});

// Control
suite.addBatch({
  "each": require("./transition-test-each"),
  "call": require("./transition-test-call"),
  "tween": require("./transition-test-tween"),
  "id": require("./transition-test-id"),
  "time": require("./transition-test-time")
});

suite.export(module);
<|endoftext|>


<commit_before>/*
in-class exercice:
Create a very simple webserver, which can distribute any found file and handle the case when no file exists
You can start with the help of the about page of the nodejs website: https://nodejs.org/en/about/
*/

var http = require('http'); // We require the http module, needed to handle http request
var fs = require('fs'); // We require the file system to access files

// We create the server
var proxy = http.createServer(function (req, res) {

  var arrayString = req.url.split("?");
  var agmtsString = arrayString[1];
  var agmts = argString.split("&");
  var paramObjet = {};

  for (var i=0; i< agmts.length; i++) {
    var argument = agmts[i].split ("=");
    paramObjet [argument[0]] = argument [1];
  }

  console.log(paramObjet);

  if (/favicon.ico/i.test(req.url)) {
    res.writeHead(404, {'Content-Type': 'text/html'});
    res.end();
  }
  else {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end();
  }

  console.log(req.url);

});

proxy.listen(1337, "127.0.0.1");

console.log('Server running at http://127.0.0.1:1337/');
<commit_msg>Workhome proxy server<commit_after>/*
in-class exercice:
Create a very simple webserver, which can distribute any found file and handle the case when no file exists
You can start with the help of the about page of the nodejs website: https://nodejs.org/en/about/
*/

var http = require('http'); // We require the http module, needed to handle http request
var fs = require('fs'); // We require the file system to access files

// We create the server
var proxy = http.createServer(function (req, res) {

  var arrayString = req.url.split("?");
  var argString = arrayString[1];
  var agmts = argString.split("&");
  var paramObjet = {};

  for (var i=0; i< agmts.length; i++) {
    var argument = agmts[i].split ("=");
    paramObjet [argument[0]] = argument [1];
  }

  console.log("paramObjet", paramObjet.website);

  if (/favicon.ico/i.test(req.url)) {
    res.writeHead(404, {'Content-Type': 'text/html'});
    res.end();
    return;
  }

  var options = {

  		hostname: paramObjet.website

  };

  	http.get(options, function(resp) {
  		resp.on('data', function(chunk) {
  			res.end(chunk);
  		});
  	}).on ('error', function(e) {
  		console.log("Got error: " + e.message);

  	});

  console.log(req.url);

});

proxy.listen(1337, "127.0.0.1");

console.log('Server running at http://127.0.0.1:1337/');
<|endoftext|>


<commit_before>dojo.provide("dijit.ProgressBar");

dojo.require("dojo.fx");
dojo.require("dojo.number");

dojo.require("dijit._Widget");
dojo.require("dijit._Templated");

dojo.declare(
	"dijit.ProgressBar",
	[dijit._Widget, dijit._Templated],
	null,
	{
		// summary:
		// a progress widget, with some calculation and server polling capabilities
		//
		// description:
		// (implementation) four overlapped divs:
		// (1) lower z-index
		// (4) higher z-index
		// empty and full percent label have the same content: when the vertical line (*)
		// partially hides the emptyLabel, the fullLabel becomes visible
		//
		//  ___________________________(1)_domNode____________________________________
		// |__(3)_internalProgress____________                                        |
		// |                                  | <--- (*)                              |
		// |            (4) fullLabel        | (2) emptyLabel                         |
		// |__________________________________|                                       |
		// |__________________________________________________________________________|
		//
		// usage:
		//

		// progress: String (Percentage or Number)
		// initial progress value.
		// with "%": percentage value, 0% <= progress <= 100%
		// or without "%": absolute value, 0 <= progress <= maximum
		progress: "0",

		// maximum: Float
		// max sample number
		maximum: 100,

		// places: Number
		// number of places to show in values; 0 by default
		places: 0,

		// indeterminate: Boolean
		// false: show progress
		// true: show that a process is underway but that the progress is unknown
		indeterminate: false,

		templatePath: dojo.moduleUrl("dijit", "templates/ProgressBar.html"),

		_indeterminateHighContrastImagePath:
			dojo.moduleUrl("dijit", "themes/a11y/indeterminate_progress.gif"),

		// public functions
		postCreate: function(){
			dijit.ProgressBar.superclass.postCreate.apply(this, arguments);

			this.inteterminateHighContrastImage.setAttribute("src",
				this._indeterminateHighContrastImagePath);

			// Vertically center label boxes.  One is absolute positioned, so we cannot do this in CSS, apparently.
			var domNode = this.domNode;
			var align = function(labelNode){
				labelNode.style.bottom =
					(parseInt(dojo.getComputedStyle(domNode).height) - dojo.contentBox(labelNode).h)/2 + 'px';
			};
			align(this.emptyLabel);
			align(this.fullLabel);

			this.update();
		},

		update: function(/*Object?*/attributes){
			// summary: update progress information
			//
			// attributes: may provide progress and/or maximum properties on this parameter,
			//	see attribute specs for details.
			dojo.mixin(this, attributes||{});
			var percent = 1, classFunc;
			if(this.indeterminate){
				classFunc = "addClass";
				dijit.wai.removeAttr(this.internalProgress, "waiState", "valuenow");
			}else{
				classFunc = "removeClass";
				if(String(this.progress).indexOf("%") != -1){
					percent = Math.min(parseFloat(this.progress)/100, 1);
					this.progress = percent * this.maximum;
				}else{
					this.progress = Math.min(this.progress, this.maximum);
					percent = this.progress / this.maximum;
				}
				var text = this.report(percent);
				this.fullLabel.firstChild.nodeValue = this.emptyLabel.firstChild.nodeValue = text;
				dijit.wai.setAttr(this.internalProgress, "waiState", "valuenow", text);
			}
			dojo[classFunc](this.domNode, "dijitProgressBarIndeterminate");
			this.internalProgress.style.width = (percent * 100) + "%";
			this.fullLabel.style.width = (this.progress ? (this.maximum / this.progress) * 100 : 0) + "%";
			this.onChange();
		},

		report: function(/*float*/percent){
			// Generates message to show; may be overridden by user
			return dojo.number.format(percent, {type: "percent", places: this.places, locale: this.lang});
		},

		onChange: function(){}
	}
);
<commit_msg>Remove computed style setting for bottom. Refs #2803<commit_after>dojo.provide("dijit.ProgressBar");

dojo.require("dojo.fx");
dojo.require("dojo.number");

dojo.require("dijit._Widget");
dojo.require("dijit._Templated");

dojo.declare(
	"dijit.ProgressBar",
	[dijit._Widget, dijit._Templated],
	null,
	{
		// summary:
		// a progress widget, with some calculation and server polling capabilities
		//
		// description:
		// (implementation) four overlapped divs:
		// (1) lower z-index
		// (4) higher z-index
		// empty and full percent label have the same content: when the vertical line (*)
		// partially hides the emptyLabel, the fullLabel becomes visible
		//
		//  ___________________________(1)_domNode____________________________________
		// |__(3)_internalProgress____________                                        |
		// |                                  | <--- (*)                              |
		// |            (4) fullLabel        | (2) emptyLabel                         |
		// |__________________________________|                                       |
		// |__________________________________________________________________________|
		//
		// usage:
		//

		// progress: String (Percentage or Number)
		// initial progress value.
		// with "%": percentage value, 0% <= progress <= 100%
		// or without "%": absolute value, 0 <= progress <= maximum
		progress: "0",

		// maximum: Float
		// max sample number
		maximum: 100,

		// places: Number
		// number of places to show in values; 0 by default
		places: 0,

		// indeterminate: Boolean
		// false: show progress
		// true: show that a process is underway but that the progress is unknown
		indeterminate: false,

		templatePath: dojo.moduleUrl("dijit", "templates/ProgressBar.html"),

		_indeterminateHighContrastImagePath:
			dojo.moduleUrl("dijit", "themes/a11y/indeterminate_progress.gif"),

		// public functions
		postCreate: function(){
			dijit.ProgressBar.superclass.postCreate.apply(this, arguments);

			this.inteterminateHighContrastImage.setAttribute("src",
				this._indeterminateHighContrastImagePath);

			this.update();
		},

		update: function(/*Object?*/attributes){
			// summary: update progress information
			//
			// attributes: may provide progress and/or maximum properties on this parameter,
			//	see attribute specs for details.
			dojo.mixin(this, attributes||{});
			var percent = 1, classFunc;
			if(this.indeterminate){
				classFunc = "addClass";
				dijit.wai.removeAttr(this.internalProgress, "waiState", "valuenow");
			}else{
				classFunc = "removeClass";
				if(String(this.progress).indexOf("%") != -1){
					percent = Math.min(parseFloat(this.progress)/100, 1);
					this.progress = percent * this.maximum;
				}else{
					this.progress = Math.min(this.progress, this.maximum);
					percent = this.progress / this.maximum;
				}
				var text = this.report(percent);
				this.fullLabel.firstChild.nodeValue = this.emptyLabel.firstChild.nodeValue = text;
				dijit.wai.setAttr(this.internalProgress, "waiState", "valuenow", text);
			}
			dojo[classFunc](this.domNode, "dijitProgressBarIndeterminate");
			this.internalProgress.style.width = (percent * 100) + "%";
			this.fullLabel.style.width = (this.progress ? (this.maximum / this.progress) * 100 : 0) + "%";
			this.onChange();
		},

		report: function(/*float*/percent){
			// Generates message to show; may be overridden by user
			return dojo.number.format(percent, {type: "percent", places: this.places, locale: this.lang});
		},

		onChange: function(){}
	}
);
<|endoftext|>


<commit_before>/*
 * Main application logic.
 *
 * @author Reuben Bradley <reuben.m.bradley@gmail.com>
 */

// Import the pieces that we need
var express = require('express');
var handlebars = require('express-handlebars');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var MongoClient = require('mongodb').MongoClient;

var CONFIG = require('./config');
var dbConfig = CONFIG.db[CONFIG.env];
var db;

// Connect to the database
var connectString = 'mongodb://' + dbConfig.host + ':' + dbConfig.port +
        '/' + dbConfig.database;
MongoClient.connect(connectString, function( err, database ) {
    if ( err ) {
        return console.log(err);
    }
    db = database;
    // TODO: Import password from "secrets" file!
    db.authenticate(dbConfig.user, dbConfig.password);
});

var handlebarsConfig = {
    extname: '.hbs',
    defaultLayout: 'default'
};

// Define the app
var app = express();
app.engine('hbs', handlebars(handlebarsConfig));
app.set('view engine', 'hbs');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(function( req, res, next ) {
    // Set the database so it's usable on every request
    req.db = db;
    next();
});

// Import the routes
app.use('/', routes);

process.on('exit', function() {
    if ( db ) {
        db.close();
    }
    console.log('Clean getaway ;-)');
});

process.on('SIGINT', function() {
    process.exit();
});

process.on('SIGTERM', function() {
    process.exit();
});

module.exports = app;
<commit_msg>Reorganised termination handlers for backend app<commit_after>/*
 * Main application logic.
 *
 * @author Reuben Bradley <reuben.m.bradley@gmail.com>
 */

// Import the pieces that we need
var express = require('express');
var handlebars = require('express-handlebars');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var MongoClient = require('mongodb').MongoClient;

var CONFIG = require('./config');
var dbConfig = CONFIG.db[CONFIG.env];
var db;

// Connect to the database
var connectString = 'mongodb://' + dbConfig.host + ':' + dbConfig.port +
        '/' + dbConfig.database;
MongoClient.connect(connectString, function( err, database ) {
    if ( err ) {
        return console.log(err);
    }
    db = database;
    // TODO: Import password from "secrets" file!
    db.authenticate(dbConfig.user, dbConfig.password);
});

var handlebarsConfig = {
    extname: '.hbs',
    defaultLayout: 'default'
};

// Define the app
var app = express();
app.engine('hbs', handlebars(handlebarsConfig));
app.set('view engine', 'hbs');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(function( req, res, next ) {
    // Set the database so it's usable on every request
    req.db = db;
    next();
});

// Import the routes
app.use('/', routes);

process.on('SIGHUP', function() {
    console.log('Received SIGHUP. Shutting down ...');
    process.exit();
});

process.on('SIGINT', function() {
    console.log('Received SIGINT. Shutting down ...');
    process.exit();
});

process.on('SIGTERM', function() {
    console.log('Received SIGTERM. Shutting down ...');
    process.exit();
});

process.on('uncaughtException', function( err ) {
    console.log('Uncaught Exception: ', err);
});

process.on('exit', function() {
    if ( db ) {
        try {
            db.close();
        }
        catch (e) {}
    }
    console.log('Clean getaway ;-)');
});

module.exports = app;
<|endoftext|>


<commit_before>"use strict";
var defaultScraper = require("../scrapers/default.js");
var getDestination = defaultScraper.getDestination;
var getDestinations = defaultScraper.getDestinations;
var getLinkStrings = defaultScraper.getLinkStrings;

var md = require("html-md");
// var sjs = require("scraperjs");

var chai = require("chai");
var expect = chai.expect;

chai.use(require("chai-json-schema"));
var result, line;

beforeEach(function () {
  line = "[Madrid](/wiki/Madrid \"Madrid\") - [Madrid Barajas Airport](/wiki/Madrid_Barajas_Airport \"Madrid Barajas Airport\")";

  return result = getDestination(line);
});

describe("getDestination function, it: ", function () {
  var destinationSchema = {
    "title": "destination schema v1",
    "type": "object",
    "required": ["city", "airport"],
    "properties": {
      "city": {
        "type": "object",
        "minItems": 1,
        "uniqueItems": true,
        "required": ["name", "url"],
        "properties": {
          "name": {
            "type": "string"
          },
          "url": {
            "type": "string"
          }
        },
        "items": {
          "type": "string"
        }
      },
      "airport": {
        "type": "object",
        "minItems": 1,
        "uniqueItems": true,
        "required": ["name", "url"],
        "properties": {
          "name": {
            "type": "string"
          },
          "url": {
            "type": "string"
          }
        },
        "items": {
          "type": "string"
        }
      }
    }
  };

  it("Should be a function", function () {
    expect(getDestinations).to.be.a("function");
  });
  it("Should return an object", function () {
    expect(result).to.be.an("object");
  });

  it("Should verify the object's structure", function () {
    expect(result).to.be.jsonSchema(destinationSchema);
  });
});

describe("getDestinations function, it: ", function () {
  var makrdown, makrdownResults;
  // var makrdownResultsSchema = {
  //   "title": "destination schema v1",
  //   "type": "array",
  //   "required": ["city", "airport"],
  //   "properties": {
  //     "city": {
  //       "type": "object",
  //       "minItems": 1,
  //       "uniqueItems": true,
  //       "required": ["name", "url"],
  //       "properties": {
  //         "name": {
  //           "type": "string"
  //         },
  //         "url": {
  //           "type": "string"
  //         }
  //       },
  //       "items": {
  //         "type": "string"
  //       }
  //     },
  //     "airport": {
  //       "type": "object",
  //       "minItems": 1,
  //       "uniqueItems": true,
  //       "required": ["name", "url"],
  //       "properties": {
  //         "name": {
  //           "type": "string"
  //         },
  //         "url": {
  //           "type": "string"
  //         }
  //       },
  //       "items": {
  //         "type": "string"
  //       }
  //     }
  //   }
  // };

  beforeEach(function () {
    makrdown = md("
North America" +
      "[edit]

" +
      "
  United States
" +
      "
 Miami - " +
      "Miami International Airport" +
      "

 Washington, D.C. - " +
      "Washington Dulles" +
      " International Airport

", {
        inline: true
      });
    // sjs.StaticScraper.create("./spec/models/Air Austral - Wikipedia, the free encyclopedia.html")
    //   .scrape(function ($) {
    //     makrdown = md($(".mw-content-ltr").html(), {
    //       inline: true
    //     });
    //   })
    //   .then();
    makrdownResults = getDestinations(makrdown);
  });

  it("Should be a function", function () {
    expect(getDestinations).to.be.a("function");
  });

  it("should return an Array", function () {
    expect(makrdownResults).to.be.an("array");
  });

  it("Shouldn't be an empty array", function () {
    // console.log(makrdownResults.length);
    expect(makrdownResults.length).to.be.above(1);
  });
});

describe("getLinkStrings function, it:", function () {
  var linkStringResult;

  beforeEach(function () {
    linkStringResult = getLinkStrings(line);
  });

  it("Should be a function", function () {
    expect(getLinkStrings).to.be.a("function");
  });

  it("Should return an array ", function () {

    expect(linkStringResult).to.be.an("array");
  });

  it("Shouldn't return an empty array", function () {
    expect(linkStringResult.length).to.be.above(1);
  });
});
<commit_msg>testing failed links<commit_after>"use strict";
var defaultScraper = require("../scrapers/default.js");
var getDestination = defaultScraper.getDestination;
var getDestinations = defaultScraper.getDestinations;
var getLinkStrings = defaultScraper.getLinkStrings;
var hasValidLinks = defaultScraper.hasValidLinks;
var getLinkInfo = defaultScraper.getLinkInfo;

var md = require("html-md");
// var sjs = require("scraperjs");

var chai = require("chai");
var expect = chai.expect;

chai.use(require("chai-json-schema"));
var result, line;

beforeEach(function () {
  line = "[Madrid](/wiki/Madrid \"Madrid\") - [Madrid Barajas Airport](/wiki/Madrid_Barajas_Airport \"Madrid Barajas Airport\")";

  return result = getDestination(line);
});

describe("getDestination function, it: ", function () {
  var destinationSchema = {
    "title": "destination schema v1",
    "type": "object",
    "required": ["city", "airport"],
    "properties": {
      "city": {
        "type": "object",
        "minItems": 1,
        "uniqueItems": true,
        "required": ["name", "url"],
        "properties": {
          "name": {
            "type": "string"
          },
          "url": {
            "type": "string"
          }
        },
        "items": {
          "type": "string"
        }
      },
      "airport": {
        "type": "object",
        "minItems": 1,
        "uniqueItems": true,
        "required": ["name", "url"],
        "properties": {
          "name": {
            "type": "string"
          },
          "url": {
            "type": "string"
          }
        },
        "items": {
          "type": "string"
        }
      }
    }
  };

  it("Should be a function", function () {
    expect(getDestinations).to.be.a("function");
  });
  it("Should return an object", function () {
    expect(result).to.be.an("object");
  });

  it("Should verify the object's structure", function () {
    expect(result).to.be.jsonSchema(destinationSchema);
  });
});

describe("getDestinations function, it: ", function () {
  var makrdown, makrdownResults;
  // var makrdownResultsSchema = {
  //   "title": "destination schema v1",
  //   "type": "array",
  //   "required": ["city", "airport"],
  //   "properties": {
  //     "city": {
  //       "type": "object",
  //       "minItems": 1,
  //       "uniqueItems": true,
  //       "required": ["name", "url"],
  //       "properties": {
  //         "name": {
  //           "type": "string"
  //         },
  //         "url": {
  //           "type": "string"
  //         }
  //       },
  //       "items": {
  //         "type": "string"
  //       }
  //     },
  //     "airport": {
  //       "type": "object",
  //       "minItems": 1,
  //       "uniqueItems": true,
  //       "required": ["name", "url"],
  //       "properties": {
  //         "name": {
  //           "type": "string"
  //         },
  //         "url": {
  //           "type": "string"
  //         }
  //       },
  //       "items": {
  //         "type": "string"
  //       }
  //     }
  //   }
  // };

  beforeEach(function () {
    makrdown = md("
North America" +
      "[edit]

" +
      "
  United States
" +
      "
 Miami - " +
      "Miami International Airport" +
      "

 Washington, D.C. - " +
      "Washington Dulles" +
      " International Airport

", {
        inline: true
      });
    // sjs.StaticScraper.create("./spec/models/Air Austral - Wikipedia, the free encyclopedia.html")
    //   .scrape(function ($) {
    //     makrdown = md($(".mw-content-ltr").html(), {
    //       inline: true
    //     });
    //   })
    //   .then();
    makrdownResults = getDestinations(makrdown);
  });

  it("Should be a function", function () {
    expect(getDestinations).to.be.a("function");
  });

  it("should return an Array", function () {
    expect(makrdownResults).to.be.an("array");
  });

  it("Shouldn't be an empty array", function () {
    // console.log(makrdownResults.length);
    expect(makrdownResults.length).to.be.above(1);
  });
});

describe("getLinkStrings function, it:", function () {
  var linkStringResult;

  beforeEach(function () {
    linkStringResult = getLinkStrings(line);
  });

  it("Should be a function", function () {
    expect(getLinkStrings).to.be.a("function");
  });

  it("Should return an array ", function () {

    expect(linkStringResult).to.be.an("array");
  });

  it("Shouldn't return an empty array", function () {
    expect(linkStringResult.length).to.be.above(1);
  });
});

describe("hasValidLinks function, it:", function () {
  var link, hasValidLinksResult;

  beforeEach(function () {
    link = [
      [
        "[Madrid](/wiki/Madrid \"Madrid\")",
        "Madrid",
        "/wiki/Madrid"
      ],
      [
        "[Madrid Barajas Airport](/wiki/Madrid_Barajas_Airport \"Madrid Barajas Airport\")",
        "Madrid Barajas Airport",
        "/wiki/Madrid_Barajas_Airport"
      ]
    ];
    hasValidLinksResult = hasValidLinks(link);
  });

  it("Should be a function", function () {
    expect(hasValidLinks).to.be.a("function");
  });

  it("Shouldn't return undefined", function() {
    console.log(hasValidLinksResult);
    expect(hasValidLinksResult).to.not.be.undefined;
  });

  it("Should return the last right element", function() {
    expect(hasValidLinksResult).to.match(/^\/wiki\//);
  });
  it("Should check for all the links", function() {
    var link_1_2_false = [
      [
        "[Madrid](/wiki/Madrid \"Madrid\")",
        "Madrid",
        "/wiki/Madrid"
      ],
      [
        "[Madrid Barajas Airport](/wiki/Madrid_Barajas_Airport \"Madrid Barajas Airport\")",
        "",
        "/wiki/Madrid_Barajas_Airport"
      ]
    ];
    var result = hasValidLinks(link_1_2_false);

    expect(result).not.to.be.ok;
  });
});

describe("getLinkInfo function, it:", function () {
  it("Should be a function", function () {
    expect(getLinkInfo).to.be.a("function");
  });
});
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var ipc = require('ipc');
var moment = require('moment');
var Mustache = require('mustache');

import { mainView } from './view/main.js';
import * as Schedule from './model/schedule.js';
import { setSchedule, readForm, setForm } from './controller/html.js';

function injectContent() {
    return new Promise(function(resolve, reject) {
        fs.readFile(__dirname + '/app.mst.html', 'utf-8', function(err, data) {
            if (err) {
                reject(err);
            }
            let view = mainView(Schedule.ids);
            let rendered = Mustache.render(data, view);
            document.getElementById('container').innerHTML = rendered;
            resolve();
        });
    });
}

injectContent()
.then(function() {
    ipc.on('schedule', function(schedule) {
        console.log('Recieved schedule from main process', schedule);

        if (schedule === null) {
            schedule = readForm();
        } else {
            // Config doesn't save all attributes
            let d = readForm();
            for (let a in schedule) { d[a] = schedule[a]; }
            schedule = d;
        }
        setSchedule(Schedule.url(schedule));
        setForm(schedule);
    });

    ipc.send('load-schedule');
})
.then(function() {
    window.addEventListener('unload', function() {
        ipc.send('save-schedule', readForm());
    });

    window.addEventListener('resize', function() {
        // Adjust schedule size
        setSchedule(Schedule.url(readForm()));
    });

    document.getElementById('form').addEventListener('change', function() {
        setSchedule(Schedule.url(readForm()));
    });

    document.getElementById('refresh-button').addEventListener('click', function() {
        ipc.send('reload');
    });

    // If the app is kept open for a long period of time the schedule should
    // still be up to date.
    let timeoutReload = function() {
        setTimeout(function() {
            if (navigator.onLine) {
                ipc.send('reload');
            } else {
                timeoutReload();
            }
        }, moment.duration(30, 'minutes').asMilliseconds());
    }
    timeoutReload();
})
.catch(function(err) {
    console.log(err);
});
<commit_msg>Reload if internet connection is established<commit_after>'use strict';

var fs = require('fs');
var ipc = require('ipc');
var moment = require('moment');
var Mustache = require('mustache');
var util = require('util');

import { mainView } from './view/main.js';
import * as Schedule from './model/schedule.js';
import { setSchedule, readForm, setForm } from './controller/html.js';

function injectContent() {
    return new Promise(function(resolve, reject) {
        fs.readFile(__dirname + '/app.mst.html', 'utf-8', function(err, data) {
            if (err) {
                reject(err);
            }
            let view = mainView(Schedule.ids);
            let rendered = Mustache.render(data, view);
            document.getElementById('container').innerHTML = rendered;
            resolve();
        });
    });
}

injectContent()
.then(function() {
    ipc.on('schedule', function(schedule) {
        console.log('Recieved schedule from main process', schedule);

        if (schedule === null) {
            schedule = readForm();
        } else {
            // Config doesn't save all attributes
            let d = readForm();
            for (let a in schedule) { d[a] = schedule[a]; }
            schedule = d;
        }
        setSchedule(Schedule.url(schedule));
        setForm(schedule);
    });

    ipc.send('load-schedule');
})
.then(function() {
    window.addEventListener('unload', function() {
        ipc.send('save-schedule', readForm());
    });

    window.addEventListener('resize', function() {
        // Adjust schedule size
        setSchedule(Schedule.url(readForm()));
    });

    document.getElementById('form').addEventListener('change', function() {
        setSchedule(Schedule.url(readForm()));
    });

    document.getElementById('refresh-button').addEventListener('click', function() {
        ipc.send('reload');
    });

    window.addEventListener('online', function() {
        util.log('Online event fired');
        ipc.send('reload');
    });

    // If the app is kept open for a long period of time the schedule should
    // still be up to date.
    let timeoutReload = function() {
        setTimeout(function() {
            if (navigator.onLine) {
                ipc.send('reload');
            } else {
                timeoutReload();
            }
        }, moment.duration(30, 'minutes').asMilliseconds());
    }
    timeoutReload();
})
.catch(function(err) {
    console.log(err);
});
<|endoftext|>


<commit_before>

angular.module('ModelSEED',
['config',          // config file for urls, workspace paths, etc
 'core-directives', // a large set of directives.  probably should be broken into components
 'ctrls',           // general controllers
 'ms-ctrls',        // controllers more specific to the ModelSEED site
 'ms-tour',         // controllers related to interactive tour
 'help-ctrls',      // controllers related to help docs.  probably obsolete.
 'DataViewCtrls',   // controllers related to rendering of workspace objects
 'duScroll',        // plugin for hash based scrolling
 'ui.router',       // router for all urls
 'ngMaterial',      // angular material.  main dependency for layout/css, "widgets", etc
 'ngAnimate',       // angular animate.  ngMaterial dependency.
 'ms-rpc',          // module for simplifying with the KBase type compilier RPC requests
 'Auth',            // module for Auth-related requests and state
 'dd-filter',       // custom module for creating searchable dropdowns.
 'mega-dropdown',   // custom module for hover-over dropdowns
 'ng-context-menu', // module for right-click menus (see workspace browser)
 'FBA',
 'ModelViewer',
 'MSSolr',
 'Patric',
 'WS',
 'MS',
 'Upload',
 'UploadCtrl',
 'Biochem',
 'Browser',
 'Regulons',
 'Fusions',
 'Dialogs',
 'docs-directives',
 'Socket',
 'Jobs'
 ])
.config(['$locationProvider', '$stateProvider', '$httpProvider',
         '$urlRouterProvider', '$urlMatcherFactoryProvider', '$sceProvider',
function($locationProvider, $stateProvider, $httpProvider,
         $urlRouterProvider, $urlMatcherFactoryProvider, $sceProvider) {

    $locationProvider.html5Mode(true);
    $sceProvider.enabled(false);
    $urlMatcherFactoryProvider.strictMode(false);

    function valToString(val) {
        return val !== null ? decodeURI(val) : val;
    }

    $urlMatcherFactoryProvider.type('nonURIEncoded', {
        encode: valToString,
        decode: valToString,
        is: function () { return true; }
    });

    $stateProvider
        .state('main', {
            templateUrl: 'app/views/main.html',
        }).state('main.home', {
            url: "/?login&redirect",
            templateUrl: 'app/views/home.html',
            controller: 'Home',
        }).state('main.team', {
            url: "/team",
            templateUrl: 'app/views/docs/team.html',
        }).state('main.teamMember', {
            url: "/team/:name",
            templateUrl: function ($stateParams){
                return 'app/views/docs/team/'+$stateParams.name+'.html';
            },
        }).state('main.publications', {
            url: "/publications",
            templateUrl: 'app/views/docs/publications.html',
            controller: 'Publications'
        })

        // ModelSEED Projects
        .state('main.projects', {
            url: '/projects',
            templateUrl: '/ms-projects/home.html'
        }).state('main.projects.regulons', {
            url: '/regulons?q',
            templateUrl: '/ms-projects/regulons/overview.html',
            controller: 'Regulons'
        })

        .state('main.projects.fusions', {
            url: '/fusions',
            templateUrl: '/ms-projects/fusions/overview.html',
            controller: 'Fusions'
        }).state('main.projects.trainingGene', {
            url: '/fusions/training-gene/:gene',
            templateUrl: '/ms-projects/fusions/training-gene.html',
            controller: 'TrainingGene'
        }).state('main.projects.fusionGene', {
            url: '/fusions/fusion-gene/:gene',
            templateUrl: '/ms-projects/fusions/fusion-gene.html',
            controller: 'FusionGene'
        }).state('main.projects.fusionRole', {
            url: '/fusions/role/:role',
            templateUrl: '/ms-projects/fusions/fusion-role.html',
            controller: 'FusionRole'
        }).state('main.projects.fusionCdd', {
            url: '/fusions/cdd/:cdd',
            templateUrl: '/ms-projects/fusions/fusion-cdd.html',
            controller: 'FusionCDD'
        }).state('main.projects.fusionCddSets', {
            url: '/fusions/cdd-sets/:cdd',
            templateUrl: '/ms-projects/fusions/fusion-cdd-sets.html',
            controller: 'FusionCDDSets'
        }).state('main.projects.fusionGenomeStats', {
            url: '/fusions/genome-stats/:id',
            templateUrl: '/ms-projects/fusions/fusion-genome-stats.html',
            controller: 'FusionGenomeStats'
        }).state('main.projects.fusionReactions', {
            url: '/fusions/reactions/:id',
            templateUrl: '/ms-projects/fusions/fusion-reactions.html',
            controller: 'FusionReactions'
        }).state('main.projects.fusionSubsystems', {
            url: '/fusions/subsystems/:id',
            templateUrl: '/ms-projects/fusions/fusion-subsystems.html',
            controller: 'FusionSubsystems'
        })

        // about pages
        .state('main.about', {
            url: '/about',
            templateUrl: 'app/views/about.html',
        }).state('main.about.version', {
            url: "/version",
            templateUrl: 'app/views/version.html',
            controller: 'Version'
        }).state('main.about.faq', {
            url: "/faq",
            templateUrl: 'app/views/docs/faq.html',
        }).state('main.about.data', {
            url: "/data-sources",
            templateUrl: 'app/views/docs/sources.html',
        }).state('main.api', {
            url: "/about/api",
            templateUrl: 'app/views/docs/api.html',
            controller: 'API'
        })

        // main application template
        .state('app', {
            templateUrl: 'app/views/app.html',
        })

        // main views
        .state('app.biochem', {
            url: "/biochem",
            templateUrl: 'app/views/biochem/biochem.html',
            controller: 'Biochem',
            authenticate: true,
        }).state('app.cpd', {
            // WARNING: external services depend on this URL.
            url: "/biochem/compounds/:id",
            templateUrl: 'app/views/biochem/compound.html',
            controller: 'Compound',
            authenticate: false,
        }).state('app.rxn', {
            // WARNING: external services depend on this URL.
            url: "/biochem/reactions/:id",
            templateUrl: 'app/views/biochem/reaction.html',
            controller: 'Reaction',
            authenticate: false,
        })

        .state('app.plantAnnotations', {
            url: "/plant-annotations/",
            templateUrl: 'app/views/annotations.html',
            controller: 'PlantAnnotations',
            authenticate: true
        }).state('app.genomes', {
            url: "/genomes/",
            templateUrl: 'app/views/genomes/genomes.html',
            controller: 'Genomes',
            authenticate: true
        }).state('app.media', {
            url: "/list-media/?tab",
            templateUrl: 'app/views/media.html',
            controller: 'Media',
            authenticate: true
        }).state('app.myModels', {
            url: "/my-models/",
            templateUrl: 'app/views/my-models.html',
            controller: 'MyModels',
            authenticate: true
        }).state('app.jobs', {
            url: "/my-jobs/",
            templateUrl: 'app/views/my-jobs.html',
            controller: 'Jobs',
            authenticate: true,
            /*resolve: {
                getStatus: function(Jobs) {
                    return Jobs.getStatus()
                }
            }*/
        })

        // data browser
        .state('app.myData', {
            url: "/data{dir:nonURIEncoded}",
            templateUrl: 'app/components/browser/browser.html',
            controller: 'MyData',
            authenticate: true
        }).state('app.modelPage', {
            url: "/model{path:nonURIEncoded}?login",
            templateUrl: 'app/views/data/model.html',
            controller: 'ModelDataView',
            authenticate: true
        }).state('app.fbaPage', {
            url: "/fba{path:nonURIEncoded}",
            templateUrl: 'app/views/data/fba.html',
            controller: 'FBADataView',
            authenticate: true
        }).state('app.genomePage', {
            url: "/genome{path:nonURIEncoded}",
            templateUrl: 'app/views/data/genome.html',
            controller: 'GenomeDataView',
            authenticate: true
        }).state('app.featurePage', {
            url: "/feature{genome:nonURIEncoded}/{feature:nonURIEncoded}",
            templateUrl: 'app/views/data/feature.html',
            controller: 'FeatureDataView',
            authenticate: true
        }).state('app.mediaPage', {
            url: "/media{path:nonURIEncoded}",
            templateUrl: 'app/views/data/media.html',
            controller: 'MediaDataView',
            authenticate: true
        }).state('app.gfPage', {
            url: "/gapfill{path:nonURIEncoded}",
            templateUrl: 'app/views/data/gapfill.html',
            controller: 'GapfillDataView',
            authenticate: true
        })

        // object editors (for media editor, see media view)
        .state('app.modelEditor', {
            url: "/model-editor/",
            templateUrl: 'app/views/editor/model-editor.html',
            controller: 'ModelEditor',
            authenticate: true
        })

        // comparative analysis
        .state('app.compare', {
            url: "/compare",
            templateUrl: 'app/views/compare.html',
            controller: 'Compare',
            authenticate: true
        })

        // prototype page
        .state('app.proto', {
            url: "/proto",
            templateUrl: 'app/views/proto.html',
            /*controller: 'Proto',*/
            authenticate: true
        }).state('app.maps', {
            url: "/maps",
            templateUrl: 'app/views/maps.html',
            controller: 'Maps',
        }).state('app.map', {
            url: "/maps{path:nonURIEncoded}",
            templateUrl: 'app/views/data/map.html',
            controller: 'Map',
        }).state('app.json', {
            url: "/json{path:nonURIEncoded}",
            templateUrl: 'app/views/data/json.html',
            controller: 'Json',
        }).state('app.image', {
            url: "/image{path:nonURIEncoded}",
            templateUrl: 'app/views/data/image.html',
            controller: 'Image',
        })

        .state('app.userStatus', {
            url: "/user-status",
            templateUrl: 'app/views/docs/user-status.html',
            controller: 'UserStatus',
            authenticate: true
        })

        /* only used for testing analysis forms */
        .state('app.run', {
            url: "/run",
            templateUrl: 'app/views/run/run.html',
        }).state('app.runReconstruct', {
            url: "/run/reconstruct",
            templateUrl: 'app/views/apps/reconstruct.html',
            controller: 'RunReconstruct',
        }).state('app.runFBA', {
            url: "/run/fba",
            templateUrl: 'app/views/apps/runFBA.html',
            controller: 'RunFBA',
        }).state('app.runGapfill', {
            url: "/run/gapfill",
            templateUrl: 'app/views/apps/gapfill.html',
            controller: 'RunGapfill',
        })

    // default redirects (when not already authenticated)
    $urlRouterProvider.when('', '/home/')
                      .when('/', '/home/')
                      .when('#', '/home/');

}])

.config(['$mdThemingProvider', function($mdThemingProvider) {
    $mdThemingProvider.theme('default')
        .primaryPalette('cyan')
        .accentPalette('light-blue');
}])

.run(['$rootScope', '$state', '$stateParams', '$window',
      '$location', 'Auth', '$timeout', 'config', 'AuthDialog',
function($rootScope, $state, $sParams, $window,
         $location, auth, $timeout, config, AuthDialog) {

    $rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams){
        // if first load on home and user is authenticated,
        // forward to application page.
        // if not authenticated and url is private, force login.
        if (fromState.name === '' && toState.name === "main.home" && auth.isAuthenticated()) {
            // wait for state digest
            $timeout(function() {
                $state.transitionTo('app.genomes')
                event.preventDefault();
            })
        } else if (toState.authenticate && !auth.isAuthenticated()) {
            // wait for state digest
            $timeout(function() {
                AuthDialog.signIn();
            })
        }

        // google analytics
        $window.ga('send', 'pageview', $location.path());
    })

    $rootScope.$state = $state;
    $rootScope.$stateParams = $sParams;

    $rootScope.user = auth.user;
    $rootScope.token = auth.token;

    $rootScope.includePlants = config.includePlants;

    // instantiate user feedback plugin
    $.feedback({
        ajaxURL: config.services.ms_rest_url+'/feedback',
        html2canvasURL: 'lib/feedback/development/html2canvas.min.js',
    });
}])

.run(['Jobs', function(Jobs) {

    // Note: the jobs service is invoked here (services/jobs.js)
    // which kicks of polling if needed.
    // Order is important so that auth is finished.

}])
<commit_msg>don't require auth for biochem<commit_after>

angular.module('ModelSEED',
['config',          // config file for urls, workspace paths, etc
 'core-directives', // a large set of directives.  probably should be broken into components
 'ctrls',           // general controllers
 'ms-ctrls',        // controllers more specific to the ModelSEED site
 'ms-tour',         // controllers related to interactive tour
 'help-ctrls',      // controllers related to help docs.  probably obsolete.
 'DataViewCtrls',   // controllers related to rendering of workspace objects
 'duScroll',        // plugin for hash based scrolling
 'ui.router',       // router for all urls
 'ngMaterial',      // angular material.  main dependency for layout/css, "widgets", etc
 'ngAnimate',       // angular animate.  ngMaterial dependency.
 'ms-rpc',          // module for simplifying with the KBase type compilier RPC requests
 'Auth',            // module for Auth-related requests and state
 'dd-filter',       // custom module for creating searchable dropdowns.
 'mega-dropdown',   // custom module for hover-over dropdowns
 'ng-context-menu', // module for right-click menus (see workspace browser)
 'FBA',
 'ModelViewer',
 'MSSolr',
 'Patric',
 'WS',
 'MS',
 'Upload',
 'UploadCtrl',
 'Biochem',
 'Browser',
 'Regulons',
 'Fusions',
 'Dialogs',
 'docs-directives',
 'Socket',
 'Jobs'
 ])
.config(['$locationProvider', '$stateProvider', '$httpProvider',
         '$urlRouterProvider', '$urlMatcherFactoryProvider', '$sceProvider',
function($locationProvider, $stateProvider, $httpProvider,
         $urlRouterProvider, $urlMatcherFactoryProvider, $sceProvider) {

    $locationProvider.html5Mode(true);
    $sceProvider.enabled(false);
    $urlMatcherFactoryProvider.strictMode(false);

    function valToString(val) {
        return val !== null ? decodeURI(val) : val;
    }

    $urlMatcherFactoryProvider.type('nonURIEncoded', {
        encode: valToString,
        decode: valToString,
        is: function () { return true; }
    });

    $stateProvider
        .state('main', {
            templateUrl: 'app/views/main.html',
        }).state('main.home', {
            url: "/?login&redirect",
            templateUrl: 'app/views/home.html',
            controller: 'Home',
        }).state('main.team', {
            url: "/team",
            templateUrl: 'app/views/docs/team.html',
        }).state('main.teamMember', {
            url: "/team/:name",
            templateUrl: function ($stateParams){
                return 'app/views/docs/team/'+$stateParams.name+'.html';
            },
        }).state('main.publications', {
            url: "/publications",
            templateUrl: 'app/views/docs/publications.html',
            controller: 'Publications'
        })

        // ModelSEED Projects
        .state('main.projects', {
            url: '/projects',
            templateUrl: '/ms-projects/home.html'
        }).state('main.projects.regulons', {
            url: '/regulons?q',
            templateUrl: '/ms-projects/regulons/overview.html',
            controller: 'Regulons'
        })

        .state('main.projects.fusions', {
            url: '/fusions',
            templateUrl: '/ms-projects/fusions/overview.html',
            controller: 'Fusions'
        }).state('main.projects.trainingGene', {
            url: '/fusions/training-gene/:gene',
            templateUrl: '/ms-projects/fusions/training-gene.html',
            controller: 'TrainingGene'
        }).state('main.projects.fusionGene', {
            url: '/fusions/fusion-gene/:gene',
            templateUrl: '/ms-projects/fusions/fusion-gene.html',
            controller: 'FusionGene'
        }).state('main.projects.fusionRole', {
            url: '/fusions/role/:role',
            templateUrl: '/ms-projects/fusions/fusion-role.html',
            controller: 'FusionRole'
        }).state('main.projects.fusionCdd', {
            url: '/fusions/cdd/:cdd',
            templateUrl: '/ms-projects/fusions/fusion-cdd.html',
            controller: 'FusionCDD'
        }).state('main.projects.fusionCddSets', {
            url: '/fusions/cdd-sets/:cdd',
            templateUrl: '/ms-projects/fusions/fusion-cdd-sets.html',
            controller: 'FusionCDDSets'
        }).state('main.projects.fusionGenomeStats', {
            url: '/fusions/genome-stats/:id',
            templateUrl: '/ms-projects/fusions/fusion-genome-stats.html',
            controller: 'FusionGenomeStats'
        }).state('main.projects.fusionReactions', {
            url: '/fusions/reactions/:id',
            templateUrl: '/ms-projects/fusions/fusion-reactions.html',
            controller: 'FusionReactions'
        }).state('main.projects.fusionSubsystems', {
            url: '/fusions/subsystems/:id',
            templateUrl: '/ms-projects/fusions/fusion-subsystems.html',
            controller: 'FusionSubsystems'
        })

        // about pages
        .state('main.about', {
            url: '/about',
            templateUrl: 'app/views/about.html',
        }).state('main.about.version', {
            url: "/version",
            templateUrl: 'app/views/version.html',
            controller: 'Version'
        }).state('main.about.faq', {
            url: "/faq",
            templateUrl: 'app/views/docs/faq.html',
        }).state('main.about.data', {
            url: "/data-sources",
            templateUrl: 'app/views/docs/sources.html',
        }).state('main.api', {
            url: "/about/api",
            templateUrl: 'app/views/docs/api.html',
            controller: 'API'
        })

        // main application template
        .state('app', {
            templateUrl: 'app/views/app.html',
        })

        // main views
        .state('app.biochem', {
            url: "/biochem",
            templateUrl: 'app/views/biochem/biochem.html',
            controller: 'Biochem'
        }).state('app.cpd', {
            // WARNING: external services depend on this URL.
            url: "/biochem/compounds/:id",
            templateUrl: 'app/views/biochem/compound.html',
            controller: 'Compound'
        }).state('app.rxn', {
            // WARNING: external services depend on this URL.
            url: "/biochem/reactions/:id",
            templateUrl: 'app/views/biochem/reaction.html',
            controller: 'Reaction'
        })

        .state('app.plantAnnotations', {
            url: "/plant-annotations/",
            templateUrl: 'app/views/annotations.html',
            controller: 'PlantAnnotations',
            authenticate: true
        }).state('app.genomes', {
            url: "/genomes/",
            templateUrl: 'app/views/genomes/genomes.html',
            controller: 'Genomes',
            authenticate: true
        }).state('app.media', {
            url: "/list-media/?tab",
            templateUrl: 'app/views/media.html',
            controller: 'Media',
            authenticate: true
        }).state('app.myModels', {
            url: "/my-models/",
            templateUrl: 'app/views/my-models.html',
            controller: 'MyModels',
            authenticate: true
        }).state('app.jobs', {
            url: "/my-jobs/",
            templateUrl: 'app/views/my-jobs.html',
            controller: 'Jobs',
            authenticate: true,
            /*resolve: {
                getStatus: function(Jobs) {
                    return Jobs.getStatus()
                }
            }*/
        })

        // data browser
        .state('app.myData', {
            url: "/data{dir:nonURIEncoded}",
            templateUrl: 'app/components/browser/browser.html',
            controller: 'MyData',
            authenticate: true
        }).state('app.modelPage', {
            url: "/model{path:nonURIEncoded}?login",
            templateUrl: 'app/views/data/model.html',
            controller: 'ModelDataView',
            authenticate: true
        }).state('app.fbaPage', {
            url: "/fba{path:nonURIEncoded}",
            templateUrl: 'app/views/data/fba.html',
            controller: 'FBADataView',
            authenticate: true
        }).state('app.genomePage', {
            url: "/genome{path:nonURIEncoded}",
            templateUrl: 'app/views/data/genome.html',
            controller: 'GenomeDataView',
            authenticate: true
        }).state('app.featurePage', {
            url: "/feature{genome:nonURIEncoded}/{feature:nonURIEncoded}",
            templateUrl: 'app/views/data/feature.html',
            controller: 'FeatureDataView',
            authenticate: true
        }).state('app.mediaPage', {
            url: "/media{path:nonURIEncoded}",
            templateUrl: 'app/views/data/media.html',
            controller: 'MediaDataView',
            authenticate: true
        }).state('app.gfPage', {
            url: "/gapfill{path:nonURIEncoded}",
            templateUrl: 'app/views/data/gapfill.html',
            controller: 'GapfillDataView',
            authenticate: true
        })

        // object editors (for media editor, see media view)
        .state('app.modelEditor', {
            url: "/model-editor/",
            templateUrl: 'app/views/editor/model-editor.html',
            controller: 'ModelEditor',
            authenticate: true
        })

        // comparative analysis
        .state('app.compare', {
            url: "/compare",
            templateUrl: 'app/views/compare.html',
            controller: 'Compare',
            authenticate: true
        })

        // prototype page
        .state('app.proto', {
            url: "/proto",
            templateUrl: 'app/views/proto.html',
            /*controller: 'Proto',*/
            authenticate: true
        }).state('app.maps', {
            url: "/maps",
            templateUrl: 'app/views/maps.html',
            controller: 'Maps',
        }).state('app.map', {
            url: "/maps{path:nonURIEncoded}",
            templateUrl: 'app/views/data/map.html',
            controller: 'Map',
        }).state('app.json', {
            url: "/json{path:nonURIEncoded}",
            templateUrl: 'app/views/data/json.html',
            controller: 'Json',
        }).state('app.image', {
            url: "/image{path:nonURIEncoded}",
            templateUrl: 'app/views/data/image.html',
            controller: 'Image',
        })

        .state('app.userStatus', {
            url: "/user-status",
            templateUrl: 'app/views/docs/user-status.html',
            controller: 'UserStatus',
            authenticate: true
        })

        /* only used for testing analysis forms */
        .state('app.run', {
            url: "/run",
            templateUrl: 'app/views/run/run.html',
        }).state('app.runReconstruct', {
            url: "/run/reconstruct",
            templateUrl: 'app/views/apps/reconstruct.html',
            controller: 'RunReconstruct',
        }).state('app.runFBA', {
            url: "/run/fba",
            templateUrl: 'app/views/apps/runFBA.html',
            controller: 'RunFBA',
        }).state('app.runGapfill', {
            url: "/run/gapfill",
            templateUrl: 'app/views/apps/gapfill.html',
            controller: 'RunGapfill',
        })

    // default redirects (when not already authenticated)
    $urlRouterProvider.when('', '/home/')
                      .when('/', '/home/')
                      .when('#', '/home/');

}])

.config(['$mdThemingProvider', function($mdThemingProvider) {
    $mdThemingProvider.theme('default')
        .primaryPalette('cyan')
        .accentPalette('light-blue');
}])

.run(['$rootScope', '$state', '$stateParams', '$window',
      '$location', 'Auth', '$timeout', 'config', 'AuthDialog',
function($rootScope, $state, $sParams, $window,
         $location, auth, $timeout, config, AuthDialog) {

    $rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams){
        // if first load on home and user is authenticated,
        // forward to application page.
        // if not authenticated and url is private, force login.
        if (fromState.name === '' && toState.name === "main.home" && auth.isAuthenticated()) {
            // wait for state digest
            $timeout(function() {
                $state.transitionTo('app.genomes')
                event.preventDefault();
            })
        } else if (toState.authenticate && !auth.isAuthenticated()) {
            // wait for state digest
            $timeout(function() {
                AuthDialog.signIn();
            })
        }

        // google analytics
        $window.ga('send', 'pageview', $location.path());
    })

    $rootScope.$state = $state;
    $rootScope.$stateParams = $sParams;

    $rootScope.user = auth.user;
    $rootScope.token = auth.token;

    $rootScope.includePlants = config.includePlants;

    // instantiate user feedback plugin
    $.feedback({
        ajaxURL: config.services.ms_rest_url+'/feedback',
        html2canvasURL: 'lib/feedback/development/html2canvas.min.js',
    });
}])

.run(['Jobs', function(Jobs) {

    // Note: the jobs service is invoked here (services/jobs.js)
    // which kicks of polling if needed.
    // Order is important so that auth is finished.

}])
<|endoftext|>


<commit_before>import Ember from 'ember';
import Resolver from 'ember/resolver';
import loadInitializers from 'ember/load-initializers';
import config from './config/environment';

Ember.MODEL_FACTORY_INJECTIONS = true;

var App = Ember.Application.extend({
  modulePrefix: config.modulePrefix,
  podModulePrefix: config.podModulePrefix,
  Resolver: Resolver
});

loadInitializers(App, config.modulePrefix);

export default App;
<commit_msg>4/14 push to olli dev site version 1.13<commit_after>import Ember from 'ember';
import Resolver from 'ember/resolver';
import loadInitializers from 'ember/load-initializers';
import config from './config/environment';

Ember.MODEL_FACTORY_INJECTIONS = true;

var App = Ember.Application.extend({
  //modulePrefix: config.modulePrefix,
  modulePrefix: 'jolli',
  podModulePrefix: config.podModulePrefix,
  Resolver: Resolver
});

loadInitializers(App, config.modulePrefix);

export default App;
<|endoftext|>


<commit_before>'use strict';

angular.module('myApp', [
    'ngResource',
    'ngMoment',
    'ngAnimate'
]).factory('Resource', ['$resource', function($resource) {
    function resource() {
        return $resource('', null, {
            list: {
                method: 'GET',
                url: "data/contents.json"
            }
        })
    }
    return {
        list: function() {
            return resource().list().$promise;
        }
    };
}]).factory('History', [function() {
    return {
        getList: function() {
            var histories = localStorage.getItem("histories");
            if (histories === null) {
                histories = [];
            } else {
                histories = JSON.parse(histories);
            }

            return histories;
        },
        setList: function(histories) {
            localStorage.setItem("histories", JSON.stringify(histories));
        },
        getListForName: function(name) {
            return _.filter(this.getList(), function(h) {return h.name === name; });
        }

    }
}]).controller("Controller", ['Resource', 'History', '$moment', function(Resource, History, $moment) {
    $moment.locale(["ja"]);

    Resource.list().then(_.bind(function(json) {
        this.items = _.map(json.items, function(item) {
            item.counts = _.size(History.getListForName(item.name));
            item.points = _.reduce(History.getListForName(item.name), function(memo, h) { return memo + h.point; }, 0);
            item.point = json.type[item.type].point;
            item.bonus = json.type[Math.min(parseInt(item.type) + 1, 6)].point;
            return item;
        });
        this.type = json.type;

        this.counts = _.reduce(this.items, function(memo, item) {return memo + item.counts}, 0);
        this.points = _.reduce(this.items, function(memo, item) {return memo + item.points}, 0);
    }, this), function(error) {
        console.log(error);
    });

    this.histories = _.map(_.first(History.getList(), 11), function(history) {
        history.createdAt = $moment(history.created_at).format('LLL');
        return history;
    });

    this.doRecord = function(name, point) {
        var histories = History.getList();
        var history = {name: name, point: point, created_at: Date.now()};
        histories.unshift(history);
        History.setList(histories);
        history.createdAt = $moment(history.created_at).format('LLL');
        this.histories.unshift(history);
    };

    this.deleteRecord = _.bind(function(history) {
        var histories = History.getList();
        for(var i = 0; i < histories.length; ++i) {
            var h = histories[i];
            if (h.name === history.name && h.point == history.point && h.created_at == history.created_at) {
                histories.splice(i, 1);
                this.histories.splice(i, 1);
                History.setList(histories);

                this.counts -= 1;
                this.points -= h.point;
                break;
            }
        }
    }, this);

    this.doUpdate = _.bind(function(item, point) {
        item.counts += 1;
        this.counts += 1;
        item.points += point;
        this.points += point;
    }, this);

}]);
<commit_msg>対象アイテムも動的に変更されるように<commit_after>'use strict';

angular.module('myApp', [
    'ngResource',
    'ngMoment',
    'ngAnimate'
]).factory('Resource', ['$resource', function($resource) {
    function resource() {
        return $resource('', null, {
            list: {
                method: 'GET',
                url: "data/contents.json"
            }
        })
    }
    return {
        list: function() {
            return resource().list().$promise;
        }
    };
}]).factory('History', [function() {
    return {
        getList: function() {
            var histories = localStorage.getItem("histories");
            if (histories === null) {
                histories = [];
            } else {
                histories = JSON.parse(histories);
            }

            return histories;
        },
        setList: function(histories) {
            localStorage.setItem("histories", JSON.stringify(histories));
        },
        getListForName: function(name) {
            return _.filter(this.getList(), function(h) {return h.name === name; });
        }

    }
}]).controller("Controller", ['Resource', 'History', '$moment', function(Resource, History, $moment) {
    $moment.locale(["ja"]);

    Resource.list().then(_.bind(function(json) {
        this.items = _.map(json.items, function(item) {
            item.counts = _.size(History.getListForName(item.name));
            item.points = _.reduce(History.getListForName(item.name), function(memo, h) { return memo + h.point; }, 0);
            item.point = json.type[item.type].point;
            item.bonus = json.type[Math.min(parseInt(item.type) + 1, 6)].point;
            return item;
        });
        this.type = json.type;

        this.counts = _.reduce(this.items, function(memo, item) {return memo + item.counts}, 0);
        this.points = _.reduce(this.items, function(memo, item) {return memo + item.points}, 0);
    }, this), function(error) {
        console.log(error);
    });

    this.histories = _.map(_.first(History.getList(), 11), function(history) {
        history.createdAt = $moment(history.created_at).format('LLL');
        return history;
    });

    this.doRecord = function(name, point) {
        var histories = History.getList();
        var history = {name: name, point: point, created_at: Date.now()};
        histories.unshift(history);
        History.setList(histories);
        history.createdAt = $moment(history.created_at).format('LLL');
        this.histories.unshift(history);
    };

    this.deleteRecord = _.bind(function(history) {
        var histories = History.getList();
        for(var i = 0; i < histories.length; ++i) {
            var h = histories[i];
            if (h.name === history.name && h.point == history.point && h.created_at == history.created_at) {
                histories.splice(i, 1);
                this.histories.splice(i, 1);
                History.setList(histories);

                this.counts -= 1;
                this.points -= h.point;
                var item = _.find(this.items, function(item){ return item.name === h.name; });
                item.counts -= 1;
                item.points -= h.point;
                break;
            }
        }
    }, this);

    this.doUpdate = _.bind(function(item, point) {
        item.counts += 1;
        this.counts += 1;
        item.points += point;
        this.points += point;
    }, this);

}]);
<|endoftext|>


<commit_before>var http = require('http');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.end('
Innovadiv - Entertainment Consultation

Contact lscullark@innovadiv.com for more details
');
}).listen(80);

console.log('app running...');<commit_msg>added logo<commit_after>var http = require('http');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.end('

Innovadiv - Entertainment Consultation

Contact lscullark@innovadiv.com for more details.
');
}).listen(80);

console.log('app running...');<|endoftext|>


<commit_before>import React from 'react'
import { render } from 'react-dom'
import { Router, Route, browserHistory } from 'react-router'
import childRoutes from './utils/urls'
import Library from './components/Library'

const routes = {
  path: '/',
  component: Library,
  childRoutes
}

render((
  <Router history={browserHistory} routes={routes} />
), document.getElementById('app'))
<commit_msg>use hashHistory as it works with SimpleHTTPServer<commit_after>import React from 'react'
import { render } from 'react-dom'
import { Router, Route, hashHistory } from 'react-router'
import childRoutes from './utils/urls'
import Library from './components/Library'

const routes = {
  path: '/',
  component: Library,
  childRoutes
}

render((
  <Router history={hashHistory} routes={routes} />
), document.getElementById('app'))
<|endoftext|>