<commit_before>var async = require('async');
var request = require('request');
var constants = require('./../lib/constants');
var elasticsearch = require('./../lib/elasticsearch');
var invoker = require('./../lib/invoker');

var TITLE = constants.TITLE;

function index(req, res) {
  if (req.isAuthenticated()) {
    res.redirect('/folders/0');
  } else {
    res.render('index', { title: TITLE });
  }
}

function folders(req, res) {
  invoker.folder(req.session.passport.user.accessToken, req.params.id, function(err, result) {
    if (err) {
      console.error(err);
      res.send(500);
    } else {
      result.item_collection.entries.forEach(function(entry) {
        entry.href = '/' + entry.type + 's/' + entry.id;
      });
      res.render('folders', { title: TITLE, result: result });
    }
  });
}

function files(req, res) {
  invoker.file(req.session.passport.user.accessToken, req.params.id, function(err, result) {
    if (err) {
      console.error(err);
      res.send(500);
    } else {
      res.render('files', { title: TITLE, result: result });
    }
  });
}

function download(req, res) {
  request.get({
    headers: { Authorization: "Bearer " + req.session.passport.user.accessToken },
    url: constants.CONTENT_API_BASE + '/files/' + req.params.id + '/content'
  }).pipe(res);
}

function view(req, res) {
  async.parallel({
    file: function (callback) {
      invoker.file(req.session.passport.user.accessToken, req.params.id, callback);
    },
    documents: function (callback) {
      invoker.documents(callback);
    }
  }, function (err, result) {
    if (err) {
      console.error(err);
      res.send(500);
      return;
    }
    if (result.documents.document_collection.entries.some(function(entry) {
      return entry.name === req.params.id && new Date(result.file.modified_at) < new Date(entry.created_at);
    })) {
      var id = result.documents.document_collection.entries.filter(function(entry) {
        return entry.name === req.params.id && new Date(result.file.modified_at) < new Date(entry.created_at);
      }).shift().id;
      invoker.sessions(id, function(err, result) {
        if (err) {
          console.error(err);
          res.send(500);
          return;
        }
        res.redirect(result.urls.view);
      });
    } else {
      async.waterfall([
        function (callback) {
          invoker.location(req.session.passport.user.accessToken, req.params.id, callback);
        },
        function (url, callback) {
          invoker.upload(url, req.params.id, callback);
        },
        function (body, callback) {
          invoker.sessions(body.id, callback);
        }
      ], function (err, result) {
        if (err) {
          console.error(err);
          res.send(500);
          return;
        }
        res.redirect(result.urls.view);
      });
    }
  });
}

function indexing(userId, token, id, callback) {
  async.waterfall([
    function(callback) {
      async.parallel({
        file: function (callback) {
          invoker.file(token, id, callback);
        },
        documents: function (callback) {
          invoker.documents(callback);
        }
      }, callback);
    },
    function(result, callback) {
      if (result.documents.document_collection.entries.some(function (entry) {
        return entry.name === id && new Date(result.file.modified_at) < new Date(entry.created_at);
      })) {
        callback(null, {
          file: result.file,
          id:   result.documents.document_collection.entries.filter(function (entry) {
            return entry.name === id && new Date(result.file.modified_at) < new Date(entry.created_at);
          }).shift().id
        });
      } else {
        async.waterfall([
          function (callback) {
            invoker.location(token, id, callback);
          },
          function (url, callback) {
            invoker.upload(url, id, callback);
          }
        ], function(err, id) {
          callback(err, { file: result.file, id: id });
        });
      }
    },
    function(result, callback) {
      elasticsearch.documents(result.file.id, userId, function(err, documents) {
        var modified = new Date(result.file.modified_at);
        var isUpdated = documents.every(function(document) {
          return document._source.modified === result.file.modified_at || new Date(document._source.modified) === modified;
        });
        if (isUpdated) {
          callback();
          return;
        }
        async.waterfall([
          function (callback) {
            invoker.extract(result.id, callback);
          },
          function (text, callback) {
            elasticsearch.upsertDocument(documents, result.file.id, result.file.name, result.file.modified_at, result.file.created_by.id, text, callback);
          }
        ], callback);
      });
    }
  ], callback);
}

function documents(req, res) {
  invoker.documents(function(err, result) {
    if (err) {
      console.error(err);
      res.send(500);
      return;
    }
    res.render('documents', { title: TITLE, result: result });
  });
}

function zip(req, res) {
  request.get({
    headers: { Authorization: "Token " + process.env.API_KEY },
    url: constants.VIEW_API_BASE + '/documents/' + req.params.id + '/content.zip'
  }).pipe(res);
}

function pdf(req, res) {
  request.get({
    headers: { Authorization: "Token " + process.env.API_KEY },
    url: constants.VIEW_API_BASE + '/documents/' + req.params.id + '/content.pdf'
  }).pipe(res);
}

function createIndex(req, res) {
  if (typeof req.params.id !== 'string') {
    res.send(400);
    return;
  }
  indexing(req.session.passport.user.id, req.session.passport.user.accessToken, req.params.id, function(err, result) {
    if (err) {
      res.send(500);
      console.error(err);
      return;
    }
    res.send(result);
  });
}

function search(req, res) {
  if (typeof req.query.query !== 'string' || req.query.query === '') {
    res.send(400);
    return;
  }
  elasticsearch.search(req.session.passport.user.id, req.query.query, function(err, result) {
    if (err) {
      res.send(500);
      console.error(err);
      return;
    }
    res.render('search', { title: TITLE, result: result, query: req.query.query });
  });
}

exports.index = index;
exports.folders = folders;
exports.files = files;
exports.download = download;
exports.view = view;
exports.documents = documents;
exports.zip = zip;
exports.pdf = pdf;
exports.createIndex = createIndex;
exports.search = search;
<commit_msg>Fixed a bug to misjudge 'isUpdated'.<commit_after>var async = require('async');
var request = require('request');
var constants = require('./../lib/constants');
var elasticsearch = require('./../lib/elasticsearch');
var invoker = require('./../lib/invoker');

var TITLE = constants.TITLE;

function index(req, res) {
  if (req.isAuthenticated()) {
    res.redirect('/folders/0');
  } else {
    res.render('index', { title: TITLE });
  }
}

function folders(req, res) {
  invoker.folder(req.session.passport.user.accessToken, req.params.id, function(err, result) {
    if (err) {
      console.error(err);
      res.send(500);
    } else {
      result.item_collection.entries.forEach(function(entry) {
        entry.href = '/' + entry.type + 's/' + entry.id;
      });
      res.render('folders', { title: TITLE, result: result });
    }
  });
}

function files(req, res) {
  invoker.file(req.session.passport.user.accessToken, req.params.id, function(err, result) {
    if (err) {
      console.error(err);
      res.send(500);
    } else {
      res.render('files', { title: TITLE, result: result });
    }
  });
}

function download(req, res) {
  request.get({
    headers: { Authorization: "Bearer " + req.session.passport.user.accessToken },
    url: constants.CONTENT_API_BASE + '/files/' + req.params.id + '/content'
  }).pipe(res);
}

function view(req, res) {
  async.parallel({
    file: function (callback) {
      invoker.file(req.session.passport.user.accessToken, req.params.id, callback);
    },
    documents: function (callback) {
      invoker.documents(callback);
    }
  }, function (err, result) {
    if (err) {
      console.error(err);
      res.send(500);
      return;
    }
    if (result.documents.document_collection.entries.some(function(entry) {
      return entry.name === req.params.id && new Date(result.file.modified_at) < new Date(entry.created_at);
    })) {
      var id = result.documents.document_collection.entries.filter(function(entry) {
        return entry.name === req.params.id && new Date(result.file.modified_at) < new Date(entry.created_at);
      }).shift().id;
      invoker.sessions(id, function(err, result) {
        if (err) {
          console.error(err);
          res.send(500);
          return;
        }
        res.redirect(result.urls.view);
      });
    } else {
      async.waterfall([
        function (callback) {
          invoker.location(req.session.passport.user.accessToken, req.params.id, callback);
        },
        function (url, callback) {
          invoker.upload(url, req.params.id, callback);
        },
        function (body, callback) {
          invoker.sessions(body.id, callback);
        }
      ], function (err, result) {
        if (err) {
          console.error(err);
          res.send(500);
          return;
        }
        res.redirect(result.urls.view);
      });
    }
  });
}

function indexing(userId, token, id, callback) {
  async.waterfall([
    function(callback) {
      async.parallel({
        file: function (callback) {
          invoker.file(token, id, callback);
        },
        documents: function (callback) {
          invoker.documents(callback);
        }
      }, callback);
    },
    function(result, callback) {
      if (result.documents.document_collection.entries.some(function (entry) {
        return entry.name === id && new Date(result.file.modified_at) < new Date(entry.created_at);
      })) {
        callback(null, {
          file: result.file,
          id:   result.documents.document_collection.entries.filter(function (entry) {
            return entry.name === id && new Date(result.file.modified_at) < new Date(entry.created_at);
          }).shift().id
        });
      } else {
        async.waterfall([
          function (callback) {
            invoker.location(token, id, callback);
          },
          function (url, callback) {
            invoker.upload(url, id, callback);
          }
        ], function(err, id) {
          callback(err, { file: result.file, id: id });
        });
      }
    },
    function(result, callback) {
      elasticsearch.documents(result.file.id, userId, function(err, documents) {
        if (documents.length > 0) {
          var modified = new Date(result.file.modified_at);
          var isUpdated = documents.every(function (document) {
            return document._source.modified === result.file.modified_at || new Date(document._source.modified) === modified;
          });
          if (isUpdated) {
            callback();
            return;
          }
        }
        async.waterfall([
          function (callback) {
            invoker.extract(result.id, callback);
          },
          function (text, callback) {
            elasticsearch.upsertDocument(documents, result.file.id, result.file.name, result.file.modified_at, result.file.created_by.id, text, callback);
          }
        ], callback);
      });
    }
  ], callback);
}

function documents(req, res) {
  invoker.documents(function(err, result) {
    if (err) {
      console.error(err);
      res.send(500);
      return;
    }
    res.render('documents', { title: TITLE, result: result });
  });
}

function zip(req, res) {
  request.get({
    headers: { Authorization: "Token " + process.env.API_KEY },
    url: constants.VIEW_API_BASE + '/documents/' + req.params.id + '/content.zip'
  }).pipe(res);
}

function pdf(req, res) {
  request.get({
    headers: { Authorization: "Token " + process.env.API_KEY },
    url: constants.VIEW_API_BASE + '/documents/' + req.params.id + '/content.pdf'
  }).pipe(res);
}

function createIndex(req, res) {
  if (typeof req.params.id !== 'string') {
    res.send(400);
    return;
  }
  indexing(req.session.passport.user.id, req.session.passport.user.accessToken, req.params.id, function(err, result) {
    if (err) {
      res.send(500);
      console.error(err);
      return;
    }
    res.send(result);
  });
}

function search(req, res) {
  if (typeof req.query.query !== 'string' || req.query.query === '') {
    res.send(400);
    return;
  }
  elasticsearch.search(req.session.passport.user.id, req.query.query, function(err, result) {
    if (err) {
      res.send(500);
      console.error(err);
      return;
    }
    res.render('search', { title: TITLE, result: result, query: req.query.query });
  });
}

exports.index = index;
exports.folders = folders;
exports.files = files;
exports.download = download;
exports.view = view;
exports.documents = documents;
exports.zip = zip;
exports.pdf = pdf;
exports.createIndex = createIndex;
exports.search = search;
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();

var quizController = require('../controllers/quiz_controller');

// Página de entrada (home page)
router.get('/', function(req, res) {
  res.render('index', { title: 'Quiz' });
});

// Autoload de comandos con :quizId
router.param('quizId', quizController.load);  // autoload :quizId

// Definición de rutas de /quizes
router.get('/quizes',                      quizController.index);
router.get('/quizes/:quizId(\\d+)',        quizController.show);
router.get('/quizes/:quizId(\\d+)/answer', quizController.answer);

router.get('/autor', function(req, res) {
  res.render('autor', { title: 'Autor' });
});

module.exports = router;
<commit_msg>Quiz (M7.1) con DB + Multipr. + Autoload<commit_after>var express = require('express');
var router = express.Router();

var quizController = require('../controllers/quiz_controller');

// Página de entrada (home page)

router.get('/', function(req, res) {
  res.render('index', { title: 'Quiz' });
});

// Autoload de comandos con :quizId
router.param('quizId', quizController.load);  // autoload :quizId

// Definición de rutas de /quizes
router.get('/quizes',                      quizController.index);
router.get('/quizes/:quizId(\\d+)',        quizController.show);
router.get('/quizes/:quizId(\\d+)/answer', quizController.answer);

router.get('/autor', function(req, res) {
  res.render('autor', { title: 'Autor' });
});

module.exports = router;
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Posts = require('../dbModels/posts.js');
var privKey = require('./privKey.js');
var bodyParser = require('body-parser');
var recaptcha = require('express-recaptcha');

recaptcha.init('6LcpzREUAAAAAMb2qn7aobDAldkSgBX_fq7tpOXj', global.privKey);

/* GET home page and specify variables. */
router.get('/', function(req, res, next) {
    Posts.count({}, function(err, documentCount){
	if (documentCount > 100) {
	    Posts.find({}).sort({"date": 1}).skip(documentCount-100).limit(100).exec( function(err, postData) {
		if (err) return next(err);
		res.render('index-paginated', { post: postData, page: 0, count: 100 });
	    });
	}
	else {
	    Posts.find({}).sort({"date": 1}).exec( function(err, postData) {
		if (err) return next(err);
		res.render('index', { post: postData, count: documentCount });
	    });
	}
    });
});

router.get('/page/:page', function(req, res, next) {
    Posts.count({}, function(err, documentCount) {
	if (documentCount%100 != 0 && req.params.page >= parseInt(documentCount/100)) {
	    Posts.find({}).sort({"date": 1}).limit(documentCount%100).exec( function(err, postData) {
		if (err) return next(err);
		res.render('index', { post: postData, count: documentCount%100 });
	    });
	}
	else {
	    Posts.find({}).sort({"date": 1}).skip(documentCount-(100*req.params.page)).limit(100).exec( function(err, postData) {
		if (err) return next(err);
		res.render('index-paginated', { post: postData, page: req.params.page, count: 100 });
	    });
	}
    });
});

router.get('/tag/:tag', function(req, res, next) {
    Posts.count({tags: req.params.tag }, function(err, documentCount) {
	if (documentCount > 100) {
	    Posts.find({tags: req.params.tag}).sort({"date": 1}).skip(documentCount-100).limit(100).exec( function(err, postData) {
		if (err) return next(err);
		res.render('tag/index-paginated', { post: postData, page: 0, count: 100 });
	    });
	}
	else {
	    Posts.find({tags: req.params.tag}).sort({"date": 1}).exec( function(err, postData) {
		if (err) return next(err);
		res.render('index', { post: postData, count: documentCount });
	    });
	}
    });
});

router.get('/tag/:tag/page/:page', function(req, res, next) {
    Posts.count({tags: req.params.tag}, function(err, documentCount) {
	if (documentCount%100 != 0 && req.params.page >= parseInt(documentCount/100)) {
	    Posts.find({tags: req.params.tag}).limit(documentCount%100).exec( function(err, postData) {
		res.render('index', { post: postData, count: documentCount%100 });
	    });
	}
	else {
	    Posts.find({tags: req.params.tag}).skip(documentCount-(100*req.params.page)).limit(100).exec( function(err, postData) {
		if (err) return next(err);
		res.render('tag/index-paginated', { post: postData, page: req.params.page, count: 100});
	    });
	}
    });
});

router.get('/postId/:id', function (req, res, next) {
    Posts.findById(req.params.id, function(err, postData) {
	if(err) res.send(err);
	res.render('postId/index', { post: postData });
    });
});

router.get('/Text', function(req, res, next) {
    res.render('Text/index', { captcha:recaptcha.render() });
});

router.get('/Image', function(req, res, next) {
    res.render('Image/index');
});

/* POST request to /newText creates new text post */
router.post('/newText', function(req, res, next) {
    recaptcha.verify(req, function(error) {
	if(!error) {
	    var type = req.body.type;
	    var title = req.body.title;
	    var content = req.body.content;
	    var tags = req.body.tags;
	    var tagsSplit = tags.split(', ');

	    if (tags.indexOf('#') != -1 || tags.indexOf('$') != -1 || tags.indexOf(';') != -1) {
		res.send(res.render('error/tagParsing'));
	    }
	    else {
	    if (title != null) {
		title = title.replace(/</g, "<").replace(/>/g, ">");
	    }
	    if (content != null) {
		content = content.replace(/</g, "<").replace(/>/g, ">");
	    }
	    for (var i = 0; i < tagsSplit.length; i++) {
		if (tagsSplit[i] != null) {
		    tagsSplit[i] = tagsSplit[i].replace(/</g, "<").replace(/>/g, ">");
		}
	    }

	    Posts.create({type: type, title: title, content: content, tags: tagsSplit}, function(err, textPost) {
		if (err) return next(err);
		res.send(res.render('post/new', {postId: textPost._id}));
	    });
	    }
	}
	else {
	    res.send(res.render('error/reCAPTCHA'));
	}
    });
});

router.post('/newImage', function(req, res, next) {
    recaptcha.verify(req, function(error) {
	if(!error) {
	    var type = req.body.type;
	    var title = req.body.title;
	    var content = req.body.content;
	    var contentSplit = content.split(', ');
	    var caption = req.body.caption;
	    var tags = req.body.tags;
	    var tagsSplit = tags.split(', ');
	    if (tags.indexOf('#') != -1 || tags.indexOf('$') != -1 || tags.indexOf(';') != -1) {
		res.send(res.render('error/tagParsing'));
	    }
	    Posts.create({type: type, title: title, content: contentSplit, caption: caption, tags: tagsSplit}, function(err, imagePost) {
		if (err) return next(err);
		res.send(res.render('post/new', {postId: imagePost._id}));
	    });
	}
	else {
	    res.send(res.render('error/reCAPTCHA'));
	}
    });
});

router.get('/tag/:tag', function (req, res, next) {
    Posts.count({tags: req.params.tag}, function(err, postCount) {
	Posts.find({tags: req.params.tag}, function(err, postData) {
	    res.render('index', {post: postData, count: postCount});
	});
    });
});

module.exports = router;
<commit_msg>add view count increment for every index page load, change method of searching by tag to make it possible to do multiple at a time, implement method to exclude by tag(s), changes to integrate into one index.jade format<commit_after>var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Posts = require('../dbModels/posts.js');
var privKey = require('./privKey.js');
var bodyParser = require('body-parser');
var recaptcha = require('express-recaptcha');

recaptcha.init('6LcpzREUAAAAAMb2qn7aobDAldkSgBX_fq7tpOXj', global.privKey);

/*function getMultiplePosts(limit, viewLimit, page, tag) {

}

function getSinglePost(id) {
    Posts.findById(id, function(err, postData) {
	if(err) res.send(err);
	res.render('index', {post: postData, pageIdentifier: "single", count: 1});
    });
}*/

// GET home page and specify variables.
router.get('/', function(req, res, next) {
    Posts.count({}, function(err, documentCount){
	if (documentCount > 100) {
	    Posts.find({}).sort({"date": 1}).skip(documentCount-100).limit(100).exec( function(err, postData) {
		if (err) return next(err);
		res.render('index', { post: postData, page: 0, count: 100, pageIdentifier: "paginated" });
	    });
	}
	else {
	    Posts.find({}).sort({"date": 1}).exec( function(err, postData) {
		if (err) return next(err);
		res.render('index', { post: postData, count: documentCount });
	    });
	}
	Posts.find({}).sort({"date": -1})/*.skip(documentCount-100)*/.limit(20).exec( function(err, data) {
            var v = Posts.update({"_id": {$in: data}}, {$inc: {"views": 1}}, {multi: true});
            v.exec(function(err) {
		if (err) return next(err);
            });
	});

    });
});

router.get('/page/:page', function(req, res, next) {
    Posts.count({}, function(err, documentCount) {
	if (documentCount%100 != 0 && req.params.page >= parseInt(documentCount/100)) {
	    Posts.find({}).sort({"date": 1}).limit(documentCount%100).exec( function(err, postData) {
		if (err) return next(err);
		res.render('index', { post: postData, count: documentCount%100 });
	    });
	}
	else {
	    Posts.find({}).sort({"date": 1}).skip(documentCount-(100*req.params.page)).limit(100).exec( function(err, postData) {
		if (err) return next(err);
		res.render('index', { post: postData, page: req.params.page, count: 100, pageIdentifier: "paginated" });
	    });
	}
	Posts.find({}).sort({"date": -1}).skip(req.params.page*100).limit(20).exec( function(err, data) {
	    var v = Posts.update({"_id": {$in: data}}, {$inc: {"views": 1}}, {multi: true});
	});
    });
});

router.get('/tag/:tag', function(req, res, next) {
    var allTags = req.params.tag;
    var tagSplit = allTags.split(', ');
    Posts.count({tags: { $all: tagSplit } }, function(err, documentCount) {
	if (documentCount > 100) {
	    Posts.find({tags: { $all: tagSplit } }).sort({"date": 1}).skip(documentCount-100).limit(100).exec( function(err, postData) {
		if (err) return next(err);
		res.render('index', { post: postData, page: 0, count: 100, pageIdentifier: "paginated" });
	    });
	}
	else {
	    Posts.find({tags: { $all: tagSplit } }).sort({"date": 1}).exec( function(err, postData) {
		if (err) return next(err);
		res.render('index', { post: postData, count: documentCount });
	    });
	}
    });
});

router.get('/tag/:tag/page/:page', function(req, res, next) {
    var allTags = req.params.tag;
    var tagSplit = allTags.split(', ');
    Posts.count({tags: { $all: tagSplit }}, function(err, documentCount) {
	if (documentCount%100 != 0 && req.params.page >= parseInt(documentCount/100)) {
	    Posts.find({tags: { $all: tagSplit } }).limit(documentCount%100).exec( function(err, postData) {
		res.render('index', { post: postData, count: documentCount%100 });
	    });
	}
	else {
	    Posts.find({tags: { $all: tagSplit } }).skip(documentCount-(100*req.params.page)).limit(100).exec( function(err, postData) {
		if (err) return next(err);
		res.render('index', { post: postData, page: req.params.page, count: 100, pageIdentifier: "paginated-tag", tag: req.params.tag });
	    });
	}
    });
});

router.get('/exclude/:tag', function(req, res, next) {
    var allTags = req.params.tag;
    var tagSplit = allTags.split(', ');
    Posts.count({tags: { $nin: tagSplit } }).exec( function(err, documentCount) {
	if (documentCount > 100) {
	    Posts.find({tags: { $nin: tagSplit } }).sort({"date": 1}).skip(documentCount-100).limit(100).exec( function(err, postData) {
		if (err) return next(err);
		res.render('index', { post: postData, page: 0, count: 100, pageIdentifier: "paginated" });
	    });
	}
	else {
	    Posts.find({tags: { $nin: tagSplit } }).sort({"date": 1}).exec( function(err, postData) {
		if (err) return next(err);
		console.log(req.params.tag);
		res.render('index', { post: postData, count: documentCount });
	    });
	}
    });
});

router.get('/postId/:id', function (req, res, next) {
    Posts.find({"_id": req.params.id}, function(err, postData) {
	if(err) res.send(err);
	res.render('index', { post: postData, count: 1 });
    });
    //getSinglePost(req.params.id);
});

router.get('/Text', function(req, res, next) {
    res.render('Text/index', { captcha:recaptcha.render() });
});

router.get('/Image', function(req, res, next) {
    res.render('Image/index');
});

/* POST request to /newText creates new text post */
router.post('/newText', function(req, res, next) {
    recaptcha.verify(req, function(error) {
	if(!error) {
	    var type = req.body.type;
	    var title = req.body.title;
	    var content = req.body.content;
	    var tags = req.body.tags;
	    var tagsSplit = tags.split(', ');
	    var views = req.body.views;

	    if (tags.indexOf('#') != -1 || tags.indexOf('$') != -1 || tags.indexOf(';') != -1) {
		res.send(res.render('error/tagParsing'));
	    }
	    else {
	    if (title != null) {
		title = title.replace(/</g, "<").replace(/>/g, ">");
	    }
	    if (content != null) {
		content = content.replace(/</g, "<").replace(/>/g, ">");
	    }
	    for (var i = 0; i < tagsSplit.length; i++) {
		if (tagsSplit[i] != null) {
		    tagsSplit[i] = tagsSplit[i].replace(/</g, "<").replace(/>/g, ">");
		}
	    }

		Posts.create({type: type, title: title, content: content, tags: tagsSplit, views: views}, function(err, textPost) {
		if (err) return next(err);
		res.send(res.render('post/new', {postId: textPost._id}));
	    });
	    }
	}
	else {
	    res.send(res.render('error/reCAPTCHA'));
	}
    });
});

router.post('/newImage', function(req, res, next) {
    recaptcha.verify(req, function(error) {
	if(!error) {
	    var type = req.body.type;
	    var title = req.body.title;
	    var content = req.body.content;
	    var contentSplit = content.split(', ');
	    var caption = req.body.caption;
	    var tags = req.body.tags;
	    var tagsSplit = tags.split(', ');
	    if (tags.indexOf('#') != -1 || tags.indexOf('$') != -1 || tags.indexOf(';') != -1) {
		res.send(res.render('error/tagParsing'));
	    }
	    Posts.create({type: type, title: title, content: contentSplit, caption: caption, tags: tagsSplit}, function(err, imagePost) {
		if (err) return next(err);
		res.send(res.render('post/new', {postId: imagePost._id}));
	    });
	}
	else {
	    res.send(res.render('error/reCAPTCHA'));
	}
    });
});

router.get('/tag/:tag', function (req, res, next) {
    Posts.count({tags: req.params.tag}, function(err, postCount) {
	Posts.find({tags: req.params.tag}, function(err, postData) {
	    res.render('index', {post: postData, count: postCount});
	});
    });
});

module.exports = router;
<|endoftext|>


<commit_before>var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('pluses.db');
var express = require('express');
var router = express.Router();
var request = require('request');
var http = require('http');
var querystring = require('querystring');
var sys = require('sys')
var exec = require('child_process').exec;
function puts(error, stdout, stderr) { sys.puts(stdout) }

router.post('/', function(req, res) {
	// Replace spaces in request
	var term = req.body.text.replace(/^\./g, ''),
        parts = term.split(" "),
        command = parts[0],
        args = parts.slice(1).join(" "),
		finishCall = function(item) {
			res.end(JSON.stringify({text: item}));
		};
    if (parts[1]) {
        var nick = parts[1],
            nick = nick.replace(/[^a-zA-z0-9_ \.-]/g, '');
    }
    var leaderboard = function (table) {
        db.all("SELECT nick, pluses FROM " + table + " ORDER BY pluses DESC LIMIT 10", function (err, rows) {
            var leaders = table.charAt(0).toUpperCase() + table.slice(1) + " Leaderboard:\n";
            var i = 0;
            rows.forEach(function (row) {
                i++;
                leaders += i + ". " + row.pluses + " " + row.nick + "\n";
            });
            finishCall(leaders);
        });
    }

    var add_one = function(table, nick, req) {
        if (nick != req.body.user_name) {
            console.log("|" + nick + "| incremented " + table);
            db.run("INSERT OR IGNORE INTO " + table + " VALUES (?, 0)", nick);
            db.run("UPDATE " + table + " SET pluses = pluses + 1 WHERE nick = ?", nick);

            db.get("SELECT pluses FROM " + table + " WHERE nick = ?", nick, function (err, row) {
                finishCall(nick + " now has " + row.pluses + " " + table);
            });
        } else {
            finishCall("nice try");
        }
    }

    var sub_one = function(table, nick, req) {
        console.log("|" + req.body.user_name + "| tried to decrement" + table);
        db.run("INSERT OR IGNORE INTO " + table + " VALUES (?, 0)", req.body.user_name);
        db.run("UPDATE " + table + " SET pluses = pluses - 1 WHERE nick = ?", req.body.user_name);

        db.get("SELECT pluses FROM " + table + " WHERE nick = ?", req.body.user_name, function (err, row) {
            finishCall("Don't be a meanie! " + req.body.user_name + " now has " + row.pluses + " " + table);
        });
    }

    switch (command) {
        case "increment":
        case "pluses":
        case "plus":
            if (!nick) {
                leaderboard("pluses");
            } else {
                add_one("pluses", nick, req);
            }
            break;
        case "decrement":
            sub_one("pluses", nick, req);
            break;
        case "troll":
        case "trolls":
            if (!nick) {
                leaderboard("trolls");
            } else {
                add_one("trolls", nick);
            }
            break;
        case "summon":
        case "gif":
            var options = {
                host: 'www.google.com',
                port: 80,
                path: "/search?tbm=isch&q=" + encodeURIComponent(args),
                method: 'GET',
                headers: {
                    'user-agent': 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)'
                }
            };
            var req = http.get(options,
                function(res) {
                    res.setEncoding('utf8');
                    res.on('data', function (chunk) {
                        var matches = chunk.match(/imgurl=(.*?)&/g);
                        if (matches) {
                            finishCall(matches[0].replace(/^imgurl=/, '').replace(/&$/, ''));
                        }
                    });
                }
            ).on("error", function (e) {
                finishCall("Got error: " + e.message);
            });
            break;
        case 'g':
        case 'google':
            var tmp = []
            var qs = querystring.stringify(args);
            var options = {
                host: 'ajax.googleapis.com',
                port: 80,
                path: '/ajax/services/search/web?v=1.0&rsz=large&start=0&q=' + encodeURIComponent(args),
                method: 'GET',
                headers: {
                    'user-agent': 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)'
                }
            };
            var req = http.request(options,
                function(res) {
                    res.setEncoding('utf8');
                    res.on('data', function (chunk) {
                        tmp.push(chunk);
                    });

                    res.on('end', function (e) {
                        body = tmp.join('');
                        var result = JSON.parse(body);
                        finishCall(
                            result.responseData.results[0].titleNoFormatting + " @ " +
                            result.responseData.results[0].unescapedUrl
                        );
                    });
                }
            ).on("error", function (e) {
                finishCall("Got error: " + e.message);
            });
            req.end();
            break;
        case 'source':
            finishCall('https://github.com/jayson/SlackCat');
            break;
        case 'gitup':
            exec("git pull", function (error, stdout, stderr) {
                finishCall(stdout + "\n" + stderr);
            });
            break;
    }
});

module.exports = router;
<commit_msg>Adding resummon<commit_after>var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('pluses.db');
var express = require('express');
var router = express.Router();
var request = require('request');
var http = require('http');
var querystring = require('querystring');
var sys = require('sys')
var exec = require('child_process').exec;
function puts(error, stdout, stderr) { sys.puts(stdout) }
var image_index = 0;
var rando = false;

router.post('/', function(req, res) {
	// Replace spaces in request
	var term = req.body.text.replace(/^\./g, ''),
        parts = term.split(" "),
        command = parts[0],
        args = parts.slice(1).join(" "),
		finishCall = function(item) {
			res.end(JSON.stringify({text: item}));
		};
    if (parts[1]) {
        var nick = parts[1],
            nick = nick.replace(/[^a-zA-z0-9_ \.-]/g, '');
    }
    var leaderboard = function (table) {
        db.all("SELECT nick, pluses FROM " + table + " ORDER BY pluses DESC LIMIT 10", function (err, rows) {
            var leaders = table.charAt(0).toUpperCase() + table.slice(1) + " Leaderboard:\n";
            var i = 0;
            rows.forEach(function (row) {
                i++;
                leaders += i + ". " + row.pluses + " " + row.nick + "\n";
            });
            finishCall(leaders);
        });
    }

    var add_one = function(table, nick, req) {
        if (nick != req.body.user_name) {
            console.log("|" + nick + "| incremented " + table);
            db.run("INSERT OR IGNORE INTO " + table + " VALUES (?, 0)", nick);
            db.run("UPDATE " + table + " SET pluses = pluses + 1 WHERE nick = ?", nick);

            db.get("SELECT pluses FROM " + table + " WHERE nick = ?", nick, function (err, row) {
                finishCall(nick + " now has " + row.pluses + " " + table);
            });
        } else {
            finishCall("nice try");
        }
    }

    var sub_one = function(table, nick, req) {
        console.log("|" + req.body.user_name + "| tried to decrement" + table);
        db.run("INSERT OR IGNORE INTO " + table + " VALUES (?, 0)", req.body.user_name);
        db.run("UPDATE " + table + " SET pluses = pluses - 1 WHERE nick = ?", req.body.user_name);

        db.get("SELECT pluses FROM " + table + " WHERE nick = ?", req.body.user_name, function (err, row) {
            finishCall("Don't be a meanie! " + req.body.user_name + " now has " + row.pluses + " " + table);
        });
    }

    switch (command) {
        case "increment":
        case "pluses":
        case "plus":
            if (!nick) {
                leaderboard("pluses");
            } else {
                add_one("pluses", nick, req);
            }
            break;
        case "decrement":
            sub_one("pluses", nick, req);
            break;
        case "troll":
        case "trolls":
            if (!nick) {
                leaderboard("trolls");
            } else {
                add_one("trolls", nick);
            }
            break;
        case "resummon":
            rando = true;
        case "summon":
        case "gif":
            var options = {
                host: 'www.google.com',
                port: 80,
                path: "/search?tbm=isch&q=" + encodeURIComponent(args),
                method: 'GET',
                headers: {
                    'user-agent': 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)'
                }
            };
            var tmpist = [];
            var req = http.get(options,
                function(res) {
                    res.setEncoding('utf8');
                    res.on('data', function (chunk) {
                        tmpist.push(chunk);
                    });

                    res.on('end', function (e) {
                        chunk = tmpist.join('');

                        var matches = chunk.match(/imgurl=(.*?)&/g);
                        if (matches) {
                            if (rando) {
                                image_index = Math.floor(Math.random() * matches.length);
                            }
                            var match = matches[image_index];
                            console.log(match);
                            rando = false;
                            finishCall(match.replace(/^imgurl=/, '').replace(/&$/, ''));
                        }
                    });
                }
            ).on("error", function (e) {
                finishCall("Got error: " + e.message);
            });

            break;
        case 'g':
        case 'google':
            var tmp = []
            var qs = querystring.stringify(args);
            var options = {
                host: 'ajax.googleapis.com',
                port: 80,
                path: '/ajax/services/search/web?v=1.0&rsz=large&start=0&q=' + encodeURIComponent(args),
                method: 'GET',
                headers: {
                    'user-agent': 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)'
                }
            };
            var req = http.request(options,
                function(res) {
                    res.setEncoding('utf8');
                    res.on('data', function (chunk) {
                        tmp.push(chunk);
                    });

                    res.on('end', function (e) {
                        body = tmp.join('');
                        var result = JSON.parse(body);
                        finishCall(
                            result.responseData.results[0].titleNoFormatting + " @ " +
                            result.responseData.results[0].unescapedUrl
                        );
                    });
                }
            ).on("error", function (e) {
                finishCall("Got error: " + e.message);
            });
            req.end();
            break;
        case 'source':
            finishCall('https://github.com/jayson/SlackCat');
            break;
        case 'gitup':
            exec("git pull", function (error, stdout, stderr) {
                finishCall(stdout + "\n" + stderr);
            });
            break;
    }
});

module.exports = router;
<|endoftext|>


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

  app.get('/', function (req, res){
    res.render('index', {title:'Rock, Paper Scissors Game'});
  });

  users = {};
  users[0] = {user_id: 0, name: "Tommy the Computer"};
  cplay=["Rock", "Paper", "Scissors"]
  room={}

  app.io.on('connection', function (req) {
  	console.log('New User Connected', req.id);
  });

  app.io.route('user_connect', function (req, res){
  	req.io.broadcast('new_user_added', { name: req.data.name, user_id: req.socket.id});
    req.io.emit('user_added', { name: req.data.name, user_id: req.socket.id, users_connected: users});
    users[req.socket.id] = {user_id: req.socket.id, name: req.data.name};
  });

  app.io.route('issue_challenge', function (req){
    if (req.data.player2==0){
      var roomissue={player1: req.data.player1, player2: req.data.player2}
      req.io.route('accepted', roomissue);
    }else{
      app.io.broadcast('challenge', {player1: req.data.player1, player1_name: users[req.data.player1].name, player2: req.data.player2, player2_name: users[req.data.player2].name})
    }
  });

  app.io.route('accepted', function (req){
    if (req.data.player2==0){
      req.io.join(req.data.player1)
      room[eq.data.player1] = {room_id: req.data.player1, player1: users[req.data.player1], player2: users[req.data.player2]}
      console.log('room', room);
      app.io.room(req.data.player1).broadcast('room_create', room)
    } else {
      req.io.join(req.data.player2)
      room[req.data.player2] = {room_id: req.data.player2, player1: users[req.data.player1], player2: users[req.data.player2]}
      console.log('room', room);
      app.io.room(req.data.player2).broadcast('room_create', room)
    }
  })

  app.io.route('denied', function (req){
    room[req.data.player2] = {room_id: req.data.player2, player1: users[req.data.player1], player2: users[req.data.player2]};
    delete room[req.data.player2];
    app.io.room(req.data.player2).broadcast('denied', room);
  })

  app.io.route('play', function (req){
    if (room[req.data.room].player2==0){
      compplay = cplay[(Math.random(2)+1)];
      console.log(compplay);
      req.io.room(req.data.room).broadcast('round', compplay)
    } else {
      req.io.room(req.data.room).broadcast('round', req.data.play)
    }
  })

  app.io.route('quit', function (req){
    delete room[req.data.room]
    req.io.room(req.data.room).broadcast('user_quit')
  })

 	app.io.route('disconnect', function (req){
 		console.log('User disconnected', req.socket.id);
    delete users[req.socket.id];
 		req.io.broadcast('user_disconnect', { user_id: req.socket.id});
 	});

}<commit_msg>req fix<commit_after>module.exports = function Route(app){

  app.get('/', function (req, res){
    res.render('index', {title:'Rock, Paper Scissors Game'});
  });

  users = {};
  users[0] = {user_id: 0, name: "Tommy the Computer"};
  cplay=["Rock", "Paper", "Scissors"]
  room={}

  app.io.on('connection', function (req) {
  	console.log('New User Connected', req.id);
  });

  app.io.route('user_connect', function (req, res){
  	req.io.broadcast('new_user_added', { name: req.data.name, user_id: req.socket.id});
    req.io.emit('user_added', { name: req.data.name, user_id: req.socket.id, users_connected: users});
    users[req.socket.id] = {user_id: req.socket.id, name: req.data.name};
  });

  app.io.route('issue_challenge', function (req){
    if (req.data.player2==0){
      var roomissue={player1: req.data.player1, player2: req.data.player2}
      req.io.route('accepted', roomissue);
    }else{
      app.io.broadcast('challenge', {player1: req.data.player1, player1_name: users[req.data.player1].name, player2: req.data.player2, player2_name: users[req.data.player2].name})
    }
  });

  app.io.route('accepted', function (req){
    if (req.data.player2==0){
      req.io.join(req.data.player1)
      room[req.data.player1] = {room_id: req.data.player1, player1: users[req.data.player1], player2: users[req.data.player2]}
      console.log('room', room);
      app.io.room(req.data.player1).broadcast('room_create', room)
    } else {
      req.io.join(req.data.player2)
      room[req.data.player2] = {room_id: req.data.player2, player1: users[req.data.player1], player2: users[req.data.player2]}
      console.log('room', room);
      app.io.room(req.data.player2).broadcast('room_create', room)
    }
  })

  app.io.route('denied', function (req){
    room[req.data.player2] = {room_id: req.data.player2, player1: users[req.data.player1], player2: users[req.data.player2]};
    delete room[req.data.player2];
    app.io.room(req.data.player2).broadcast('denied', room);
  })

  app.io.route('play', function (req){
    if (room[req.data.room].player2==0){
      compplay = cplay[(Math.random(2)+1)];
      console.log(compplay);
      req.io.room(req.data.room).broadcast('round', compplay)
    } else {
      req.io.room(req.data.room).broadcast('round', req.data.play)
    }
  })

  app.io.route('quit', function (req){
    delete room[req.data.room]
    req.io.room(req.data.room).broadcast('user_quit')
  })

 	app.io.route('disconnect', function (req){
 		console.log('User disconnected', req.socket.id);
    delete users[req.socket.id];
 		req.io.broadcast('user_disconnect', { user_id: req.socket.id});
 	});

}<|endoftext|>


<commit_before>import styled from 'styled-components'
import { Box } from '../../components/Primitives'

// this component basically exists as a giant stylesheet that inherits from the theme
// it's for markdown content (hence the name)
// it's kind of a b
const MarkdownContent = styled(Box)`
  /* Vertical Rhythm */
  & > * {
    /* reset all margins */
    margin-top: 0;
    margin-bottom: 0;

    /* margin top to all child elements */
    & + * {
      margin-top: ${({ theme }) => theme.space[3]};
    }

    /* bigger margin top on headers */
    & + h1,
    & + h2 {
      margin-top: ${({ theme }) => theme.space[5]};
    }

    & + h3,
    & + h4 {
      margin-top: ${({ theme }) => theme.space[4]};
    }
  }

  h1,
  h2,
  h3,
  h4,
  h5,
  h6 {
    line-height: ${({ theme }) => theme.lineHeights.title};
  }

  p,
  ul,
  ol,
  dl,
  address {
    max-width: 33em;
  }

  /* Headers */
  h1 {
    font-size: ${({ theme }) => theme.fontSizes[3]};
    font-weight: 600;

    @media (min-width: ${({ theme }) => theme.breakpoints[0]}) {
      font-size: ${({ theme }) => theme.fontSizes[4]};
    }
  }

  h2 {
    font-size: ${({ theme }) => theme.fontSizes[2]};
    font-weight: 600;

    @media (min-width: ${({ theme }) => theme.breakpoints[0]}) {
      font-size: ${({ theme }) => theme.fontSizes[3]};
    }
  }

  h3 {
    font-size: ${({ theme }) => theme.fontSizes[1]};
    font-weight: 600;

    @media (min-width: ${({ theme }) => theme.breakpoints[0]}) {
      font-size: ${({ theme }) => theme.fontSizes[2]};
    }
  }

  h4,
  h5,
  h6 {
    font-size: ${({ theme }) => theme.fontSizes[1]};
    font-weight: 500;

    @media (min-width: ${({ theme }) => theme.breakpoints[0]}) {
      font-size: ${({ theme }) => theme.fontSizes[2]};
    }
  }

  h1 code,
  h2 code,
  h3 code,
  h4 code,
  h5 code,
  h6 code {
    background-color: transparent;
    color: inherit;
  }

  /* Type Elements */

  hr {
    width: 100%;
    max-width: 4rem;
    margin-left: 0;
    margin-right: 0;
    border: ${({ theme }) => theme.borders[1]}
      ${({ theme }) => theme.colors.orange};
    margin: ${({ theme }) => theme.space[4]} 0;
  }

  ul,
  ol,
  dl {
    padding-left: ${({ theme }) => theme.space[4]};
  }

  ul ul,
  ol ol,
  ul ol,
  ol ul {
    margin-top: 0;
    margin-bottom: 0;
  }

  b,
  strong,
  em,
  small,
  code {
    line-height: 1;
  }

  sup,
  sub {
    vertical-align: baseline;
    position: relative;
    top: -0.4em;
  }

  sub {
    top: 0.4em;
  }

  a {
    color: ${({ theme }) => theme.colors.darkGrey};
    text-decoration: underline;
    text-decoration-color: ${({ theme }) => theme.colors.orange};

    &:hover {
      color: ${({ theme }) => theme.colors.orange};
    }

    @media print {
      &:after {
        content: ' (' attr(href) ')';
        font-size: 0.875em;
      }
      &[href^='/']:after {
        content: ' (https://lowmess.com' attr(href) ')';
      }
      &[href^='#'] {
        text-decoration: none;

        &:after {
          content: '';
        }
      }
    }
  }

  blockquote,
  details {
    margin-top: ${({ theme }) => theme.space[4]};
    margin-right: 0;
    margin-bottom: ${({ theme }) => theme.space[4]};
    margin-left: 0;
    border-left: ${({ theme }) => theme.borders[3]}
      ${({ theme }) => theme.colors.orange};
    border-radius: ${({ theme }) => theme.radii[1]};
    padding: ${({ theme }) => theme.space[3]};
    background-color: ${({ theme }) => theme.colors.nearWhite};

    p {
      max-width: 30em;
    }

    > :first-child {
      margin-top: 0;
    }
    > :last-child {
      margin-bottom: 0;
    }
  }

  code {
    font-family: ${({ theme }) => theme.fonts.monospace};
  }

  p code,
  li code {
    border: 1px solid rgba(0, 0, 0, 0.1);
    border-radius: ${({ theme }) => theme.radii[1]};
    padding-left: ${({ theme }) => theme.space[1]};
    padding-right: ${({ theme }) => theme.space[1]};
    background-color: ${({ theme }) => theme.colors.nearWhite};
    color: ${({ theme }) => theme.colors.darkGrey};
    font-size: ${({ theme }) => theme.fontSizes[0]};
    white-space: nowrap;

    @media (min-width: ${({ theme }) => theme.breakpoints[0]}) {
      font-size: ${({ theme }) => theme.fontSizes[1]};
    }
  }

  pre {
    width: 100%;
    overflow-x: scroll;
    margin-top: ${({ theme }) => theme.space[4]};
    margin-bottom: ${({ theme }) => theme.space[4]};
    border-left: ${({ theme }) => theme.borders[3]}
      ${({ theme }) => theme.colors.orange};
    border-radius: ${({ theme }) => theme.radii[1]};
    padding: ${({ theme }) => theme.space[3]};
    background-color: ${({ theme }) => theme.colors.nearBlack};
    color: ${({ theme }) => theme.colors.nearWhite};
    font-size: ${({ theme }) => theme.fontSizes[0]};
    font-family: ${({ theme }) => theme.fonts.monospace};
    white-space: pre;

    @media (min-width: ${({ theme }) => theme.breakpoints[0]}) {
      font-size: ${({ theme }) => theme.fontSizes[1]};
    }

    @media print {
      background-color: transparent;
      color: ${({ theme }) => theme.colors.darkGrey};
    }
  }

  img {
    display: block;
    width: 100%;
    max-width: 48rem;
    margin-top: ${({ theme }) => theme.space[4]};
    margin-bottom: ${({ theme }) => theme.space[4]};
    border-radius: ${({ theme }) => theme.radii[1]};
  }

  iframe {
    margin-top: ${({ theme }) => theme.space[4]};
    margin-bottom: ${({ theme }) => theme.space[4]};
    border: 1px solid ${({ theme }) => theme.colors.grey};
  }
`

export default MarkdownContent
<commit_msg>:lipstick: change color of code links on hover<commit_after>import styled from 'styled-components'
import { Box } from '../../components/Primitives'

// this component basically exists as a giant stylesheet that inherits from the theme
// it's for markdown content (hence the name)
// it's kind of a b
const MarkdownContent = styled(Box)`
  /* Vertical Rhythm */
  & > * {
    /* reset all margins */
    margin-top: 0;
    margin-bottom: 0;

    /* margin top to all child elements */
    & + * {
      margin-top: ${({ theme }) => theme.space[3]};
    }

    /* bigger margin top on headers */
    & + h1,
    & + h2 {
      margin-top: ${({ theme }) => theme.space[5]};
    }

    & + h3,
    & + h4 {
      margin-top: ${({ theme }) => theme.space[4]};
    }
  }

  h1,
  h2,
  h3,
  h4,
  h5,
  h6 {
    line-height: ${({ theme }) => theme.lineHeights.title};
  }

  p,
  ul,
  ol,
  dl,
  address {
    max-width: 33em;
  }

  /* Headers */
  h1 {
    font-size: ${({ theme }) => theme.fontSizes[3]};
    font-weight: 600;

    @media (min-width: ${({ theme }) => theme.breakpoints[0]}) {
      font-size: ${({ theme }) => theme.fontSizes[4]};
    }
  }

  h2 {
    font-size: ${({ theme }) => theme.fontSizes[2]};
    font-weight: 600;

    @media (min-width: ${({ theme }) => theme.breakpoints[0]}) {
      font-size: ${({ theme }) => theme.fontSizes[3]};
    }
  }

  h3 {
    font-size: ${({ theme }) => theme.fontSizes[1]};
    font-weight: 600;

    @media (min-width: ${({ theme }) => theme.breakpoints[0]}) {
      font-size: ${({ theme }) => theme.fontSizes[2]};
    }
  }

  h4,
  h5,
  h6 {
    font-size: ${({ theme }) => theme.fontSizes[1]};
    font-weight: 500;

    @media (min-width: ${({ theme }) => theme.breakpoints[0]}) {
      font-size: ${({ theme }) => theme.fontSizes[2]};
    }
  }

  h1 code,
  h2 code,
  h3 code,
  h4 code,
  h5 code,
  h6 code {
    background-color: transparent;
    color: inherit;
  }

  /* Type Elements */

  hr {
    width: 100%;
    max-width: 4rem;
    margin-left: 0;
    margin-right: 0;
    border: ${({ theme }) => theme.borders[1]}
      ${({ theme }) => theme.colors.orange};
    margin: ${({ theme }) => theme.space[4]} 0;
  }

  ul,
  ol,
  dl {
    padding-left: ${({ theme }) => theme.space[4]};
  }

  ul ul,
  ol ol,
  ul ol,
  ol ul {
    margin-top: 0;
    margin-bottom: 0;
  }

  b,
  strong,
  em,
  small,
  code {
    line-height: 1;
  }

  sup,
  sub {
    vertical-align: baseline;
    position: relative;
    top: -0.4em;
  }

  sub {
    top: 0.4em;
  }

  a {
    color: ${({ theme }) => theme.colors.darkGrey};
    text-decoration: underline;
    text-decoration-color: ${({ theme }) => theme.colors.orange};

    &:hover,
    &:hover code {
      color: ${({ theme }) => theme.colors.orange};
    }

    @media print {
      &:after {
        content: ' (' attr(href) ')';
        font-size: 0.875em;
      }
      &[href^='/']:after {
        content: ' (https://lowmess.com' attr(href) ')';
      }
      &[href^='#'] {
        text-decoration: none;

        &:after {
          content: '';
        }
      }
    }
  }

  blockquote,
  details {
    margin-top: ${({ theme }) => theme.space[4]};
    margin-right: 0;
    margin-bottom: ${({ theme }) => theme.space[4]};
    margin-left: 0;
    border-left: ${({ theme }) => theme.borders[3]}
      ${({ theme }) => theme.colors.orange};
    border-radius: ${({ theme }) => theme.radii[1]};
    padding: ${({ theme }) => theme.space[3]};
    background-color: ${({ theme }) => theme.colors.nearWhite};

    p {
      max-width: 30em;
    }

    > :first-child {
      margin-top: 0;
    }
    > :last-child {
      margin-bottom: 0;
    }
  }

  code {
    font-family: ${({ theme }) => theme.fonts.monospace};
  }

  p code,
  li code {
    border: 1px solid rgba(0, 0, 0, 0.1);
    border-radius: ${({ theme }) => theme.radii[1]};
    padding-left: ${({ theme }) => theme.space[1]};
    padding-right: ${({ theme }) => theme.space[1]};
    background-color: ${({ theme }) => theme.colors.nearWhite};
    color: ${({ theme }) => theme.colors.darkGrey};
    font-size: ${({ theme }) => theme.fontSizes[0]};
    white-space: nowrap;

    @media (min-width: ${({ theme }) => theme.breakpoints[0]}) {
      font-size: ${({ theme }) => theme.fontSizes[1]};
    }
  }

  pre {
    width: 100%;
    overflow-x: scroll;
    margin-top: ${({ theme }) => theme.space[4]};
    margin-bottom: ${({ theme }) => theme.space[4]};
    border-left: ${({ theme }) => theme.borders[3]}
      ${({ theme }) => theme.colors.orange};
    border-radius: ${({ theme }) => theme.radii[1]};
    padding: ${({ theme }) => theme.space[3]};
    background-color: ${({ theme }) => theme.colors.nearBlack};
    color: ${({ theme }) => theme.colors.nearWhite};
    font-size: ${({ theme }) => theme.fontSizes[0]};
    font-family: ${({ theme }) => theme.fonts.monospace};
    white-space: pre;

    @media (min-width: ${({ theme }) => theme.breakpoints[0]}) {
      font-size: ${({ theme }) => theme.fontSizes[1]};
    }

    @media print {
      background-color: transparent;
      color: ${({ theme }) => theme.colors.darkGrey};
    }
  }

  img {
    display: block;
    width: 100%;
    max-width: 48rem;
    margin-top: ${({ theme }) => theme.space[4]};
    margin-bottom: ${({ theme }) => theme.space[4]};
    border-radius: ${({ theme }) => theme.radii[1]};
  }

  iframe {
    margin-top: ${({ theme }) => theme.space[4]};
    margin-bottom: ${({ theme }) => theme.space[4]};
    border: 1px solid ${({ theme }) => theme.colors.grey};
  }
`

export default MarkdownContent
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();

var fs = require('fs')
var words = JSON.parse(fs.readFileSync('gre-words.json', 'utf8'))

console.log(words);

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;
<commit_msg>Implements trie construction from json<commit_after>var express = require('express');
var router = express.Router();
var fs = require('fs');
var words = JSON.parse(fs.readFileSync('routes/gre-words.json', 'utf8'));
var trie = {};

function add_word(word,meaning) {
  var curr = trie
  for(var i = 0; i < word.length;i++){
    letter = word[i];
    if(letter in curr){
      curr = curr[letter];
    }else{
      curr[letter] = {};
      curr = curr[letter];
    }
  }
  curr['_end_'] = true;
  curr['_meaning_'] = meaning;
}

function search_word(word){
  var curr = trie;
  for(var i = 0; i < word.length; i++) {
    var letter = word[i];
    if(letter in curr){
      curr = curr[letter];
    }else{
      return undefined
    }
  }
  if(curr['_end_']){
    return curr['_meaning_'];
  }else{
    return undefined;
  }
}

for(word in words){
  add_word(word,words[word]);
}

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.get('/get_trie',function(req, res, next) {
  res.send(trie);
});
module.exports = router;
<|endoftext|>


<commit_before>// This is the backend that is injected into the page that a Vue app lives in
// when the Vue Devtools panel is activated.

import { highlight, unHighlight, getInstanceRect } from './highlighter'
import { initVuexBackend } from './vuex'
import { stringify, classify, camelize } from '../util'

// hook should have been injected before this executes.
const hook = window.__VUE_DEVTOOLS_GLOBAL_HOOK__
const rootInstances = []
const propModes = ['default', 'sync', 'once']

const instanceMap = window.__VUE_DEVTOOLS_INSTANCE_MAP__ = new Map()
let currentInspectedId
let bridge
let filter = ''
let captureCount = 0

export function initBackend (_bridge) {
  bridge = _bridge
  if (hook.Vue) {
    connect()
  } else {
    hook.once('init', connect)
  }
  if (hook.store) {
    initVuexBackend(hook, bridge)
  } else {
    hook.once('vuex:init', store => {
      initVuexBackend(hook, bridge)
    })
  }
}

function connect () {
  hook.currentTab = 'components'
  bridge.on('switch-tab', tab => {
    hook.currentTab = tab
    if (tab === 'components') {
      flush()
    }
  })

  // the backend may get injected to the same page multiple times
  // if the user closes and reopens the devtools.
  // make sure there's only one flush listener.
  hook.off('flush')
  hook.on('flush', () => {
    if (hook.currentTab === 'components') {
      flush()
    }
  })

  bridge.on('select-instance', id => {
    currentInspectedId = id
    const instance = instanceMap.get(id)
    if (instance) {
      scrollIntoView(instance)
      highlight(instance)
    }
    bridge.send('instance-details', stringify(getInstanceDetails(id)))
  })

  bridge.on('send-to-console', id => {
    window.$vm = instanceMap.get(id)
    console.log('[vue-devtools] <' + getInstanceName(window.$vm) + '> is now available as $vm.')
  })

  bridge.on('filter-instances', _filter => {
    filter = _filter.toLowerCase()
    flush()
  })

  bridge.on('refresh', scan)
  bridge.on('enter-instance', id => highlight(instanceMap.get(id)))
  bridge.on('leave-instance', unHighlight)

  bridge.log('backend ready.')
  bridge.send('ready', hook.Vue.version)
  console.log('[vue-devtools] Ready. Detected Vue v' + hook.Vue.version)
  scan()
}

/**
 * Scan the page for root level Vue instances.
 */

function scan () {
  rootInstances.length = 0
  let inFragment = false
  let currentFragment = null
  walk(document, function (node) {
    if (inFragment) {
      if (node === currentFragment._fragmentEnd) {
        inFragment = false
        currentFragment = null
      }
      return true
    }
    const instance = node.__vue__
    if (instance) {
      if (instance._isFragment) {
        inFragment = true
        currentFragment = instance
      }
      rootInstances.push(instance)
      return true
    }
  })
  flush()
}

/**
 * DOM walk helper
 *
 * @param {NodeList} nodes
 * @param {Function} fn
 */

function walk (node, fn) {
  if (node.childNodes) {
    Array.prototype.forEach.call(node.childNodes, function (node) {
      const stop = fn(node)
      if (!stop) {
        walk(node, fn)
      }
    })
  }
}

/**
 * Called on every Vue.js batcher flush cycle.
 * Capture current component tree structure and the state
 * of the current inspected instance (if present) and
 * send it to the devtools.
 */

function flush () {
  let start
  if (process.env.NODE_ENV !== 'production') {
    captureCount = 0
    start = window.performance.now()
  }
  const payload = stringify({
    inspectedInstance: getInstanceDetails(currentInspectedId),
    instances: findQualifiedChildrenFromList(rootInstances)
  })
  if (process.env.NODE_ENV !== 'production') {
    console.log(`[flush] serialized ${captureCount} instances, took ${window.performance.now() - start}ms.`)
  }
  bridge.send('flush', payload)
}

/**
 * Iterate through an array of instances and flatten it into
 * an array of qualified instances. This is a depth-first
 * traversal - e.g. if an instance is not matched, we will
 * recursively go deeper until a qualified child is found.
 *
 * @param {Array} instances
 * @return {Array}
 */

function findQualifiedChildrenFromList (instances) {
  instances = instances
    .filter(child => !child._isBeingDestroyed)
  return !filter
    ? instances.map(capture)
    : Array.prototype.concat.apply([], instances.map(findQualifiedChildren))
}

/**
 * Find qualified children from a single instance.
 * If the instance itself is qualified, just return itself.
 * This is ok because [].concat works in both cases.
 *
 * @param {Vue} instance
 * @return {Vue|Array}
 */

function findQualifiedChildren (instance) {
  return isQualified(instance)
    ? capture(instance)
    : findQualifiedChildrenFromList(instance.$children)
}

/**
 * Check if an instance is qualified.
 *
 * @param {Vue} instance
 * @return {Boolean}
 */

function isQualified (instance) {
  const name = getInstanceName(instance).toLowerCase()
  return name.indexOf(filter) > -1
}

/**
 * Capture the meta information of an instance. (recursive)
 *
 * @param {Vue} instance
 * @return {Object}
 */

function capture (instance, _, list) {
  if (process.env.NODE_ENV !== 'production') {
    captureCount++
  }
  mark(instance)
  const ret = {
    id: instance._uid,
    name: getInstanceName(instance),
    inactive: !!instance._inactive,
    isFragment: !!instance._isFragment,
    children: instance.$children
      .filter(child => !child._isBeingDestroyed)
      .map(capture)
  }
  // record screen position to ensure correct ordering
  if ((!list || list.length > 1) && !instance._inactive) {
    const rect = getInstanceRect(instance)
    ret.top = rect ? rect.top : Infinity
  } else {
    ret.top = Infinity
  }
  // check router view
  const isRouterView2 = instance.$vnode && instance.$vnode.data.routerView
  if (instance._routerView || isRouterView2) {
    ret.isRouterView = true
    if (!instance._inactive) {
      const matched = instance.$route.matched
      const depth = isRouterView2
        ? instance.$vnode.data.routerViewDepth
        : instance._routerView.depth
      ret.matchedRouteSegment =
        matched &&
        matched[depth] &&
        (isRouterView2 ? matched[depth].path : matched[depth].handler.path)
    }
  }
  return ret
}

/**
 * Mark an instance as captured and store it in the instance map.
 *
 * @param {Vue} instance
 */

function mark (instance) {
  if (!instanceMap.has(instance._uid)) {
    instanceMap.set(instance._uid, instance)
    instance.$on('hook:beforeDestroy', function () {
      instanceMap.delete(instance._uid)
    })
  }
}

/**
 * Get the detailed information of an inspected instance.
 *
 * @param {Number} id
 */

function getInstanceDetails (id) {
  const instance = instanceMap.get(id)
  if (!instance) {
    return {}
  } else {
    return {
      id: id,
      name: getInstanceName(instance),
      state: processProps(instance).concat(
        processState(instance),
        processComputed(instance),
        processRouteContext(instance),
        processVuexGetters(instance),
        processFirebaseBindings(instance)
      )
    }
  }
}

/**
 * Get the appropriate display name for an instance.
 *
 * @param {Vue} instance
 * @return {String}
 */

function getInstanceName (instance) {
  const name = instance.$options.name || instance.$options._componentTag
  return name
    ? classify(name)
    : instance.$root === instance
      ? 'Root'
      : 'Anonymous Component'
}

/**
 * Process the props of an instance.
 * Make sure return a plain object because window.postMessage()
 * will throw an Error if the passed object contains Functions.
 *
 * @param {Vue} instance
 * @return {Array}
 */

function processProps (instance) {
  let props
  if ((props = instance._props)) {
    // 1.x
    return Object.keys(props).map(key => {
      const prop = props[key]
      const options = prop.options
      return {
        type: 'prop',
        key: prop.path,
        value: instance[prop.path],
        meta: {
          'type': options.type ? getPropType(options.type) : 'any',
          required: !!options.required,
          'binding mode': propModes[prop.mode]
        }
      }
    })
  } else if ((props = instance.$options.props)) {
    // 2.0
    return Object.keys(props).map(key => {
      const prop = props[key]
      key = camelize(key)
      return {
        type: 'prop',
        key,
        value: instance[key],
        meta: {
          type: prop.type ? getPropType(prop.type) : 'any',
          required: !!prop.required
        }
      }
    })
  } else {
    return []
  }
}

/**
 * Convert prop type constructor to string.
 *
 * @param {Function} fn
 */

const fnTypeRE = /^function (\w+)\(/
function getPropType (type) {
  return typeof type === 'function'
    ? type.toString().match(fnTypeRE)[1]
    : 'any'
}

/**
 * Process state, filtering out props and "clean" the result
 * with a JSON dance. This removes functions which can cause
 * errors during structured clone used by window.postMessage.
 *
 * @param {Vue} instance
 * @return {Array}
 */

function processState (instance) {
  const props = instance._props || instance.$options.props
  const getters =
    instance.$options.vuex &&
    instance.$options.vuex.getters
  return Object.keys(instance._data)
    .filter(key => (
      !(props && key in props) &&
      !(getters && key in getters)
    ))
    .map(key => ({
      key,
      value: instance[key]
    }))
}

/**
 * Process the computed properties of an instance.
 *
 * @param {Vue} instance
 * @return {Array}
 */

function processComputed (instance) {
  return Object.keys(instance.$options.computed || {}).map(key => {
    return {
      type: 'computed',
      key,
      value: instance[key]
    }
  })
}

/**
 * Process possible vue-router $route context
 *
 * @param {Vue} instance
 * @return {Array}
 */

function processRouteContext (instance) {
  const route = instance.$route
  if (route) {
    const { path, query, params } = route
    const value = { path, query, params }
    if (route.fullPath) value.fullPath = route.fullPath
    if (route.hash) value.hash = route.hash
    if (route.name) value.name = route.name
    return [{
      key: '$route',
      value
    }]
  } else {
    return []
  }
}

/**
 * Process Vuex getters.
 *
 * @param {Vue} instance
 * @return {Array}
 */

function processVuexGetters (instance) {
  const getters =
    instance.$options.vuex &&
    instance.$options.vuex.getters
  if (getters) {
    return Object.keys(getters).map(key => {
      return {
        type: 'vuex getter',
        key,
        value: instance[key]
      }
    })
  } else {
    return []
  }
}

/**
 * Process Firebase bindings.
 *
 * @param {Vue} instance
 * @return {Array}
 */

function processFirebaseBindings (instance) {
  var refs = instance.$firebaseRefs
  if (refs) {
    return Object.keys(refs).map(key => {
      return {
        type: 'firebase binding',
        key,
        value: instance[key]
      }
    })
  } else {
    return []
  }
}

/**
 * Sroll a node into view.
 *
 * @param {Vue} instance
 */

function scrollIntoView (instance) {
  const rect = getInstanceRect(instance)
  if (rect) {
    window.scrollBy(0, rect.top)
  }
}
<commit_msg>include route meta<commit_after>// This is the backend that is injected into the page that a Vue app lives in
// when the Vue Devtools panel is activated.

import { highlight, unHighlight, getInstanceRect } from './highlighter'
import { initVuexBackend } from './vuex'
import { stringify, classify, camelize } from '../util'

// hook should have been injected before this executes.
const hook = window.__VUE_DEVTOOLS_GLOBAL_HOOK__
const rootInstances = []
const propModes = ['default', 'sync', 'once']

const instanceMap = window.__VUE_DEVTOOLS_INSTANCE_MAP__ = new Map()
let currentInspectedId
let bridge
let filter = ''
let captureCount = 0

export function initBackend (_bridge) {
  bridge = _bridge
  if (hook.Vue) {
    connect()
  } else {
    hook.once('init', connect)
  }
  if (hook.store) {
    initVuexBackend(hook, bridge)
  } else {
    hook.once('vuex:init', store => {
      initVuexBackend(hook, bridge)
    })
  }
}

function connect () {
  hook.currentTab = 'components'
  bridge.on('switch-tab', tab => {
    hook.currentTab = tab
    if (tab === 'components') {
      flush()
    }
  })

  // the backend may get injected to the same page multiple times
  // if the user closes and reopens the devtools.
  // make sure there's only one flush listener.
  hook.off('flush')
  hook.on('flush', () => {
    if (hook.currentTab === 'components') {
      flush()
    }
  })

  bridge.on('select-instance', id => {
    currentInspectedId = id
    const instance = instanceMap.get(id)
    if (instance) {
      scrollIntoView(instance)
      highlight(instance)
    }
    bridge.send('instance-details', stringify(getInstanceDetails(id)))
  })

  bridge.on('send-to-console', id => {
    window.$vm = instanceMap.get(id)
    console.log('[vue-devtools] <' + getInstanceName(window.$vm) + '> is now available as $vm.')
  })

  bridge.on('filter-instances', _filter => {
    filter = _filter.toLowerCase()
    flush()
  })

  bridge.on('refresh', scan)
  bridge.on('enter-instance', id => highlight(instanceMap.get(id)))
  bridge.on('leave-instance', unHighlight)

  bridge.log('backend ready.')
  bridge.send('ready', hook.Vue.version)
  console.log('[vue-devtools] Ready. Detected Vue v' + hook.Vue.version)
  scan()
}

/**
 * Scan the page for root level Vue instances.
 */

function scan () {
  rootInstances.length = 0
  let inFragment = false
  let currentFragment = null
  walk(document, function (node) {
    if (inFragment) {
      if (node === currentFragment._fragmentEnd) {
        inFragment = false
        currentFragment = null
      }
      return true
    }
    const instance = node.__vue__
    if (instance) {
      if (instance._isFragment) {
        inFragment = true
        currentFragment = instance
      }
      rootInstances.push(instance)
      return true
    }
  })
  flush()
}

/**
 * DOM walk helper
 *
 * @param {NodeList} nodes
 * @param {Function} fn
 */

function walk (node, fn) {
  if (node.childNodes) {
    Array.prototype.forEach.call(node.childNodes, function (node) {
      const stop = fn(node)
      if (!stop) {
        walk(node, fn)
      }
    })
  }
}

/**
 * Called on every Vue.js batcher flush cycle.
 * Capture current component tree structure and the state
 * of the current inspected instance (if present) and
 * send it to the devtools.
 */

function flush () {
  let start
  if (process.env.NODE_ENV !== 'production') {
    captureCount = 0
    start = window.performance.now()
  }
  const payload = stringify({
    inspectedInstance: getInstanceDetails(currentInspectedId),
    instances: findQualifiedChildrenFromList(rootInstances)
  })
  if (process.env.NODE_ENV !== 'production') {
    console.log(`[flush] serialized ${captureCount} instances, took ${window.performance.now() - start}ms.`)
  }
  bridge.send('flush', payload)
}

/**
 * Iterate through an array of instances and flatten it into
 * an array of qualified instances. This is a depth-first
 * traversal - e.g. if an instance is not matched, we will
 * recursively go deeper until a qualified child is found.
 *
 * @param {Array} instances
 * @return {Array}
 */

function findQualifiedChildrenFromList (instances) {
  instances = instances
    .filter(child => !child._isBeingDestroyed)
  return !filter
    ? instances.map(capture)
    : Array.prototype.concat.apply([], instances.map(findQualifiedChildren))
}

/**
 * Find qualified children from a single instance.
 * If the instance itself is qualified, just return itself.
 * This is ok because [].concat works in both cases.
 *
 * @param {Vue} instance
 * @return {Vue|Array}
 */

function findQualifiedChildren (instance) {
  return isQualified(instance)
    ? capture(instance)
    : findQualifiedChildrenFromList(instance.$children)
}

/**
 * Check if an instance is qualified.
 *
 * @param {Vue} instance
 * @return {Boolean}
 */

function isQualified (instance) {
  const name = getInstanceName(instance).toLowerCase()
  return name.indexOf(filter) > -1
}

/**
 * Capture the meta information of an instance. (recursive)
 *
 * @param {Vue} instance
 * @return {Object}
 */

function capture (instance, _, list) {
  if (process.env.NODE_ENV !== 'production') {
    captureCount++
  }
  mark(instance)
  const ret = {
    id: instance._uid,
    name: getInstanceName(instance),
    inactive: !!instance._inactive,
    isFragment: !!instance._isFragment,
    children: instance.$children
      .filter(child => !child._isBeingDestroyed)
      .map(capture)
  }
  // record screen position to ensure correct ordering
  if ((!list || list.length > 1) && !instance._inactive) {
    const rect = getInstanceRect(instance)
    ret.top = rect ? rect.top : Infinity
  } else {
    ret.top = Infinity
  }
  // check router view
  const isRouterView2 = instance.$vnode && instance.$vnode.data.routerView
  if (instance._routerView || isRouterView2) {
    ret.isRouterView = true
    if (!instance._inactive) {
      const matched = instance.$route.matched
      const depth = isRouterView2
        ? instance.$vnode.data.routerViewDepth
        : instance._routerView.depth
      ret.matchedRouteSegment =
        matched &&
        matched[depth] &&
        (isRouterView2 ? matched[depth].path : matched[depth].handler.path)
    }
  }
  return ret
}

/**
 * Mark an instance as captured and store it in the instance map.
 *
 * @param {Vue} instance
 */

function mark (instance) {
  if (!instanceMap.has(instance._uid)) {
    instanceMap.set(instance._uid, instance)
    instance.$on('hook:beforeDestroy', function () {
      instanceMap.delete(instance._uid)
    })
  }
}

/**
 * Get the detailed information of an inspected instance.
 *
 * @param {Number} id
 */

function getInstanceDetails (id) {
  const instance = instanceMap.get(id)
  if (!instance) {
    return {}
  } else {
    return {
      id: id,
      name: getInstanceName(instance),
      state: processProps(instance).concat(
        processState(instance),
        processComputed(instance),
        processRouteContext(instance),
        processVuexGetters(instance),
        processFirebaseBindings(instance)
      )
    }
  }
}

/**
 * Get the appropriate display name for an instance.
 *
 * @param {Vue} instance
 * @return {String}
 */

function getInstanceName (instance) {
  const name = instance.$options.name || instance.$options._componentTag
  return name
    ? classify(name)
    : instance.$root === instance
      ? 'Root'
      : 'Anonymous Component'
}

/**
 * Process the props of an instance.
 * Make sure return a plain object because window.postMessage()
 * will throw an Error if the passed object contains Functions.
 *
 * @param {Vue} instance
 * @return {Array}
 */

function processProps (instance) {
  let props
  if ((props = instance._props)) {
    // 1.x
    return Object.keys(props).map(key => {
      const prop = props[key]
      const options = prop.options
      return {
        type: 'prop',
        key: prop.path,
        value: instance[prop.path],
        meta: {
          'type': options.type ? getPropType(options.type) : 'any',
          required: !!options.required,
          'binding mode': propModes[prop.mode]
        }
      }
    })
  } else if ((props = instance.$options.props)) {
    // 2.0
    return Object.keys(props).map(key => {
      const prop = props[key]
      key = camelize(key)
      return {
        type: 'prop',
        key,
        value: instance[key],
        meta: {
          type: prop.type ? getPropType(prop.type) : 'any',
          required: !!prop.required
        }
      }
    })
  } else {
    return []
  }
}

/**
 * Convert prop type constructor to string.
 *
 * @param {Function} fn
 */

const fnTypeRE = /^function (\w+)\(/
function getPropType (type) {
  return typeof type === 'function'
    ? type.toString().match(fnTypeRE)[1]
    : 'any'
}

/**
 * Process state, filtering out props and "clean" the result
 * with a JSON dance. This removes functions which can cause
 * errors during structured clone used by window.postMessage.
 *
 * @param {Vue} instance
 * @return {Array}
 */

function processState (instance) {
  const props = instance._props || instance.$options.props
  const getters =
    instance.$options.vuex &&
    instance.$options.vuex.getters
  return Object.keys(instance._data)
    .filter(key => (
      !(props && key in props) &&
      !(getters && key in getters)
    ))
    .map(key => ({
      key,
      value: instance[key]
    }))
}

/**
 * Process the computed properties of an instance.
 *
 * @param {Vue} instance
 * @return {Array}
 */

function processComputed (instance) {
  return Object.keys(instance.$options.computed || {}).map(key => {
    return {
      type: 'computed',
      key,
      value: instance[key]
    }
  })
}

/**
 * Process possible vue-router $route context
 *
 * @param {Vue} instance
 * @return {Array}
 */

function processRouteContext (instance) {
  const route = instance.$route
  if (route) {
    const { path, query, params } = route
    const value = { path, query, params }
    if (route.fullPath) value.fullPath = route.fullPath
    if (route.hash) value.hash = route.hash
    if (route.name) value.name = route.name
    if (route.meta) value.meta = route.meta
    return [{
      key: '$route',
      value
    }]
  } else {
    return []
  }
}

/**
 * Process Vuex getters.
 *
 * @param {Vue} instance
 * @return {Array}
 */

function processVuexGetters (instance) {
  const getters =
    instance.$options.vuex &&
    instance.$options.vuex.getters
  if (getters) {
    return Object.keys(getters).map(key => {
      return {
        type: 'vuex getter',
        key,
        value: instance[key]
      }
    })
  } else {
    return []
  }
}

/**
 * Process Firebase bindings.
 *
 * @param {Vue} instance
 * @return {Array}
 */

function processFirebaseBindings (instance) {
  var refs = instance.$firebaseRefs
  if (refs) {
    return Object.keys(refs).map(key => {
      return {
        type: 'firebase binding',
        key,
        value: instance[key]
      }
    })
  } else {
    return []
  }
}

/**
 * Sroll a node into view.
 *
 * @param {Vue} instance
 */

function scrollIntoView (instance) {
  const rect = getInstanceRect(instance)
  if (rect) {
    window.scrollBy(0, rect.top)
  }
}
<|endoftext|>


<commit_before>import assert from '../../_test-helper/assert';
import sinon from 'sinon';
import {
  es6ToEs5CodeForTestingOnly as es6ToEs5Code,
  runSpecsForTestingOnly as runSpecs
} from './spec-runner';

describe('Transpile', () => {
  describe('WHEN transpileToEs5=true', () => {
    const transpileToEs5 = (sourceCode) =>
      es6ToEs5Code({sourceCode, transpileToEs5: true});
    it('transpiles code (the `import` statement)', () => {
      const es6Code = 'import assert from "assert"';
      const es5Code = transpileToEs5(es6Code);
      assert(es5Code.includes('require("assert")'), `Expected transpiled code to contain "require(assert)", was NOT found.`);
    });
  });
  describe('WHEN transpileToEs5=false', () => {
    const noopTranspile = (sourceCode) =>
      es6ToEs5Code({sourceCode, transpileToEs5: false});
    it('transpiles code (the `import` statement)', () => {
      const es6Code = 'import assert from "assert";';
      const es5Code = noopTranspile(es6Code);
      assert.equal(es5Code, es6Code);
    });
  });
});

describe('Running a spec', () => {
  it('an empty files runs through silently', () => {
    const deps = {emptyErrorPane: () => {}, es6ToEs5Code: () => {}, fillErrorPaneWith: () => {}};
    assert.doesNotThrow(() => runSpecs({sourceCode: ''}, deps));
  });
  it('the error pane is emptied', () => {
    const emptyErrorPane = sinon.spy();
    const deps = {emptyErrorPane, es6ToEs5Code: () => {}, fillErrorPaneWith: () => {}};
    runSpecs({}, deps);
    assert.called(emptyErrorPane);
  });
  it('executes the passed source', () => {
    // Make the eval'ed code assign `x=42` to the global object.
    const globalObject = (new Function("return this"))();
    const sourceCode = '((new Function("return this"))()).x = 42;';
    let fillErrorPaneWithWasCalled = false;
    const deps = {emptyErrorPane: () => {}, es6ToEs5Code: () => sourceCode, fillErrorPaneWith: (...args) => { fillErrorPaneWithWasCalled = args; }};
    runSpecs({sourceCode: ''}, deps);
    assert.equal(fillErrorPaneWithWasCalled, false, '`fillErrorPaneWith()` should not have been called, but was called with: ' + fillErrorPaneWithWasCalled);
    assert.equal(globalObject.x, 42);
  });
});
<commit_msg>Use sinon.<commit_after>import assert from '../../_test-helper/assert';
import sinon from 'sinon';
import {
  es6ToEs5CodeForTestingOnly as es6ToEs5Code,
  runSpecsForTestingOnly as runSpecs
} from './spec-runner';

describe('Transpile', () => {
  describe('WHEN transpileToEs5=true', () => {
    const transpileToEs5 = (sourceCode) =>
      es6ToEs5Code({sourceCode, transpileToEs5: true});
    it('transpiles code (the `import` statement)', () => {
      const es6Code = 'import assert from "assert"';
      const es5Code = transpileToEs5(es6Code);
      assert(es5Code.includes('require("assert")'), `Expected transpiled code to contain "require(assert)", was NOT found.`);
    });
  });
  describe('WHEN transpileToEs5=false', () => {
    const noopTranspile = (sourceCode) =>
      es6ToEs5Code({sourceCode, transpileToEs5: false});
    it('transpiles code (the `import` statement)', () => {
      const es6Code = 'import assert from "assert";';
      const es5Code = noopTranspile(es6Code);
      assert.equal(es5Code, es6Code);
    });
  });
});

describe('Running a spec', () => {
  it('an empty files runs through silently', () => {
    const deps = {emptyErrorPane: () => {}, es6ToEs5Code: () => {}, fillErrorPaneWith: () => {}};
    assert.doesNotThrow(() => runSpecs({sourceCode: ''}, deps));
  });
  it('the error pane is emptied', () => {
    const emptyErrorPane = sinon.spy();
    const deps = {emptyErrorPane, es6ToEs5Code: () => {}, fillErrorPaneWith: () => {}};
    runSpecs({}, deps);
    assert.called(emptyErrorPane);
  });
  it('executes the passed source', () => {
    // Make the eval'ed code assign `x=42` to the global object.
    const globalObject = (new Function("return this"))();
    const sourceCode = '((new Function("return this"))()).x = 42;';
    const fillErrorPaneWith = sinon.spy();
    const deps = {emptyErrorPane: () => {}, es6ToEs5Code: () => sourceCode, fillErrorPaneWith};
    runSpecs({sourceCode: ''}, deps);
    assert.notCalled(fillErrorPaneWith);
    assert.equal(globalObject.x, 42);
  });
});
<|endoftext|>


<commit_before>"use strict";

require("ssl-root-cas").inject();

var request = require("superagent");

module.exports.handler = function (event, context, callback) {
  if(context.done === undefined) {
    console.log(arguments);
    return;
  }

  var banks;
  var outstanding = 0;

  /**
   * Fetches the resource at the `thing` subpath of QBank's API.  Calls function
   * `success` when the resource is received.  Keeps track of how many requests
   * are still waiting to be received; once all requests are finished, calls the
   * context's `succeed` function with the bank hierarchy as the return value.
   */
  function get(thing, success) {
    ++outstanding;
    console.log("Getting " + thing + ", " + outstanding + " requests");

    request.
      get("https://qbank-clix-dev.mit.edu/api/v1/assessment/hierarchies/" + thing).
      set("Accept", "application/json").
      then((response) => {
        console.log("Received", thing);
        success(response);
        // We need to decrement-and-check *after* we call the success function,
        // as that function may add more work to do.
        --outstanding;
        console.log(outstanding + " requests left");
        if(outstanding == 0) {
          console.log("Succeeding", banks);
          context.succeed(banks);
        }
      }, function () {
        console.log("Failed to GET resource", thing, arguments);
        context.fail();
      });
  }

  /**
   * Gets the details for a single bank, such as title, description, etc.
   * Updates the bank in-place.
   */
  function getBankDetails(bank) {
    console.log("getBankDetails", bank.id);
    get("nodes/" + bank.id, (response) => {
      var details = JSON.parse(response.text);

      // The detailed object we get back contains a `childNodes` key with an
      // empty array value, which conflicts with the real `childNodes` value
      // already in the hierarchy.  We preserve the correct value by assigning
      // it to the newly-received object, *then* assign the new object's entries
      // to the original.

      details.childNodes = bank.childNodes;
      Object.assign(bank, details);
    });
  }

  /**
   * Given a hierarchy of banks with no details (title, etc.), recursively walks
   * the hiearchy, requesting details each bank.
   */
  function recursivelyGetBankDetails(bank) {
    for(var i in bank.childNodes) {
      var child = bank.childNodes[i];
      getBankDetails(child);
      recursivelyGetBankDetails(child);
    }
  }

  /**
   * Gets the hierarchy of banks appearing under the given root bank.  The
   * hierarchy includes only IDs, not details such as title.
   */
  function getChildren(bank) {
    console.log("getChildren", bank.id);
    get("nodes/" + bank.id + "/children?descendants=10", (response) => {
      console.log("inserting children...");
      bank.childNodes = JSON.parse(response.text);
      for(var i in bank.childNodes) {
        recursivelyGetBankDetails(bank.childNodes[i]);
      }
      console.log("done inserting children");
    });
  }

  // Get the root banks and start filling in the hierarchy and details.
  get("roots", (response) => {
    console.log("Received roots");
    banks = JSON.parse(response.text);
    console.log("Parsed roots");
    for(var i in banks) {
      getChildren(banks[i]);
    }
    console.log("Requested children");
  });
};
<commit_msg>Fetch the assessments and attach them to the bank hierarchy<commit_after>"use strict";

require("ssl-root-cas").inject();

var request = require("superagent");

module.exports.handler = function (event, context, callback) {
  if(context.done === undefined) {
    console.log(arguments);
    return;
  }

  var banks;
  var assessments = [];
  var outstanding = 0;

  function attachToBank(bank, map) {
    console.log("attachToBank", bank.id, map);
    bank.assessments = map[bank.id] || [];
    console.log(bank.id, bank.assessments);
    for(var i in bank.childNodes) {
      attachToBank(bank.childNodes[i], map);
    }
  }

  function attachAssessments() {
    console.log("attachAssessments");
    var map = {};
    for(var i in assessments) {
      var assessment = assessments[i];
      map[assessment.bankId] = map[assessment.bankId] || [];
      map[assessment.bankId].push(assessment);
    }
    console.log(map);
    for(i in banks) {
      attachToBank(banks[i], map);
    }
  }

  /**
   * Fetches the resource at the `thing` subpath of QBank's API.  Calls function
   * `success` when the resource is received.  Keeps track of how many requests
   * are still waiting to be received; once all requests are finished, calls the
   * context's `succeed` function with the bank hierarchy as the return value.
   */
  function get(thing, success) {
    ++outstanding;
    console.log("Getting " + thing + ", " + outstanding + " requests");

    request.
      get("https://qbank-clix-dev.mit.edu/api/v1/assessment/" + thing).
      set("Accept", "application/json").
      then((response) => {
        console.log("Received", thing);
        success(response);
        // We need to decrement-and-check *after* we call the success function,
        // as that function may add more work to do.
        --outstanding;
        console.log(outstanding + " requests left");
        if(outstanding == 0) {
          console.log("Succeeding", banks, assessments);
          attachAssessments();
          context.succeed(banks);
        }
      }, function () {
        console.log("Failed to GET resource", thing, arguments);
        context.fail();
      });
  }

  /**
   * Gets the details for a single bank, such as title, description, etc.
   * Updates the bank in-place.
   */
  function getBankDetails(bank) {
    console.log("getBankDetails", bank.id);
    get("hierarchies/nodes/" + bank.id, (response) => {
      var details = JSON.parse(response.text);

      // The detailed object we get back contains a `childNodes` key with an
      // empty array value, which conflicts with the real `childNodes` value
      // already in the hierarchy.  We preserve the correct value by assigning
      // it to the newly-received object, *then* assign the new object's entries
      // to the original.

      details.childNodes = bank.childNodes;
      Object.assign(bank, details);
    });
  }

  /**
   * Given a hierarchy of banks with no details (title, etc.), recursively walks
   * the hiearchy, requesting details each bank.
   */
  function recursivelyGetBankDetails(bank) {
    for(var i in bank.childNodes) {
      var child = bank.childNodes[i];
      getBankDetails(child);
      recursivelyGetBankDetails(child);
    }
  }

  /**
   * Gets the hierarchy of banks appearing under the given root bank.  The
   * hierarchy includes only IDs, not details such as title.
   */
  function getChildren(bank) {
    console.log("getChildren", bank.id);
    get("hierarchies/nodes/" + bank.id + "/children?descendants=10", (response) => {
      console.log("inserting children...");
      bank.childNodes = JSON.parse(response.text);
      for(var i in bank.childNodes) {
        recursivelyGetBankDetails(bank.childNodes[i]);
      }
      console.log("done inserting children");
    });
  }

  function getAssessments(bank) {
    console.log("getAssessments", bank.id);
    get("banks/" + bank.id + "/assessments", (response) => {
      var arr = JSON.parse(response.text);
      console.log(arr);
      assessments = assessments.concat(arr);
    });
  }

  // Get the root banks and start filling in the hierarchy and details.
  get("hierarchies/roots", (response) => {
    console.log("Received roots");
    banks = JSON.parse(response.text);
    console.log("Parsed roots");
    for(var i in banks) {
      getChildren(banks[i]);
      getAssessments(banks[i]);
    }
    console.log("Requested children");
  });
};
<|endoftext|>


<commit_before>require(window.APT_OPTIONS.configObject,
	['underscore', 'js/quickvm_sup', // jQuery modules
	 'js/lib/text!template/aboutapt.html',
	 'js/lib/text!template/aboutcloudlab.html',
         'formhelpers', 'filestyle', 'marked'],
function (_, sup, aboutaptString, aboutcloudString)
{
    'use strict';

    var ajaxurl;

    function initialize()
    {
	window.APT_OPTIONS.initialize();
	ajaxurl = window.AJAXURL;

	// The about panel.
	$('#about_div').html(window.ISCLOUD ? aboutcloudString : aboutaptString);

	if (window.APT_OPTIONS.isNewUser) {
	    $('#verify_modal_submit').click(function (event) {
		$('#verify_modal').modal('hide');
		$("#waitwait").modal('show');
		return true;
	    });
	    $('#verify_modal').modal('show');
	}
        $('#quickvm_topomodal').on('shown.bs.modal', function() {
            ShowProfileList($('.current'))
        });

	$('button#reset-form').click(function (event) {
	    event.preventDefault();
	    resetForm($('#quickvm_form'));
	});
	$('button#profile').click(function (event) {
	    event.preventDefault();
	    $('#quickvm_topomodal').modal('show');
	});
	$('li.profile-item').click(function (event) {
	    event.preventDefault();
	    ShowProfileList(event.target);
	});
	$('button#showtopo_select').click(function (event) {
	    event.preventDefault();
	    UpdateProfileSelection($('.selected'));
	    ShowProfileList($('.selected'));
	    $('#quickvm_topomodal').modal('hide');
	});
	$('#instantiate_submit').click(function (event) {
	    $("#waitwait").modal('show');
	    return true;
	});
	var startProfile = $('#profile_name li[value = ' + window.PROFILE + ']')
        UpdateProfileSelection(startProfile);
	ShowProfileList(startProfile, true);
	_.delay(function () {$('.dropdown-toggle').dropdown();}, 500);
    }

    function resetForm($form) {
	$form.find('input:text, input:password, select, textarea').val('');
    }

    function UpdateProfileSelection(selectedElement)
    {
	var profile_name = $(selectedElement).text();
	var profile_value = $(selectedElement).attr('value');
	$('#selected_profile').attr('value', profile_value);
	$('#selected_profile_text').html("" + profile_name);

	if (!$(selectedElement).hasClass('current')) {
	    $('#profile_name li').each(function() {
		$(this).removeClass('current');
	    });
	    $(selectedElement).addClass('current');
	}
    }

    function ShowProfileList(selectedElement, justTitle)
    {
	var profile = $(selectedElement).attr('value');

	if (!$(selectedElement).hasClass('selected')) {
	    $('#profile_name li').each(function() {
		$(this).removeClass('selected');
	    });
	    $(selectedElement).addClass('selected');
	}

	var callback = function(json) {
	    if (json.code) {
		alert("Could not get profile: " + json.value);
		return;
	    }

	    var xmlDoc = $.parseXML(json.value.rspec);
	    var xml    = $(xmlDoc);

	    $('#showtopo_title').html("
" + json.value.name + "
");

	    /*
	     * We now use the desciption from inside the rspec, unless there
	     * is none, in which case look to see if the we got one in the
	     * rpc reply, which we will until all profiles converted over to
	     * new format rspecs.
	     */
	    var description = null;
	    $(xml).find("rspec_tour").each(function() {
		$(this).find("description").each(function() {
		    var marked = require("marked");
		    description = marked($(this).text());
		});
	    });
	    if (!description) {
		if (json.value.description != "") {
		    description = json.value.description;
		}
		else {
		    description = "Hmm, no description for this profile";
		}
	    }
	    $('#showtopo_description').html(description);
	    $('#selected_profile_description').html(description);

	    if (! justTitle) {
		sup.maketopmap('#showtopo_div', json.value.rspec, null);
	    }
	}
	var $xmlthing = sup.CallServerMethod(ajaxurl,
					     "instantiate", "GetProfile",
					     {"uuid" : profile});
	$xmlthing.done(callback);
    }

    $(document).ready(initialize);
});
<commit_msg>Minor format change.<commit_after>require(window.APT_OPTIONS.configObject,
	['underscore', 'js/quickvm_sup', // jQuery modules
	 'js/lib/text!template/aboutapt.html',
	 'js/lib/text!template/aboutcloudlab.html',
         'formhelpers', 'filestyle', 'marked'],
function (_, sup, aboutaptString, aboutcloudString)
{
    'use strict';

    var ajaxurl;

    function initialize()
    {
	window.APT_OPTIONS.initialize();
	ajaxurl = window.AJAXURL;

	// The about panel.
	$('#about_div').html(window.ISCLOUD ?
			     aboutcloudString : aboutaptString);

	if (window.APT_OPTIONS.isNewUser) {
	    $('#verify_modal_submit').click(function (event) {
		$('#verify_modal').modal('hide');
		$("#waitwait").modal('show');
		return true;
	    });
	    $('#verify_modal').modal('show');
	}
        $('#quickvm_topomodal').on('shown.bs.modal', function() {
            ShowProfileList($('.current'))
        });

	$('button#reset-form').click(function (event) {
	    event.preventDefault();
	    resetForm($('#quickvm_form'));
	});
	$('button#profile').click(function (event) {
	    event.preventDefault();
	    $('#quickvm_topomodal').modal('show');
	});
	$('li.profile-item').click(function (event) {
	    event.preventDefault();
	    ShowProfileList(event.target);
	});
	$('button#showtopo_select').click(function (event) {
	    event.preventDefault();
	    UpdateProfileSelection($('.selected'));
	    ShowProfileList($('.selected'));
	    $('#quickvm_topomodal').modal('hide');
	});
	$('#instantiate_submit').click(function (event) {
	    $("#waitwait").modal('show');
	    return true;
	});
	var startProfile = $('#profile_name li[value = ' + window.PROFILE + ']')
        UpdateProfileSelection(startProfile);
	ShowProfileList(startProfile, true);
	_.delay(function () {$('.dropdown-toggle').dropdown();}, 500);
    }

    function resetForm($form) {
	$form.find('input:text, input:password, select, textarea').val('');
    }

    function UpdateProfileSelection(selectedElement)
    {
	var profile_name = $(selectedElement).text();
	var profile_value = $(selectedElement).attr('value');
	$('#selected_profile').attr('value', profile_value);
	$('#selected_profile_text').html("" + profile_name);

	if (!$(selectedElement).hasClass('current')) {
	    $('#profile_name li').each(function() {
		$(this).removeClass('current');
	    });
	    $(selectedElement).addClass('current');
	}
    }

    function ShowProfileList(selectedElement, justTitle)
    {
	var profile = $(selectedElement).attr('value');

	if (!$(selectedElement).hasClass('selected')) {
	    $('#profile_name li').each(function() {
		$(this).removeClass('selected');
	    });
	    $(selectedElement).addClass('selected');
	}

	var callback = function(json) {
	    if (json.code) {
		alert("Could not get profile: " + json.value);
		return;
	    }

	    var xmlDoc = $.parseXML(json.value.rspec);
	    var xml    = $(xmlDoc);

	    $('#showtopo_title').html("
" + json.value.name + "
");

	    /*
	     * We now use the desciption from inside the rspec, unless there
	     * is none, in which case look to see if the we got one in the
	     * rpc reply, which we will until all profiles converted over to
	     * new format rspecs.
	     */
	    var description = null;
	    $(xml).find("rspec_tour").each(function() {
		$(this).find("description").each(function() {
		    var marked = require("marked");
		    description = marked($(this).text());
		});
	    });
	    if (!description) {
		if (json.value.description != "") {
		    description = json.value.description;
		}
		else {
		    description = "Hmm, no description for this profile";
		}
	    }
	    $('#showtopo_description').html(description);
	    $('#selected_profile_description').html(description);

	    if (! justTitle) {
		sup.maketopmap('#showtopo_div', json.value.rspec, null);
	    }
	}
	var $xmlthing = sup.CallServerMethod(ajaxurl,
					     "instantiate", "GetProfile",
					     {"uuid" : profile});
	$xmlthing.done(callback);
    }

    $(document).ready(initialize);
});
<|endoftext|>