<commit_before>(function() {
	var exports = app.namespace("app.views.board");

	/**
	 * createInstance returns a new instance of class Board.
	 * @param HTMLElement board Root element where all other markup is placed to create the board.
	 * @param integer columnMaxWidth Maximum width of columns in pixels.
	 * @param integer columnMarginLeft Margin between columns in pixels.
	 * @returns object Board
	 */
	exports.createInstance = function(board, columnMaxWidth, columnMarginLeft) {
		return new Board(board, columnMaxWidth, columnMarginLeft);
	};

	/**
	 * Class Board manages the display of images as well as some delegated click
	 * events.
	 * @param HTMLElement board Root element where all other markup is placed to create the board.
	 * @param integer columnMaxWidth Maximum width of columns in pixels.
	 * @param integer columnMarginLeft Margin between columns in pixels.
	 */
	function Board(board, columnMaxWidth, columnMarginLeft) {
		var self = this;

		var columnCount;
		var columnWidth;

		var columns = [];
		var boardItems = [];
		var resizeTimeoutId;

		// For keeping track of states
		var hasLoadedAnImage = false;
		var isWaitingForRedditResponse = false;
		var lastThreadId;
		var requestToReddit;

		var columnIndex = 0;
		var styleElement;

		self.initialize = function() {
			window.addEvent("app.views.board.loadMoreImages", handleLoadImagesEvent);
			window.addEvent("resize", handleWindowResizeEvent);
			board.addEvent("click:relay(.board-item-image-anchor)", handleBoardItemImageAnchorClickEvent);
			board.addEvent("click:relay(.board-item-title-anchor)", handleBoardItemTitleAnchorClickEvent);
		};

		function handleBoardItemImageAnchorClickEvent(event) {
			event.stop();
			var anchor = event.target;

			if (anchor.get("tag") !== "a") {
				anchor = anchor.getParent(".board-item-image-anchor");
			}

			if (!anchor) {
				return;
			}

			var url = anchor.getProperty("href");

			if (!url) {
				return;
			}

			window.open(url);
		}

		function handleBoardItemTitleAnchorClickEvent(event) {
			event.stop();
			var url = event.target.getProperty("href");

			if (!url) {
				return;
			}

			window.open(url);
		}

		function handleWindowResizeEvent() {
			if (!board) {
				return;
			}

			if (resizeTimeoutId) {
				clearTimeout(resizeTimeoutId);
			}

			resizeTimeoutId = self.rebuild.delay(10);
		}

		/**
		 * rebuild creates a board with image columns from scratch.
		 * @returns element HTML element
		 */
		self.rebuild = function() {
			if (typeOf(board) !== "element") {
				return;
			}

			var availableBoardWidth = board.getWidth();
			var newColumnCount = 1;
			var newColumnWidth = columnMaxWidth;

			if (newColumnWidth > availableBoardWidth) {
				newColumnWidth = availableBoardWidth;
			} else {
				newColumnCount += Math.floor((availableBoardWidth - newColumnWidth) / (newColumnWidth + columnMarginLeft));
			}

			if (newColumnWidth !== columnWidth) {
				resizeColumns(newColumnWidth, columnMarginLeft);
				columnWidth = newColumnWidth;
			}

			if (newColumnCount === columnCount) {
				return;
			}

			columnCount = newColumnCount;
			columns = [];

			// Remove all child elements and reset column index
			board.empty();
			columnIndex = 0;

			// Create columns
			for (var i = 0; i < columnCount; i++) {
				var column = createColumn();
				columns.push(column);
				board.grab(column);
			}

			// alert(JSON.stringify({
			// 	availableBoardWidth: availableBoardWidth,
			// 	columnCount: columnCount,
			// 	newColumnWidth: newColumnWidth
			// }));
			console.log("app.views.board.rebuild: Rebuilding board with %d images.", boardItems.length);

			// Fill columns with previously fetched images, if any.
			for (var i = 0, boardItemCount = boardItems.length; i < boardItemCount; i++) {
				placeImageOnBoard(boardItems[i]);
			}

			return board;
		};

		function createColumn(properties) {
			properties = properties || {};
			properties = Object.merge(properties, {
				"class": "board-column"
			});

			var column = new Element("div", properties);
			return column;
		}

		function getUrl() {
			var subredditNames = app.extractSubredditNamesFromLocationHash(location.hash);

			if (subredditNames.length === 0) {
				subredditNames = app.config.core.getNamesOfDefaultSubreddits();
			}

			url = "http://www.reddit.com/r/" + subredditNames.join("+") + ".json?limit=25";

			if (lastThreadId) {
				url += "&after=" + lastThreadId;
			}

			return url;
		}

		function handleLoadImagesEvent() {
			requestToReddit = new Request.JSONP({
				callbackKey: "jsonp",
				onCancel: handleRedditRequestCancelEvent,
				onComplete: handleRedditRequestCompleteEvent,
				onRequest: handleRedditRequestRequestEvent,
				onTimeout: handleRedditRequestTimeoutEvent,
				timeout: app.config.core.network.timeout,
				url: getUrl()
			});

			requestToReddit.send();
		}

		function handleRedditRequestCancelEvent() {
			isWaitingForRedditResponse = false;
			updateLoadMoreAnchor();
		}

		function handleRedditRequestCompleteEvent(response) {
			isWaitingForRedditResponse = false;

			var threads = response.data.children;

			for (var i = 0, threadCount = threads.length; i < threadCount; i++) {
				var url = threads[i].data.url;
				var imgurImageHash = threads[i].data.url.match(/^https?:\/\/(?:i\.)?imgur\.com\/([a-zA-Z0-9]+)/);

				// If image is hosted on Imgur, try to load large preview version of image
				if (imgurImageHash) {
					url = "http://i.imgur.com/" + imgurImageHash[1] + "l.jpg";
					fullsizeImageUrl = "http://i.imgur.com/" + imgurImageHash[1] + ".jpg";

					var image = new Image();
					image.addEvent("error", handleImgurRequestErrorEvent.pass([threads[i].data]));
					image.addEvent("load", handleImgurRequestLoadEvent.pass([threads[i].data, image, fullsizeImageUrl]));
					image.src = url;
					continue;
				}

				// Load image
				var image = new Image();
				image.addEvent("error", handleImageErrorEvent.pass([threads[i].data]));
				image.addEvent("load", handleImageLoadEvent.pass([threads[i].data, image]));
				image.src = url;
			}

			lastThreadId = response.data.after;
			updateLoadMoreAnchor();
		}

		function handleRedditRequestRequestEvent(event) {
			isWaitingForRedditResponse = true;
			updateLoadMoreAnchor();
		}

		function handleRedditRequestTimeoutEvent(event) {
			console.log("timeout", arguments);
			isWaitingForRedditResponse = false;
			updateLoadMoreAnchor();
			alert("Panoptikos cannot retrieve data from Reddit because Reddit is slow or you are not connected to the Internet.");
		}

		function handleImgurRequestErrorEvent(thread) {
			console.log("app.views.board.handleImgurRequestErrorEvent:", thread)
		}

		function handleImgurRequestLoadEvent(thread, image, fullsizeImageUrl) {
			console.log("app.views.board.handleImgurRequestLoadEvent: " + image.width + "x" + image.height);
			handleImageLoadEvent(thread, image, fullsizeImageUrl);
		}

		function handleImageErrorEvent() {
			console.log("imageError", arguments);
		}

		function handleImageLoadEvent(thread, image, fullsizeImageUrl) {
			// Ignore Imgur's "Image does not exist" image
			// TODO: Find a way to make absolutely sure we are actually blocking Imgur's "Image does not exist" image and not a random image with the same dimensions.
			if (image.height === 81
					&& image.width === 161
					&& image.src.match(/^https?:\/\/i\.imgur\.com\//)) {
				console.log("Ignoring image: " + image.src);
				return;
			}

			var boardItem = app.views.boardItem.createInstance();
			var boardItemElement = boardItem.create(thread, image, fullsizeImageUrl);

			boardItems.push(boardItemElement);
			placeImageOnBoard(boardItemElement);

			if (!hasLoadedAnImage) {
				hasLoadedAnImage = true;
				updateLoadMoreAnchor();
			}
		}

		function placeImageOnBoard(boardItem) {
			if (columnIndex < 0 || columnIndex >= columns.length) {
				columnIndex = 0;
			}

			columns[columnIndex].grab(boardItem);
			columnIndex++;
		}

		function updateLoadMoreAnchor() {
			// if (!loadMoreAnchor) {
			// 	return;
			// }

			// var anchorText = loadMoreAnchorTextDefault1;

			// if (isWaitingForRedditResponse) {
			// 	anchorText = loadMoreAnchorTextActive1;
			// } else if (hasLoadedAnImage) {
			// 	anchorText = loadMoreAnchorTextDefault2;
			// }

			// loadMoreAnchor.set("html", anchorText);
		}

		var columnHeights = [30, 20, 10, 40];

		/**
		 * getShortestColumn returns the shortest of the provided columns.
		 * @param array Array of HTMLElements
		 * @returns HTMLElement|null Returns HTMLElement if columns array has at least one item, null otherwise.
		 */
		function getShortestColumn(columns) {
			return column = null;

			for (var i = 0, columnCount = columns.length; i < columnCount; i++) {
				if (i === 0) {
					column = 0;
					continue;
				}

				if (columns[i].getHeight() > column.getHeight()) {
					column = columns[i];
				}
			}

			return column;
		}

		function resizeColumns(columnWidth, columnMarginLeft) {
			var style = ".board-column {margin-left: " + columnMarginLeft + "px; width: " + columnWidth + "px;}";
			style += ".board-item {width: " + (columnWidth - 8) + "px;}";

			if (!styleElement) {
				styleElement = new Element("style", {
					"html": style,
					"type": "text/css"
				});

				styleElement.inject($(document.head));
				return;
			}

			styleElement.set("html", style);
		}
	};
})();
<commit_msg>Added doc-block. Removed one instance of unnecessary console logging. Added identifier to some console log messages so it is clear where they originated.<commit_after>(function() {
	var exports = app.namespace("app.views.board");

	/**
	 * createInstance returns a new instance of class Board.
	 * @param HTMLElement board Root element where all other markup is placed to create the board.
	 * @param integer columnMaxWidth Maximum width of columns in pixels.
	 * @param integer columnMarginLeft Margin between columns in pixels.
	 * @returns object Board
	 */
	exports.createInstance = function(board, columnMaxWidth, columnMarginLeft) {
		return new Board(board, columnMaxWidth, columnMarginLeft);
	};

	/**
	 * Class Board manages the display of images as well as some delegated click
	 * events.
	 * @param HTMLElement board Root element where all other markup is placed to create the board.
	 * @param integer columnMaxWidth Maximum width of columns in pixels.
	 * @param integer columnMarginLeft Margin between columns in pixels.
	 */
	function Board(board, columnMaxWidth, columnMarginLeft) {
		var self = this;

		var columnCount;
		var columnWidth;

		var columns = [];
		var boardItems = [];
		var resizeTimeoutId;

		// For keeping track of states
		var hasLoadedAnImage = false;
		var isWaitingForRedditResponse = false;
		var lastThreadId;
		var requestToReddit;

		var columnIndex = 0;
		var styleElement;

		self.initialize = function() {
			window.addEvent("app.views.board.loadMoreImages", handleLoadImagesEvent);
			window.addEvent("resize", handleWindowResizeEvent);
			board.addEvent("click:relay(.board-item-image-anchor)", handleBoardItemImageAnchorClickEvent);
			board.addEvent("click:relay(.board-item-title-anchor)", handleBoardItemTitleAnchorClickEvent);
		};

		function handleBoardItemImageAnchorClickEvent(event) {
			event.stop();
			var anchor = event.target;

			if (anchor.get("tag") !== "a") {
				anchor = anchor.getParent(".board-item-image-anchor");
			}

			if (!anchor) {
				return;
			}

			var url = anchor.getProperty("href");

			if (!url) {
				return;
			}

			window.open(url);
		}

		function handleBoardItemTitleAnchorClickEvent(event) {
			event.stop();
			var url = event.target.getProperty("href");

			if (!url) {
				return;
			}

			window.open(url);
		}

		function handleWindowResizeEvent() {
			if (!board) {
				return;
			}

			if (resizeTimeoutId) {
				clearTimeout(resizeTimeoutId);
			}

			resizeTimeoutId = self.rebuild.delay(10);
		}

		/**
		 * rebuild creates a board with image columns from scratch.
		 * @returns element HTML element
		 */
		self.rebuild = function() {
			if (typeOf(board) !== "element") {
				return;
			}

			var availableBoardWidth = board.getWidth();
			var newColumnCount = 1;
			var newColumnWidth = columnMaxWidth;

			if (newColumnWidth > availableBoardWidth) {
				newColumnWidth = availableBoardWidth;
			} else {
				newColumnCount += Math.floor((availableBoardWidth - newColumnWidth) / (newColumnWidth + columnMarginLeft));
			}

			if (newColumnWidth !== columnWidth) {
				resizeColumns(newColumnWidth, columnMarginLeft);
				columnWidth = newColumnWidth;
			}

			if (newColumnCount === columnCount) {
				return;
			}

			columnCount = newColumnCount;
			columns = [];

			// Remove all child elements and reset column index
			board.empty();
			columnIndex = 0;

			// Create columns
			for (var i = 0; i < columnCount; i++) {
				var column = createColumn();
				columns.push(column);
				board.grab(column);
			}

			console.log("app.views.board.rebuild: Rebuilding board with %d images.", boardItems.length);

			// Fill columns with previously fetched images, if any.
			for (var i = 0, boardItemCount = boardItems.length; i < boardItemCount; i++) {
				placeImageOnBoard(boardItems[i]);
			}

			return board;
		};

		function createColumn(properties) {
			properties = properties || {};
			properties = Object.merge(properties, {
				"class": "board-column"
			});

			var column = new Element("div", properties);
			return column;
		}

		function getUrl() {
			var subredditNames = app.extractSubredditNamesFromLocationHash(location.hash);

			if (subredditNames.length === 0) {
				subredditNames = app.config.core.getNamesOfDefaultSubreddits();
			}

			url = "http://www.reddit.com/r/" + subredditNames.join("+") + ".json?limit=25";

			if (lastThreadId) {
				url += "&after=" + lastThreadId;
			}

			return url;
		}

		function handleLoadImagesEvent() {
			requestToReddit = new Request.JSONP({
				callbackKey: "jsonp",
				onCancel: handleRedditRequestCancelEvent,
				onComplete: handleRedditRequestCompleteEvent,
				onRequest: handleRedditRequestRequestEvent,
				onTimeout: handleRedditRequestTimeoutEvent,
				timeout: app.config.core.network.timeout,
				url: getUrl()
			});

			requestToReddit.send();
		}

		function handleRedditRequestCancelEvent() {
			isWaitingForRedditResponse = false;
			updateLoadMoreAnchor();
		}

		function handleRedditRequestCompleteEvent(response) {
			isWaitingForRedditResponse = false;

			var threads = response.data.children;

			for (var i = 0, threadCount = threads.length; i < threadCount; i++) {
				var url = threads[i].data.url;
				var imgurImageHash = threads[i].data.url.match(/^https?:\/\/(?:i\.)?imgur\.com\/([a-zA-Z0-9]+)/);

				// If image is hosted on Imgur, try to load large preview version of image
				if (imgurImageHash) {
					url = "http://i.imgur.com/" + imgurImageHash[1] + "l.jpg";
					fullsizeImageUrl = "http://i.imgur.com/" + imgurImageHash[1] + ".jpg";

					var image = new Image();
					image.addEvent("error", handleImgurRequestErrorEvent.pass([threads[i].data]));
					image.addEvent("load", handleImgurRequestLoadEvent.pass([threads[i].data, image, fullsizeImageUrl]));
					image.src = url;
					continue;
				}

				// Load image
				var image = new Image();
				image.addEvent("error", handleImageErrorEvent.pass([threads[i].data]));
				image.addEvent("load", handleImageLoadEvent.pass([threads[i].data, image]));
				image.src = url;
			}

			lastThreadId = response.data.after;
			updateLoadMoreAnchor();
		}

		function handleRedditRequestRequestEvent(event) {
			isWaitingForRedditResponse = true;
			updateLoadMoreAnchor();
		}

		function handleRedditRequestTimeoutEvent(event) {
			console.log("timeout", arguments);
			isWaitingForRedditResponse = false;
			updateLoadMoreAnchor();
			alert("Panoptikos cannot retrieve data from Reddit because Reddit is slow or you are not connected to the Internet.");
		}

		function handleImgurRequestErrorEvent(thread) {
			console.log("app.views.board.handleImgurRequestErrorEvent:", thread)
		}

		function handleImgurRequestLoadEvent(thread, image, fullsizeImageUrl) {
			handleImageLoadEvent(thread, image, fullsizeImageUrl);
		}

		function handleImageErrorEvent() {
			console.log("app.views.board.handleImageErrorEvent:", arguments);
		}

		function handleImageLoadEvent(thread, image, fullsizeImageUrl) {
			// Ignore Imgur's "Image does not exist" image
			// TODO: Find a way to make absolutely sure we are actually blocking Imgur's "Image does not exist" image and not a random image with the same dimensions.
			if (image.height === 81
					&& image.width === 161
					&& image.src.match(/^https?:\/\/i\.imgur\.com\//)) {
				console.log("app.views.board.handleImageLoadEvent: Ignoring image: " + image.src);
				return;
			}

			var boardItem = app.views.boardItem.createInstance();
			var boardItemElement = boardItem.create(thread, image, fullsizeImageUrl);

			boardItems.push(boardItemElement);
			placeImageOnBoard(boardItemElement);

			if (!hasLoadedAnImage) {
				hasLoadedAnImage = true;
				updateLoadMoreAnchor();
			}
		}

		function placeImageOnBoard(boardItem) {
			if (columnIndex < 0 || columnIndex >= columns.length) {
				columnIndex = 0;
			}

			columns[columnIndex].grab(boardItem);
			columnIndex++;
		}

		function updateLoadMoreAnchor() {
			// if (!loadMoreAnchor) {
			// 	return;
			// }

			// var anchorText = loadMoreAnchorTextDefault1;

			// if (isWaitingForRedditResponse) {
			// 	anchorText = loadMoreAnchorTextActive1;
			// } else if (hasLoadedAnImage) {
			// 	anchorText = loadMoreAnchorTextDefault2;
			// }

			// loadMoreAnchor.set("html", anchorText);
		}

		var columnHeights = [30, 20, 10, 40];

		/**
		 * getShortestColumn returns the shortest of the provided columns.
		 * @param array Array of HTMLElements
		 * @returns HTMLElement|null Returns HTMLElement if columns array has at least one item, null otherwise.
		 */
		function getShortestColumn(columns) {
			return column = null;

			for (var i = 0, columnCount = columns.length; i < columnCount; i++) {
				if (i === 0) {
					column = 0;
					continue;
				}

				if (columns[i].getHeight() > column.getHeight()) {
					column = columns[i];
				}
			}

			return column;
		}

		/**
		 * resizeColumns injects CSS with style rules for Board margin, Board
		 * width and BoardItem width into the page by creating a <style> element
		 * or modifying the created <style> element.
		 * @param integer columnWidth New width of columns in pixels.
		 * @param integer columnMarginLeft New margin between board columns in pixels.
		 * @returns void
		 */
		function resizeColumns(columnWidth, columnMarginLeft) {
			var style = ".board-column {margin-left: " + columnMarginLeft + "px; width: " + columnWidth + "px;}";
			style += ".board-item {width: " + (columnWidth - 8) + "px;}";

			if (!styleElement) {
				styleElement = new Element("style", {
					"html": style,
					"type": "text/css"
				});

				styleElement.inject($(document.head));
				return;
			}

			styleElement.set("html", style);
		}
	};
})();
<|endoftext|>


<commit_before>/*
 * DIASPORA
 * -------------------
 * A cool sketch inspired by the cover of the
 * Greg Egan novel Diaspora
 *
 * License: MIT
*/

var camera, scene, renderer, container, mesh, composer;
var clock;
var stars = [];

document.addEventListener("DOMContentLoaded", startApp, false);

function startApp()
{
    init();
    animate();
}

function init()
{
    // Container and Renderer
    container = document.getElementById('container');
    renderer = new THREE.WebGLRenderer({antialias:true});
    renderer.setClearColor(0x000000, 1.0);
    renderer.setSize(window.innerWidth, window.innerHeight);
    container.appendChild(renderer.domElement);
    // Scene
    scene = new THREE.Scene();
    // Camera
    camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 1000);
    camera.position.z = 80;

    // Geometry and Material
    var geometry = new THREE.OctahedronGeometry(30, 0);
    var material = new THREE.MeshBasicMaterial({
        color: 0xffffff,
        wireframe: true
    })
    //new THREE.MeshNormalMaterial();
    // Add the mesh
    mesh = new THREE.Mesh(geometry, material);
    // Add to scene
    scene.add(mesh);

    // Add stars
    for (var i = -1000; i < 1000; i+=20)
    {
        var geometry = new THREE.SphereGeometry(0.5, 32, 32);
        var material = new THREE.MeshBasicMaterial({color: 0xffffff});
        var sphere = new THREE.Mesh(geometry, material);

        sphere.position.x = Math.random() * 1000 - 500;
        sphere.position.y = Math.random() * 1000 - 500;

        sphere.position.z = i;

        sphere.scale.x = sphere.scale.y = 2;

        scene.add(sphere);
        stars.push(sphere);
    }

    //Window resize
    window.addEventListener('resize', onWindowResize, false);
}

function animate()
{
    requestAnimationFrame(animate);
    renderer.render(scene, camera);
    animateStars();

    mesh.rotation.x += 0.01;
    mesh.rotation.y += 0.01;
}

function animateStars()
{
    for (var i = 0; i < stars.length; i++) {
        star = stars[i];
        star.position.z += i / 10;
        if (star.position.z > 1000) {
            star.position.z -= 2000;
        }
    }
}

function onWindowResize()
{
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
}<commit_msg>Made the stars in the Diaspora sketch bigger<commit_after>/*
 * DIASPORA
 * -------------------
 * A cool sketch inspired by the cover of the
 * Greg Egan novel Diaspora
 *
 * License: MIT
*/

var camera, scene, renderer, container, mesh, composer;
var clock;
var stars = [];

document.addEventListener("DOMContentLoaded", startApp, false);

function startApp()
{
    init();
    animate();
}

function init()
{
    // Container and Renderer
    container = document.getElementById('container');
    renderer = new THREE.WebGLRenderer({antialias:true});
    renderer.setClearColor(0x000000, 1.0);
    renderer.setSize(window.innerWidth, window.innerHeight);
    container.appendChild(renderer.domElement);
    // Scene
    scene = new THREE.Scene();
    // Camera
    camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 1000);
    camera.position.z = 80;

    // Geometry and Material
    var geometry = new THREE.OctahedronGeometry(30, 0);
    var material = new THREE.MeshBasicMaterial({
        color: 0xffffff,
        wireframe: true
    })
    //new THREE.MeshNormalMaterial();
    // Add the mesh
    mesh = new THREE.Mesh(geometry, material);
    // Add to scene
    scene.add(mesh);

    // Add stars
    for (var i = -1000; i < 1000; i+=20)
    {
        var geometry = new THREE.SphereGeometry(0.5, 32, 32);
        var material = new THREE.MeshBasicMaterial({color: 0xffffff});
        var sphere = new THREE.Mesh(geometry, material);

        sphere.position.x = Math.random() * 1000 - 500;
        sphere.position.y = Math.random() * 1000 - 500;

        sphere.position.z = i;

        sphere.scale.x = sphere.scale.y = 4;

        scene.add(sphere);
        stars.push(sphere);
    }

    //Window resize
    window.addEventListener('resize', onWindowResize, false);
}

function animate()
{
    requestAnimationFrame(animate);
    renderer.render(scene, camera);
    animateStars();

    mesh.rotation.x += 0.01;
    mesh.rotation.y += 0.01;
}

function animateStars()
{
    for (var i = 0; i < stars.length; i++) {
        star = stars[i];
        star.position.z += i / 10;
        if (star.position.z > 1000) {
            star.position.z -= 2000;
        }
    }
}

function onWindowResize()
{
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
}<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var debug = require('debug')('formio:middleware:submissionResourceAccessFilter');

module.exports = function(router) {
  return function submissionResourceAccessFilter(req, res, next) {
    var util = router.formio.util;
    var hook = router.formio.hook;

    // Skip this filter, if not flagged in the permission handler.
    if (!_.has(req, 'submissionResourceAccessFilter') || !req.submissionResourceAccessFilter) {
      debug('Skipping, no req.submissionResourceAccessFilter.');
      return next();
    }

    // Should never get here without a form id present..
    if (!req.formId) {
      debug('No req.formId given.');
      return res.sendStatus(500);
    }

    // Should never get here with a submission id present..
    if (req.subId) {
      debug('req.subId given, skipping.');
      return res.sendStatus(500);
    }

    // Cant determine submission resource access for not authenticated users.
    if (!req.user || !_.has(req, 'user._id') || !req.user._id) {
      debug('No user given (' + req.user + ')');
      return res.sendStatus(401);
    }

    var user = req.user._id;
    var search = [util.idToString(user), util.idToBson(user)];
    hook.alter('resourceAccessFilter', search, req, function(err, search) {
      var query = {
        form: util.idToBson(req.formId),
        deleted: {$eq: null},
        $or: [
          {
            'access.type': {$in: ['read', 'write', 'admin']},
            'access.resources': {$in: search}
          },
          {
            owner: req.token.user._id
          }
        ]
      };

      debug(query);
      req.modelQuery = req.modelQuery || this.model;
      req.modelQuery = req.modelQuery.find(query);

      req.countQuery = req.countQuery || this.model;
      req.countQuery = req.countQuery.find(query);

      next();
    }.bind(this));
  };
};
<commit_msg>Fixing bithound issue.<commit_after>'use strict';

var _ = require('lodash');
var debug = require('debug')('formio:middleware:submissionResourceAccessFilter');

module.exports = function(router) {
  return function submissionResourceAccessFilter(req, res, next) {
    var util = router.formio.util;
    var hook = router.formio.hook;

    // Skip this filter, if not flagged in the permission handler.
    if (!_.has(req, 'submissionResourceAccessFilter') || !req.submissionResourceAccessFilter) {
      debug('Skipping, no req.submissionResourceAccessFilter.');
      return next();
    }

    // Should never get here without a form id present..
    if (!req.formId) {
      debug('No req.formId given.');
      return res.sendStatus(500);
    }

    // Should never get here with a submission id present..
    if (req.subId) {
      debug('req.subId given, skipping.');
      return res.sendStatus(500);
    }

    // Cant determine submission resource access for not authenticated users.
    if (!req.user || !_.has(req, 'user._id') || !req.user._id) {
      debug('No user given (' + req.user + ')');
      return res.sendStatus(401);
    }

    var user = req.user._id;
    var search = [util.idToString(user), util.idToBson(user)];
    hook.alter('resourceAccessFilter', search, req, function(err, search) {
      // Try to recover if the hook fails.
      if (err) {
        debug(err);
      }

      var query = {
        form: util.idToBson(req.formId),
        deleted: {$eq: null},
        $or: [
          {
            'access.type': {$in: ['read', 'write', 'admin']},
            'access.resources': {$in: search}
          },
          {
            owner: req.token.user._id
          }
        ]
      };

      debug(query);
      req.modelQuery = req.modelQuery || this.model;
      req.modelQuery = req.modelQuery.find(query);

      req.countQuery = req.countQuery || this.model;
      req.countQuery = req.countQuery.find(query);

      next();
    }.bind(this));
  };
};
<|endoftext|>


<commit_before>/* global Module */

/* Magic Mirror
 * Module: NewsFeed
 *
 * By Michael Teeuw http://michaelteeuw.nl
 * MIT Licensed.
 */

Module.register("newsfeed",{

	// Default module config.
	defaults: {
		feeds: [
			{
				title: "New York Times",
				url: "http://www.nytimes.com/services/xml/rss/nyt/HomePage.xml",
				encoding: "UTF-8" //ISO-8859-1
			}
		],
		showSourceTitle: true,
		showPublishDate: true,
		showDescription: false,
		reloadInterval:  5 * 60 * 1000, // every 5 minutes
		updateInterval: 10 * 1000,
		animationSpeed: 2.5 * 1000,
		maxNewsItems: 0, // 0 for unlimited
		removeStartTags: "",
		removeEndTags: "",
		startTags: [],
		endTags: []

	},

	// Define required scripts.
	getScripts: function() {
		return ["moment.js"];
	},

	// Define required translations.
	getTranslations: function() {
		// The translations for the defaut modules are defined in the core translation files.
		// Therefor we can just return false. Otherwise we should have returned a dictionairy.
		// If you're trying to build yiur own module including translations, check out the documentation.
		return false;
	},

	// Define start sequence.
	start: function() {
		Log.info("Starting module: " + this.name);

		// Set locale.
		moment.locale(config.language);

		this.newsItems = [];
		this.loaded = false;
		this.activeItem = 0;

		this.registerFeeds();

	},

	// Override socket notification handler.
	socketNotificationReceived: function(notification, payload) {
		if (notification === "NEWS_ITEMS") {
			this.generateFeed(payload);

			if (!this.loaded) {
				this.scheduleUpdateInterval();
			}

			this.loaded = true;
		}
	},

	// Override dom generator.
	getDom: function() {
		var wrapper = document.createElement("div");

		if (this.config.feedUrl) {
			wrapper.className = "small bright";
			wrapper.innerHTML = "The configuration options for the newsfeed module have changed.
Please check the documentation.";
			return wrapper;
		}

		if (this.activeItem >= this.newsItems.length) {
			this.activeItem = 0;
		}

		if (this.newsItems.length > 0) {

			// this.config.showFullArticle is a run-time configuration, triggered by optional notifications
			if (!this.config.showFullArticle && (this.config.showSourceTitle || this.config.showPublishDate)) {
				var sourceAndTimestamp = document.createElement("div");
				sourceAndTimestamp.className = "light small dimmed";

				if (this.config.showSourceTitle && this.newsItems[this.activeItem].sourceTitle !== "") {
					sourceAndTimestamp.innerHTML = this.newsItems[this.activeItem].sourceTitle;
				}
				if (this.config.showSourceTitle && this.newsItems[this.activeItem].sourceTitle !== "" && this.config.showPublishDate) {
					sourceAndTimestamp.innerHTML += ", ";
				}
				if (this.config.showPublishDate) {
					sourceAndTimestamp.innerHTML += moment(new Date(this.newsItems[this.activeItem].pubdate)).fromNow();
				}
				if (this.config.showSourceTitle && this.newsItems[this.activeItem].sourceTitle !== "" || this.config.showPublishDate) {
					sourceAndTimestamp.innerHTML += ":";
				}

				wrapper.appendChild(sourceAndTimestamp);
			}

			//Remove selected tags from the beginning of rss feed items (title or description)

			if (this.config.removeStartTags == "title" || this.config.removeStartTags == "both") {

				for (f=0; f<this.config.startTags.length;f++) {
					if (this.newsItems[this.activeItem].title.slice(0,this.config.startTags[f].length) == this.config.startTags[f]) {
						this.newsItems[this.activeItem].title = this.newsItems[this.activeItem].title.slice(this.config.startTags[f].length,this.newsItems[this.activeItem].title.length);
					}
				}

			}

			if (this.config.removeStartTags == "description" || this.config.removeStartTags == "both") {

				if (this.config.showDescription) {
					for (f=0; f<this.config.startTags.length;f++) {
						if (this.newsItems[this.activeItem].description.slice(0,this.config.startTags[f].length) == this.config.startTags[f]) {
							this.newsItems[this.activeItem].title = this.newsItems[this.activeItem].description.slice(this.config.startTags[f].length,this.newsItems[this.activeItem].description.length);
						}
					}
				}

			}

			//Remove selected tags from the end of rss feed items (title or description)

			if (this.config.removeEndTags) {
				for (f=0; f<this.config.endTags.length;f++) {
					if (this.newsItems[this.activeItem].title.slice(-this.config.endTags[f].length)==this.config.endTags[f]) {
						this.newsItems[this.activeItem].title = this.newsItems[this.activeItem].title.slice(0,-this.config.endTags[f].length);
					}
				}

				if (this.config.showDescription) {
					for (f=0; f<this.config.endTags.length;f++) {
						if (this.newsItems[this.activeItem].description.slice(-this.config.endTags[f].length)==this.config.endTags[f]) {
							this.newsItems[this.activeItem].description = this.newsItems[this.activeItem].description.slice(0,-this.config.endTags[f].length);
						}
					}
				}

			}

			if(!this.config.showFullArticle){
				var title = document.createElement("div");
				title.className = "bright medium light";
				title.innerHTML = this.newsItems[this.activeItem].title;
				wrapper.appendChild(title);
			}

			if (this.config.showDescription) {
				var description = document.createElement("div");
				description.className = "small light";
				description.innerHTML = this.newsItems[this.activeItem].description;
				wrapper.appendChild(description);
			}

			if (this.config.showFullArticle) {
				var fullArticle = document.createElement("iframe");
				fullArticle.className = "";
				fullArticle.style.width = "100%";
				fullArticle.style.top = "0";
				fullArticle.style.left = "0";
				fullArticle.style.position = "fixed";
				fullArticle.height = window.innerHeight;
				fullArticle.style.border = "none";
				fullArticle.src = this.newsItems[this.activeItem].url;
				wrapper.appendChild(fullArticle);
			}

		} else {
			wrapper.innerHTML = this.translate("LOADING");
			wrapper.className = "small dimmed";
		}

		return wrapper;
	},

	/* registerFeeds()
	 * registers the feeds to be used by the backend.
	 */

	registerFeeds: function() {
		for (var f in this.config.feeds) {
			var feed = this.config.feeds[f];
			this.sendSocketNotification("ADD_FEED", {
				feed: feed,
				config: this.config
			});
		}
	},

	/* registerFeeds()
	 * Generate an ordered list of items for this configured module.
	 *
	 * attribute feeds object - An object with feeds returned by the nod helper.
	 */
	generateFeed: function(feeds) {
		var newsItems = [];
		for (var feed in feeds) {
			var feedItems = feeds[feed];
			if (this.subscribedToFeed(feed)) {
				for (var i in feedItems) {
					var item = feedItems[i];
					item.sourceTitle = this.titleForFeed(feed);
					newsItems.push(item);
				}
			}
		}
		newsItems.sort(function(a,b) {
			var dateA = new Date(a.pubdate);
			var dateB = new Date(b.pubdate);
			return dateB - dateA;
		});
		if(this.config.maxNewsItems > 0) {
			newsItems = newsItems.slice(0, this.config.maxNewsItems);
		}
		this.newsItems = newsItems;
	},

	/* subscribedToFeed(feedUrl)
	 * Check if this module is configured to show this feed.
	 *
	 * attribute feedUrl string - Url of the feed to check.
	 *
	 * returns bool
	 */
	subscribedToFeed: function(feedUrl) {
		for (var f in this.config.feeds) {
			var feed = this.config.feeds[f];
			if (feed.url === feedUrl) {
				return true;
			}
		}
		return false;
	},

	/* subscribedToFeed(feedUrl)
	 * Returns title for a specific feed Url.
	 *
	 * attribute feedUrl string - Url of the feed to check.
	 *
	 * returns string
	 */
	titleForFeed: function(feedUrl) {
		for (var f in this.config.feeds) {
			var feed = this.config.feeds[f];
			if (feed.url === feedUrl) {
				return feed.title || "";
			}
		}
		return "";
	},

	/* scheduleUpdateInterval()
	 * Schedule visual update.
	 */
	scheduleUpdateInterval: function() {
		var self = this;

		self.updateDom(self.config.animationSpeed);

		timer = setInterval(function() {
			self.activeItem++;
			self.updateDom(self.config.animationSpeed);
		}, this.config.updateInterval);
	},

	/* capitalizeFirstLetter(string)
	 * Capitalizes the first character of a string.
	 *
	 * argument string string - Input string.
	 *
	 * return string - Capitalized output string.
	 */
	capitalizeFirstLetter: function(string) {
		return string.charAt(0).toUpperCase() + string.slice(1);
	},

	resetDescrOrFullArticleAndTimer: function() {
		this.config.showDescription = false;
		this.config.showFullArticle = false;
		if(!timer){
			this.scheduleUpdateInterval();
		}
	},

	notificationReceived: function(notification, payload, sender) {
		Log.info(this.name + " - received notification: " + notification);
		if(notification == "ARTICLE_NEXT"){
			var before = this.activeItem;
			this.activeItem++;
			if (this.activeItem >= this.newsItems.length) {
				this.activeItem = 0;
			}
			this.resetDescrOrFullArticleAndTimer();
			Log.info(this.name + " - going from article #" + before + " to #" + this.activeItem + " (of " + this.newsItems.length + ")");
			this.updateDom(100);
		} else if(notification == "ARTICLE_PREVIOUS"){
			var before = this.activeItem;
			this.activeItem--;
			if (this.activeItem < 0) {
				this.activeItem = this.newsItems.length - 1;
			}
			this.resetDescrOrFullArticleAndTimer();
			Log.info(this.name + " - going from article #" + before + " to #" + this.activeItem + " (of " + this.newsItems.length + ")");
			this.updateDom(100);
		}
		// if "more details" is received the first time: show article summary, on second time show full article
		else if(notification == "ARTICLE_MORE_DETAILS"){
			this.config.showDescription = !this.config.showDescription;
			this.config.showFullArticle = !this.config.showDescription;
			clearInterval(timer);
			timer = null;
			Log.info(this.name + " - showing " + this.config.showDescription ? "article description" : "full article");
			this.updateDom(100);
		} else if(notification == "ARTICLE_LESS_DETAILS"){
			this.resetDescrOrFullArticleAndTimer();
			Log.info(this.name + " - showing only article titles again");
			this.updateDom(100);
		} else {
			Log.info(this.name + " - unknown notification, ignoring: " + notification);
		}
	},

});
<commit_msg>Hide News Feed loading option<commit_after>/* global Module */

/* Magic Mirror
 * Module: NewsFeed
 *
 * By Michael Teeuw http://michaelteeuw.nl
 * MIT Licensed.
 */

Module.register("newsfeed",{

	// Default module config.
	defaults: {
		feeds: [
			{
				title: "New York Times",
				url: "http://www.nytimes.com/services/xml/rss/nyt/HomePage.xml",
				encoding: "UTF-8" //ISO-8859-1
			}
		],
		showSourceTitle: true,
		showPublishDate: true,
		showDescription: false,
		hideLoading: false,
		reloadInterval:  5 * 60 * 1000, // every 5 minutes
		updateInterval: 10 * 1000,
		animationSpeed: 2.5 * 1000,
		maxNewsItems: 0, // 0 for unlimited
		removeStartTags: "",
		removeEndTags: "",
		startTags: [],
		endTags: []

	},

	// Define required scripts.
	getScripts: function() {
		return ["moment.js"];
	},

	// Define required translations.
	getTranslations: function() {
		// The translations for the defaut modules are defined in the core translation files.
		// Therefor we can just return false. Otherwise we should have returned a dictionairy.
		// If you're trying to build yiur own module including translations, check out the documentation.
		return false;
	},

	// Define start sequence.
	start: function() {
		Log.info("Starting module: " + this.name);

		// Set locale.
		moment.locale(config.language);

		this.newsItems = [];
		this.loaded = false;
		this.activeItem = 0;

		this.registerFeeds();

	},

	// Override socket notification handler.
	socketNotificationReceived: function(notification, payload) {
		if (notification === "NEWS_ITEMS") {
			this.generateFeed(payload);

			if (!this.loaded) {
				this.scheduleUpdateInterval();
			}

			this.loaded = true;
		}
	},

	// Override dom generator.
	getDom: function() {
		var wrapper = document.createElement("div");

		if (this.config.feedUrl) {
			wrapper.className = "small bright";
			wrapper.innerHTML = "The configuration options for the newsfeed module have changed.
Please check the documentation.";
			return wrapper;
		}

		if (this.activeItem >= this.newsItems.length) {
			this.activeItem = 0;
		}

		if (this.newsItems.length > 0) {

			// this.config.showFullArticle is a run-time configuration, triggered by optional notifications
			if (!this.config.showFullArticle && (this.config.showSourceTitle || this.config.showPublishDate)) {
				var sourceAndTimestamp = document.createElement("div");
				sourceAndTimestamp.className = "light small dimmed";

				if (this.config.showSourceTitle && this.newsItems[this.activeItem].sourceTitle !== "") {
					sourceAndTimestamp.innerHTML = this.newsItems[this.activeItem].sourceTitle;
				}
				if (this.config.showSourceTitle && this.newsItems[this.activeItem].sourceTitle !== "" && this.config.showPublishDate) {
					sourceAndTimestamp.innerHTML += ", ";
				}
				if (this.config.showPublishDate) {
					sourceAndTimestamp.innerHTML += moment(new Date(this.newsItems[this.activeItem].pubdate)).fromNow();
				}
				if (this.config.showSourceTitle && this.newsItems[this.activeItem].sourceTitle !== "" || this.config.showPublishDate) {
					sourceAndTimestamp.innerHTML += ":";
				}

				wrapper.appendChild(sourceAndTimestamp);
			}

			//Remove selected tags from the beginning of rss feed items (title or description)

			if (this.config.removeStartTags == "title" || this.config.removeStartTags == "both") {

				for (f=0; f<this.config.startTags.length;f++) {
					if (this.newsItems[this.activeItem].title.slice(0,this.config.startTags[f].length) == this.config.startTags[f]) {
						this.newsItems[this.activeItem].title = this.newsItems[this.activeItem].title.slice(this.config.startTags[f].length,this.newsItems[this.activeItem].title.length);
					}
				}

			}

			if (this.config.removeStartTags == "description" || this.config.removeStartTags == "both") {

				if (this.config.showDescription) {
					for (f=0; f<this.config.startTags.length;f++) {
						if (this.newsItems[this.activeItem].description.slice(0,this.config.startTags[f].length) == this.config.startTags[f]) {
							this.newsItems[this.activeItem].title = this.newsItems[this.activeItem].description.slice(this.config.startTags[f].length,this.newsItems[this.activeItem].description.length);
						}
					}
				}

			}

			//Remove selected tags from the end of rss feed items (title or description)

			if (this.config.removeEndTags) {
				for (f=0; f<this.config.endTags.length;f++) {
					if (this.newsItems[this.activeItem].title.slice(-this.config.endTags[f].length)==this.config.endTags[f]) {
						this.newsItems[this.activeItem].title = this.newsItems[this.activeItem].title.slice(0,-this.config.endTags[f].length);
					}
				}

				if (this.config.showDescription) {
					for (f=0; f<this.config.endTags.length;f++) {
						if (this.newsItems[this.activeItem].description.slice(-this.config.endTags[f].length)==this.config.endTags[f]) {
							this.newsItems[this.activeItem].description = this.newsItems[this.activeItem].description.slice(0,-this.config.endTags[f].length);
						}
					}
				}

			}

			if(!this.config.showFullArticle){
				var title = document.createElement("div");
				title.className = "bright medium light";
				title.innerHTML = this.newsItems[this.activeItem].title;
				wrapper.appendChild(title);
			}

			if (this.config.showDescription) {
				var description = document.createElement("div");
				description.className = "small light";
				description.innerHTML = this.newsItems[this.activeItem].description;
				wrapper.appendChild(description);
			}

			if (this.config.showFullArticle) {
				var fullArticle = document.createElement("iframe");
				fullArticle.className = "";
				fullArticle.style.width = "100%";
				fullArticle.style.top = "0";
				fullArticle.style.left = "0";
				fullArticle.style.position = "fixed";
				fullArticle.height = window.innerHeight;
				fullArticle.style.border = "none";
				fullArticle.src = this.newsItems[this.activeItem].url;
				wrapper.appendChild(fullArticle);
			}

			if (this.config.hideLoading) {
				this.show();
			}

		} else {
			if (this.config.hideLoading) {
				this.hide();
			} else {
				wrapper.innerHTML = this.translate("LOADING");
				wrapper.className = "small dimmed";
			}
		}

		return wrapper;
	},

	/* registerFeeds()
	 * registers the feeds to be used by the backend.
	 */

	registerFeeds: function() {
		for (var f in this.config.feeds) {
			var feed = this.config.feeds[f];
			this.sendSocketNotification("ADD_FEED", {
				feed: feed,
				config: this.config
			});
		}
	},

	/* registerFeeds()
	 * Generate an ordered list of items for this configured module.
	 *
	 * attribute feeds object - An object with feeds returned by the nod helper.
	 */
	generateFeed: function(feeds) {
		var newsItems = [];
		for (var feed in feeds) {
			var feedItems = feeds[feed];
			if (this.subscribedToFeed(feed)) {
				for (var i in feedItems) {
					var item = feedItems[i];
					item.sourceTitle = this.titleForFeed(feed);
					newsItems.push(item);
				}
			}
		}
		newsItems.sort(function(a,b) {
			var dateA = new Date(a.pubdate);
			var dateB = new Date(b.pubdate);
			return dateB - dateA;
		});
		if(this.config.maxNewsItems > 0) {
			newsItems = newsItems.slice(0, this.config.maxNewsItems);
		}
		this.newsItems = newsItems;
	},

	/* subscribedToFeed(feedUrl)
	 * Check if this module is configured to show this feed.
	 *
	 * attribute feedUrl string - Url of the feed to check.
	 *
	 * returns bool
	 */
	subscribedToFeed: function(feedUrl) {
		for (var f in this.config.feeds) {
			var feed = this.config.feeds[f];
			if (feed.url === feedUrl) {
				return true;
			}
		}
		return false;
	},

	/* subscribedToFeed(feedUrl)
	 * Returns title for a specific feed Url.
	 *
	 * attribute feedUrl string - Url of the feed to check.
	 *
	 * returns string
	 */
	titleForFeed: function(feedUrl) {
		for (var f in this.config.feeds) {
			var feed = this.config.feeds[f];
			if (feed.url === feedUrl) {
				return feed.title || "";
			}
		}
		return "";
	},

	/* scheduleUpdateInterval()
	 * Schedule visual update.
	 */
	scheduleUpdateInterval: function() {
		var self = this;

		self.updateDom(self.config.animationSpeed);

		timer = setInterval(function() {
			self.activeItem++;
			self.updateDom(self.config.animationSpeed);
		}, this.config.updateInterval);
	},

	/* capitalizeFirstLetter(string)
	 * Capitalizes the first character of a string.
	 *
	 * argument string string - Input string.
	 *
	 * return string - Capitalized output string.
	 */
	capitalizeFirstLetter: function(string) {
		return string.charAt(0).toUpperCase() + string.slice(1);
	},

	resetDescrOrFullArticleAndTimer: function() {
		this.config.showDescription = false;
		this.config.showFullArticle = false;
		if(!timer){
			this.scheduleUpdateInterval();
		}
	},

	notificationReceived: function(notification, payload, sender) {
		Log.info(this.name + " - received notification: " + notification);
		if(notification == "ARTICLE_NEXT"){
			var before = this.activeItem;
			this.activeItem++;
			if (this.activeItem >= this.newsItems.length) {
				this.activeItem = 0;
			}
			this.resetDescrOrFullArticleAndTimer();
			Log.info(this.name + " - going from article #" + before + " to #" + this.activeItem + " (of " + this.newsItems.length + ")");
			this.updateDom(100);
		} else if(notification == "ARTICLE_PREVIOUS"){
			var before = this.activeItem;
			this.activeItem--;
			if (this.activeItem < 0) {
				this.activeItem = this.newsItems.length - 1;
			}
			this.resetDescrOrFullArticleAndTimer();
			Log.info(this.name + " - going from article #" + before + " to #" + this.activeItem + " (of " + this.newsItems.length + ")");
			this.updateDom(100);
		}
		// if "more details" is received the first time: show article summary, on second time show full article
		else if(notification == "ARTICLE_MORE_DETAILS"){
			this.config.showDescription = !this.config.showDescription;
			this.config.showFullArticle = !this.config.showDescription;
			clearInterval(timer);
			timer = null;
			Log.info(this.name + " - showing " + this.config.showDescription ? "article description" : "full article");
			this.updateDom(100);
		} else if(notification == "ARTICLE_LESS_DETAILS"){
			this.resetDescrOrFullArticleAndTimer();
			Log.info(this.name + " - showing only article titles again");
			this.updateDom(100);
		} else {
			Log.info(this.name + " - unknown notification, ignoring: " + notification);
		}
	},

});
<|endoftext|>


<commit_before>import {inject} from 'aurelia-framework';
import {HttpClient} from 'aurelia-fetch-client';
// import io from 'socket.io-client';
import 'whatwg-fetch';

@inject(HttpClient)
export class Home {
    heading = 'Home';
    consoleOutputList = [];
    socket = undefined;

    constructor(http) {
        this.socket = io();

        http.configure(config => {
            config
            .useStandardConfiguration()
            .withBaseUrl('/executeShell');
        });

        this.http = http;

        this.registerShellListener();
    }

    callServer(uri) {
        this.consoleOutputList = [];

        return this.http.fetch(uri)
        .then(response => response.json())
        .then(responseObject => {
            this.consoleOutputList.push(responseObject);
        });
    }

    registerShellListener() {
        this.socket.on('shellLog', (consoleOutput) =>{
            this.consoleOutputList.push(consoleOutput);
        });
    }
}
<commit_msg>Changed how request response is handled<commit_after>import {inject} from 'aurelia-framework';
import {HttpClient} from 'aurelia-fetch-client';
// import io from 'socket.io-client';
import 'whatwg-fetch';

@inject(HttpClient)
export class Home {
    heading = 'Home';
    consoleOutputList = [];
    socket = undefined;

    constructor(http) {
        this.socket = io();

        http.configure(config => {
            config
            .useStandardConfiguration()
            .withBaseUrl('/executeShell');
        });

        this.http = http;

        this.registerShellListener();
    }

    callServer(uri) {
        this.consoleOutputList = [];

        return this.http.fetch(uri)
        .then(response => response.json())
        .then(responseObject => {
            console.log(responseObject);
        });
    }

    registerShellListener() {
        this.socket.on('shellLog', (consoleOutput) =>{
            this.consoleOutputList.push(consoleOutput);
        });
    }
}
<|endoftext|>


<commit_before>// Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// Licensed under the Apache-2.0 License on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND.

// ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at
// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sns-examples-publishing-messages.html
// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set region
AWS.config.update({region: 'us-west-2'});

// Create publish parameters
var params = {
  Message: 'This is David sending another text message from programming code.', /* required */
  TopicArn: 'arn:aws:sns:us-west-2:617985816162:FirstTopic',
};

// Create promise and SNS service object
var publishTextPromise = new AWS.SNS({apiVersion: '2010-03-31'}).publish(params).promise();

// handle promise's fulfilled/rejected states
publishTextPromise.then(
  function(data) {
    console.log("Message ${params.message} send sent to the topic ${params.topicArn}");
    console.log("MessageID is " + data.MessageId);
  }).catch(
    function(err) {
    console.error(err, err.stack);
  });
<commit_msg>Update sns_publishtotopic.js<commit_after>// Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// Licensed under the Apache-2.0 License on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND.

// ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at
// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sns-examples-publishing-messages.html
// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set region
AWS.config.update({region: 'us-west-2'});

// Create publish parameters
var params = {
  Message: 'This is David sending another text message from programming code.', /* required */
  TopicArn: 'TOPIC_ARN',
};

// Create promise and SNS service object
var publishTextPromise = new AWS.SNS({apiVersion: '2010-03-31'}).publish(params).promise();

// handle promise's fulfilled/rejected states
publishTextPromise.then(
  function(data) {
    console.log("Message ${params.message} send sent to the topic ${params.topicArn}");
    console.log("MessageID is " + data.MessageId);
  }).catch(
    function(err) {
    console.error(err, err.stack);
  });
<|endoftext|>


<commit_before>{"202":{"department":"NENS","number":"202","title":"Longevity (HUMBIO 149L, PSYCH 102)","description":"Interdisciplinary. Challenges to and solutions for the young from increased human life expectancy: health care, financial markets, families, work, and politics. Guest lectures from engineers, economists, geneticists, and physiologists.","min_units":4,"max_units":4,"gers":[],"id":205238,"primary":[[],[{"instructors":[],"meeting-times":[{"days":[true,false,true,false,false],"start":"11:00:00 AM","end":"12:15:00 PM","location":"420-040"}],"id":56634}],[]],"primary_type":"Lecture"},
"204":{"department":"NENS","number":"204","title":"Stroke Seminar","description":"Standing at the intersection of many fields of medicine, including neurology, internal medicine, cerebrovascualr surgery, diagnostic and interventional radiology, and emergency medicine, as the third leading cause of death and the leading cause of disability, stroke is a critical topic for all practitioners of medicine. This seminar draws upon Stanford's leaders in stroke research to present and discuss the causes, presentation, treatment, and imaging characteristics of the disease.","min_units":1,"max_units":1,"gers":[],"id":209452,"primary":[[],[{"instructors":[],"meeting-times":[{"days":[false,true,false,false,false],"start":"12:00:00 PM","end":"1:05:00 PM","location":"Alway Building, Room M112"}],"id":54942}],[]],"primary_type":"Seminar"},
"206":{"department":"NENS","number":"206","title":"Introduction to Neurology Seminar","description":"Exploration of aspects of neurology, including subspecialties.  Current issues, clinical cases, and opportunities in the field.","min_units":1,"max_units":1,"gers":[],"id":208208,"primary":[[{"instructors":[],"meeting-times":[{"days":[false,false,false,true,false],"start":"12:00:00 PM","end":"1:00:00 PM","location":"CCSR 4205"}],"id":53865}],[],[]],"primary_type":"Seminar"},
"230":{"department":"NENS","number":"230","title":"Analysis Techniques for the Biosciences Using MATLAB","description":"Data analysis and visualization techniques commonly encountered in biosciences research. Fundamentals of the MATLAB computing environment, programming and debugging, data import/export, data structures, plotting, image analysis, introduction to statistical tools. Examples and assignments draw from a range of topics applicable to bioscience research: frequency analysis, genetic data mining, ion channel kinetics, neural spike rasters and spike-triggered averages, cell counting in fluorescence images, regression, PCA, and stochastic simulation. Assignments are practical in nature and demonstrate how to implement specific analyses that a biosciences student is likely to encounter.","min_units":2,"max_units":2,"gers":[],"id":212760,"primary":[[{"instructors":[],"meeting-times":[{"days":[true,false,false,false,false],"start":"9:00:00 AM","end":"10:50:00 AM","location":"Li Ka Shing Center, room 208"}],"id":54557}],[],[]],"primary_type":"Lab"},
"267":{"department":"NENS","number":"267","title":"Molecular Mechanisms of Neurodegenerative Disease (BIO 267)","description":"The epidemic of neurodegenerative disorders such as Alzheimer's and Parkinson's disease occasioned by an aging human population. Genetic, molecular, and cellular mechanisms. Clinical aspects through case presentations.","min_units":4,"max_units":4,"gers":[],"id":205781,"primary":[[],[{"instructors":[],"meeting-times":[{"days":[false,true,false,true,false],"start":"1:15:00 PM","end":"3:05:00 PM","location":""}],"id":56636}],[]],"primary_type":"Lecture"},
"67N":{"department":"NENS","number":"67N","title":"Intracellular Trafficking and Neurodegeneration","description":"Preference to freshmen. Cell structures and functions, the intracellular trafficking system that maintains exchanges of materials and information inside cells, and clinical features and pathologies of neurodegenerative diseases. Techniques for examining cellular and subcellular structures, especially cytoskeletons; functional insights generated from structural explorations. Prerequisite: high school biology.","min_units":3,"max_units":3,"gers":["WAY-SMA"],"id":207789,"primary":[[],[],[{"instructors":[],"meeting-times":[{"days":[false,true,false,true,false],"start":"5:30:00 PM","end":"7:00:00 PM","location":"Li Ka Shing Center, room 306"}],"id":55097}]],"primary_type":"Introsem"}}<commit_msg>Delete NENS.js<commit_after><|endoftext|>


<commit_before>/**
 * default service pack
 */

'use strict';
const marked = require('marked');
const fs = require('fs');
require(_PATH_LIB + 'example');

APP.get('/', function (req, res) {
  let file = _PATH_ROOT + 'README.md';
  let opts = {
    renderer: new marked.Renderer(),
    gfm: true,
    tables: true,
    breaks: false,
    pedantic: false,
    sanitize: true,
    smartLists: true,
    smartypants: false
  };
  marked.setOptions(opts);
  let src = marked(fs.readFileSync(file).toString()).replace(/
/g, '
');
  res.send(`

    <title>Node Micro Service Bootstrap</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
    rel="stylesheet"
    crossorigin="anonymous">

You are seeing this page because the default service is loaded,
    run the app with custom services and the default service will be replaced.

    ${src}

  `);
});

/**
 * example apis
 */
APP.get('/example/:action', function (req, res) {
  const example = _LIB.example;
  const action = req.params.action;
  let response = {};
  // callback and use response maker
  try {
    const callback = _LIB.example[action];
    _log('EXAMPLE', {
      action: action,
      callback: callback,
      params: req.params
    });
    response = _LIB.util.response.success(callback('hello world'), `action ${action} success`);
  } catch (e) {
    _log('EXAMPLE', {
      action: action,
      error: e.toString()
    }, 'ERROR');
    response = _LIB.util.response.error(e);
  }
  // return response
  res.send(response);
});
<commit_msg>add example logging<commit_after>/**
 * default service pack
 */

'use strict';
const marked = require('marked');
const fs = require('fs');
require(_PATH_LIB + 'example');

APP.get('/', function (req, res) {
  let file = _PATH_ROOT + 'README.md';
  let opts = {
    renderer: new marked.Renderer(),
    gfm: true,
    tables: true,
    breaks: false,
    pedantic: false,
    sanitize: true,
    smartLists: true,
    smartypants: false
  };
  marked.setOptions(opts);
  let src = marked(fs.readFileSync(file).toString()).replace(/
/g, '
');
  res.send(`

    <title>Node Micro Service Bootstrap</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
    rel="stylesheet"
    crossorigin="anonymous">

You are seeing this page because the default service is loaded,
    run the app with custom services and the default service will be replaced.

    ${src}

  `);
});

/**
 * example apis
 */
APP.get('/example/:action', function (req, res) {
  const example = _LIB.example;
  const action = req.params.action;
  let response = {};
  // callback and use response maker
  try {
    const callback = _LIB.example[action];
    // log info example
    _log('EXAMPLE', {
      action: action,
      callback: callback,
      params: req.params
    });

    response = _LIB.util.response.success(callback('hello world'), `action ${action} success`);

    // log success example
    _log('EXAMPLE', 'success');
  } catch (e) {
    // log error example
    _log('EXAMPLE', {
      action: action,
      error: e.toString()
    }, 'ERROR');

    response = _LIB.util.response.error(e);
  }
  // return response
  res.send(response);
});
<|endoftext|>


<commit_before>define(['jquery', 'backbone', 'chrome', 'apps/poi/js/PoiCollection', 'text!apps/poi/templates/poi-tpl.html', 'apps/poi/js/PoiTypeCollection', 'gmaps', 'locator'], function ($, Backbone, Chrome, PoiCollection, Templates, PoiTypeCollection, GMaps, Locator) {
  'use strict';
  Templates = $('
').html(Templates);

  var View = Backbone.View.extend({
    collection: PoiCollection,
    typeid: null,
    poiid: null,
    directions: null,
    directionsType: null,
    all: false,
    el: "body",
    initialize: function(info) {
      this.typeid = info.typeid || null;
      this.poiid = info.poiid || null;
      this.directions = info.directions || false;
      this.directionsType = info.directionsType || null;
      this.all = !this.typeid && !this.poiid && !this.directions;
      var that = this;

      $(this.el).undelegate('#findMe', 'click');

      // Remove all previous bound events to avoid repeated bindings
      $(document).off('pageshow.poiMap');

      $(document).on('pageshow.poiMap', '#poiMap', function (event) {
        $("#mapCanvas").css({
          width: $("#poiMap").width(),
          height: $("#poiMap").height() - $("#mapHeader").height()
        } );

        that.mapRender(that.typeid, that.poiid, that.directions, that.directionsType, that.all);
      });
      if(!this.collection.loaded) {
        var that = this;
        this.collection.fetch().success(function(){
          that.render();
        });
      } else {
        this.render();
      }
    },

    template: _.template(Templates.find('#poiMapTemplate').html()),

    events: {
      "click #findMe": "findMeCenter"
    },

    mapRender: function(typeid, poiid, directions, directionsType, all) {
      typeid = typeid || null;
      poiid = poiid || null;
      directions = directions || false;
      directionsType = directionsType || null;
      var poiCollection = !typeid || all ?
        this.collection :
        this.collection.filterByType( typeid )
        ;

      var mainpoi = poiid ? poiCollection.get(poiid) : null;

      var useBounds = mainpoi ? false : true;

      this.mapLoad()
        .mapDrawPoints(poiCollection, mainpoi, typeid, all, useBounds)
        .mapCenterPoint(mainpoi)
        .mapDrawDirections(directions, directionsType, mainpoi);

      if( !useBounds) {
        this.mapSetZoom(19);
      }
    },

    mapLoad: function() {
      GMaps.loadInto( $('#mapCanvas').get(0) );
      return this;
    },

    mapDrawPoints: function(poiCollection, mainpoi, typeid, all, useBounds) {
      if( typeid === null && !all) {
        return this;
      }
      var pois = [], image;

      if( !mainpoi ) {
        poiCollection.each(function(poi){
          image = poi.get("active") ?
            PoiTypeCollection.get(poi.get('type')).get( 'mapImage' ) :
            PoiTypeCollection.get(poi.get('type')).get( 'closedMapImage' );

          pois.push( {
            name: poi.get("name"),
            link: ''+poi.get('name')+'',
            lat: poi.get("latitude"),
            lng: poi.get("longitude"),
            image: image
          });
        });
      } else {
        image = mainpoi.get("active") ?
          PoiTypeCollection.get(mainpoi.get('type')).get( 'mapImage' ) :
          PoiTypeCollection.get(mainpoi.get('type')).get( 'closedMapImage' );

        pois.push( {
          name: mainpoi.get("name"),
          link: ''+mainpoi.get('name')+'',
          lat: mainpoi.get("latitude"),
          lng: mainpoi.get("longitude"),
          image: image
        });
      }

      GMaps.drawPoints( pois, useBounds );
      return this;
    },

    mapSetZoom: function(level) {
      GMaps.setZoom(level);
      return this;
    },

    mapCenterPoint: function(mainpoi) {
      if( !mainpoi ) {
        return this;
      }
      GMaps.setCenter({
        lat: mainpoi.get("latitude"),
        lng: mainpoi.get("longitude"),
      });
      return this;
    },

    mapDrawDirections: function(directions, directionsType, mainpoi) {
      if( !directions || !mainpoi) {
        return this;
      }
      Locator.location(function(from, success){
        if(success) {
          var to = {
            lat: mainpoi.get("latitude"),
            lng: mainpoi.get("longitude"),
          };
          GMaps.drawDirections(from, to, directionsType);
        }
      });
      return this;
    },

    render: function() {
      var filteredPois = this.typeid === null ?
        this.collection :
        this.collection.filterByType( this.typeid );
      var html = this.template({pois: filteredPois.toJSON()});

      var parsehtml = Chrome.parseHTML(html);
      this.urlAlterHtml( parsehtml, filteredPois );
      Chrome.showPage( parsehtml );
    },

    /**
     * Function that makes addtional html alterations based on current url
     */
    urlAlterHtml: function( parsehtml, pois ) {
      // Url directions
      if( window.location.hash.substring(0, 20) == '#poi/info/directions' ) {

        // Add footer with various direction options
        var $footer = parsehtml.find( 'div[data-role="footer"]' );
        var directions_path = '#poi/info/directions' + '/' + this.poiid + '/';

        var driving_active = "";
        var transit_active = "";
        var bicycling_active = "";
        var walking_active = "";

        switch( this.directionsType ) {
          case "driving":
            driving_active = "ui-btn-active ui-state-persist";
            break;
          case "transit":
            transit_active = "ui-btn-active ui-state-persist";
            break;
          case "bicycling":
            bicycling_active = "ui-btn-active ui-state-persist";
            break;
          case "walking":
            walking_active = "ui-btn-active ui-state-persist";
            break;
        }

        $footer.append( $('
' +
          'Bil' +
          'Transit' +
          'Cykel' +
          'Gång' +
          '
') );

        // Link close button back to poi info page, instead of simple 'back'
        var $closeButton = parsehtml.find( '#closeButton' );
        $closeButton.removeAttr('data-direction');
        $closeButton.removeAttr('data-rel');
        $closeButton.prop('href', "#poi/info/" + this.poiid );
      }
    },

    findMeCenter: function() {
      Locator.location(function(myPos, success){
        if(success) {
          GMaps.setCenter(myPos, true);
        }
      });

      return false;
    }
  });

  return View;
});

//
<commit_msg>Increase zoom out when viewing individual poi<commit_after>define(['jquery', 'backbone', 'chrome', 'apps/poi/js/PoiCollection', 'text!apps/poi/templates/poi-tpl.html', 'apps/poi/js/PoiTypeCollection', 'gmaps', 'locator'], function ($, Backbone, Chrome, PoiCollection, Templates, PoiTypeCollection, GMaps, Locator) {
  'use strict';
  Templates = $('
').html(Templates);

  var View = Backbone.View.extend({
    collection: PoiCollection,
    typeid: null,
    poiid: null,
    directions: null,
    directionsType: null,
    all: false,
    el: "body",
    initialize: function(info) {
      this.typeid = info.typeid || null;
      this.poiid = info.poiid || null;
      this.directions = info.directions || false;
      this.directionsType = info.directionsType || null;
      this.all = !this.typeid && !this.poiid && !this.directions;
      var that = this;

      $(this.el).undelegate('#findMe', 'click');

      // Remove all previous bound events to avoid repeated bindings
      $(document).off('pageshow.poiMap');

      $(document).on('pageshow.poiMap', '#poiMap', function (event) {
        $("#mapCanvas").css({
          width: $("#poiMap").width(),
          height: $("#poiMap").height() - $("#mapHeader").height()
        } );

        that.mapRender(that.typeid, that.poiid, that.directions, that.directionsType, that.all);
      });
      if(!this.collection.loaded) {
        var that = this;
        this.collection.fetch().success(function(){
          that.render();
        });
      } else {
        this.render();
      }
    },

    template: _.template(Templates.find('#poiMapTemplate').html()),

    events: {
      "click #findMe": "findMeCenter"
    },

    mapRender: function(typeid, poiid, directions, directionsType, all) {
      typeid = typeid || null;
      poiid = poiid || null;
      directions = directions || false;
      directionsType = directionsType || null;
      var poiCollection = !typeid || all ?
        this.collection :
        this.collection.filterByType( typeid )
        ;

      var mainpoi = poiid ? poiCollection.get(poiid) : null;

      var useBounds = mainpoi ? false : true;

      this.mapLoad()
        .mapDrawPoints(poiCollection, mainpoi, typeid, all, useBounds)
        .mapCenterPoint(mainpoi)
        .mapDrawDirections(directions, directionsType, mainpoi);

      if( !useBounds) {
        this.mapSetZoom(15);
      }
    },

    mapLoad: function() {
      GMaps.loadInto( $('#mapCanvas').get(0) );
      return this;
    },

    mapDrawPoints: function(poiCollection, mainpoi, typeid, all, useBounds) {
      if( typeid === null && !all) {
        return this;
      }
      var pois = [], image;

      if( !mainpoi ) {
        poiCollection.each(function(poi){
          image = poi.get("active") ?
            PoiTypeCollection.get(poi.get('type')).get( 'mapImage' ) :
            PoiTypeCollection.get(poi.get('type')).get( 'closedMapImage' );

          pois.push( {
            name: poi.get("name"),
            link: ''+poi.get('name')+'',
            lat: poi.get("latitude"),
            lng: poi.get("longitude"),
            image: image
          });
        });
      } else {
        image = mainpoi.get("active") ?
          PoiTypeCollection.get(mainpoi.get('type')).get( 'mapImage' ) :
          PoiTypeCollection.get(mainpoi.get('type')).get( 'closedMapImage' );

        pois.push( {
          name: mainpoi.get("name"),
          link: ''+mainpoi.get('name')+'',
          lat: mainpoi.get("latitude"),
          lng: mainpoi.get("longitude"),
          image: image
        });
      }

      GMaps.drawPoints( pois, useBounds );
      return this;
    },

    mapSetZoom: function(level) {
      GMaps.setZoom(level);
      return this;
    },

    mapCenterPoint: function(mainpoi) {
      if( !mainpoi ) {
        return this;
      }
      GMaps.setCenter({
        lat: mainpoi.get("latitude"),
        lng: mainpoi.get("longitude"),
      });
      return this;
    },

    mapDrawDirections: function(directions, directionsType, mainpoi) {
      if( !directions || !mainpoi) {
        return this;
      }
      Locator.location(function(from, success){
        if(success) {
          var to = {
            lat: mainpoi.get("latitude"),
            lng: mainpoi.get("longitude"),
          };
          GMaps.drawDirections(from, to, directionsType);
        }
      });
      return this;
    },

    render: function() {
      var filteredPois = this.typeid === null ?
        this.collection :
        this.collection.filterByType( this.typeid );
      var html = this.template({pois: filteredPois.toJSON()});

      var parsehtml = Chrome.parseHTML(html);
      this.urlAlterHtml( parsehtml, filteredPois );
      Chrome.showPage( parsehtml );
    },

    /**
     * Function that makes addtional html alterations based on current url
     */
    urlAlterHtml: function( parsehtml, pois ) {
      // Url directions
      if( window.location.hash.substring(0, 20) == '#poi/info/directions' ) {

        // Add footer with various direction options
        var $footer = parsehtml.find( 'div[data-role="footer"]' );
        var directions_path = '#poi/info/directions' + '/' + this.poiid + '/';

        var driving_active = "";
        var transit_active = "";
        var bicycling_active = "";
        var walking_active = "";

        switch( this.directionsType ) {
          case "driving":
            driving_active = "ui-btn-active ui-state-persist";
            break;
          case "transit":
            transit_active = "ui-btn-active ui-state-persist";
            break;
          case "bicycling":
            bicycling_active = "ui-btn-active ui-state-persist";
            break;
          case "walking":
            walking_active = "ui-btn-active ui-state-persist";
            break;
        }

        $footer.append( $('
' +
          'Bil' +
          'Transit' +
          'Cykel' +
          'Gång' +
          '
') );

        // Link close button back to poi info page, instead of simple 'back'
        var $closeButton = parsehtml.find( '#closeButton' );
        $closeButton.removeAttr('data-direction');
        $closeButton.removeAttr('data-rel');
        $closeButton.prop('href', "#poi/info/" + this.poiid );
      }
    },

    findMeCenter: function() {
      Locator.location(function(myPos, success){
        if(success) {
          GMaps.setCenter(myPos, true);
        }
      });

      return false;
    }
  });

  return View;
});

//
<|endoftext|>


<commit_before>(function() {

    function createTable(columns, d3Selection, data) {
        var container = d3Selection
                .append("div")
                .classed("fixed-table-container", true)
                .classed("columns", true),
            background = container
                .append("div")
                .classed("header-background", true),
            table = container
                .append("div").classed("fixed-table-container-inner", true)
                .append("table"),

            thead = table.append("thead"),
            tbody = table.append("tbody");

        thead.append("tr");

        updateTable(table, columns, data);

        return container;
    }

    function sortActivities(activities, column, direction) {
        return activities.sort(function(a1, a2) {
            var sort = 0;
            if (a1[column] < a2[column]) {
                sort = -1;
            }
            if (a1[column] > a2[column]) {
                sort = 1;
            }
            return sort*direction;
        })
    }

    function filterActivities(activities, column, filter) {
        var re = stringToRegex(filter);

        return activities.filter(function(d) {
            return re.test(d[column]);
        });
    }

    function updateTable(table, columns, data) {
        var thead = table.select("thead"),
            tbody = table.select("tbody"),
            currentData = data;

        columns.forEach(function(column) {
            if (column.filter) {
                currentData = filterActivities(currentData, column.property, column.filter);
            }
        });

        columns.forEach(function(column) {
            if (column.sort) {
                currentData = sortActivities(currentData, column.property, column.sort);
            }
        });

        updateTableHeader(columns, thead);
        updateTableBody(columns, tbody, currentData);
    }

    function updateTableHeader(columns, thead) {
        var th = thead.select("tr")
            .selectAll("th")
            .data(columns),

            thEnter = th.enter()
                .append("th");

        thEnter.append("span")
            .classed("th-container", true)
            .text(function(column) { return column.text; });

        thEnter.append("div")
            .classed("th-inner", true)
            .text(function(column) { return column.text; });

        th.selectAll(".th-inner")
            .classed("sorted", function(d) {
                return d.sort;
            })
            .classed("desc", function(d) {
                return d.sort === DESC_DIRECTION;
            });
    }

    function updateTableBody(columns, tbody, data) {
        var rows = tbody.selectAll("tr")
            .data(data, function(d) {return d.endpoint});

        var cells = rows.enter()
            .append("tr")
            .selectAll("td")
            .data(function(row) {
                return columns.map(function (column) {
                    var renderer = column.renderer || defaultRenderer;

                    return {column: column, value: renderer(row[column.property])};
                })
            });

        cells.enter()
            .append("td")
            .html(function(d) {return d.value});

        rows.exit()
            .remove();

        rows.order();
    }

    function downloadFile(fileType, fileContent, fileName) {
        $("<a>")
            .attr("href", encodeURI(fileType + fileContent))
            .attr("download", fileName)
            .get(0)
            .click();
    }

    function createCSV(columns, data) {
        var csvRows = [columns.map(function(item) {
                return ['"',
                        item.text.replace('"', '""'),
                        '"'].join("");
            }).join(",")];

        csvRows = csvRows.concat(data.map(function(item) {
            return columns.map(function(column) {
                return item[column.property];
            }).join(",");
        }));

        return csvRows.join("\n");
    }

    function parseActivity(activity, index) {
        function isOutside(endpoint) {
            return activity.Endpoints.indexOf(endpoint) < 0;
        }

        function createEndpoint(endpoint) {
            return {
                activity: index + 1,
                endpoint: endpoint,
                internalConnections: 0,
                externalConnections: 0,
                totalConnections: 0,
                outsideConnections: 0,
                external: NCI.isExternal(endpoint)
            }
        }

        function getEndpoint(endpoint) {
            return endpoints[endpoint];
        }

        var endpoints = {};

        activity.Endpoints.forEach(function(endpoint) {
            endpoints[endpoint] = createEndpoint(endpoint);
        });

        activity.Interactions.forEach(
            function(interaction) {
                var endpointA = interaction[0],
                    endpointB = interaction[1];

                function updateInteractionConnections(epA, epB) {
                    var endpoint = getEndpoint(epA),
                        outside = isOutside(epB),
                        external = NCI.isExternal(epB);

                    if (endpoint) {
                        if (outside) {
                            endpoint.outsideConnections += 1;
                        }
                        endpoint[external ? "externalConnections" : "internalConnections"] += 1;
                        endpoint.totalConnections += 1;
                    }
                }

                updateInteractionConnections(endpointA, endpointB);
                updateInteractionConnections(endpointB, endpointA);
            }
        );

        return Object.keys(endpoints).map(function(endpoint) {return endpoints[endpoint]});
    }

    function parseActivities(activities) {
        return Array.prototype.concat.apply([], activities.map(parseActivity));
    }

    function getCommunitiesColumns(communities) {
        return communities.length > 1 ? createActivitiesColumns() : createActivityColumns();
    }

    function getActivityName(communities) {
        return communities.length > 1 ? "activities" : (communities[0].Label);
    }

    function stringToRegex(str) {
        // converts string with wildcards to regex
        // * - zero or more
        // ? - exact one

        str = str.replace(/\./g, "\\.");
        str = str.replace(/\?/g, ".");
        str = str.replace(/\*/g, ".*");

        return new RegExp(str, "g");
    }

    function defaultRenderer(value) {
        return value;
    }

    function createActivityColumns() {
        return [
            {text: "Endpoint", property: "endpoint", sort: null, filter: null},
            {text: "Internal", property: "internalConnections"},
            {text: "External", property: "externalConnections"},
            {text: "Total", property: "totalConnections", sort: DESC_DIRECTION, filter: null},
            {text: "Outside Connections", property: "outsideConnections", sort: null, filter: null},
//            {text: "External", property: "external", sort: null, filter: null}
        ];
    }

    function createActivitiesColumns() {
        return [
            {text: "Endpoint", property: "endpoint", sort: null, filter: null},
            {text: "Internal", property: "internalConnections"},
            {text: "External", property: "externalConnections"},
            {text: "Total", property: "totalConnections", sort: DESC_DIRECTION, filter: null},

//            {text: "External", property: "external", sort: null},
            {text: "Activity", property: "activity", sort: null,
                filter: null, renderer: function(value) {return "Activity #" + value}},
            {text: "Outside Connections", property: "outsideConnections", sort: null, filter: null}
        ]
    }

    function handleHeaderClick(listBuilder) {
        return function(data) {
            var $el = $(this),
                field = data.property,
                direction = $el.hasClass("desc") ? ASC_DIRECTION : DESC_DIRECTION;

            listBuilder.sortTable(field, direction);
        }
    }

    function ListBuilder(communities) {
        this.columns = getCommunitiesColumns(communities);
        this.activityName = getActivityName(communities);
        this.activities = sortActivities(parseActivities(communities));
        this.container = null;
    }

    var ASC_DIRECTION = 1,
        DESC_DIRECTION = -1,
        downloadCSV = downloadFile.bind(null, "data:text/csv;charset=utf-8,");

    ListBuilder.prototype.downloadCSV = function() {
        var columns = this.columns,
            csvName = this.activityName + ".csv",
            activities = this.activities,
            csvContent = createCSV(columns, activities);

        return downloadCSV(csvContent, csvName);
    };

    ListBuilder.prototype.createTable = function(d3Selection) {
        var columns = this.columns,
            activities = this.activities,
            container = createTable(columns, d3Selection, activities);

        container.selectAll(".th-inner").on("click", handleHeaderClick(this));

        this.container = container;

        return this.container;
    };

    ListBuilder.prototype.removeTable = function() {
        if (this.container) {
            this.container.on(".click");
            this.container.remove();
        }
        this.container = null;
    };

    ListBuilder.prototype.getTable = function() {
        return this.container.select("table");
    };

    ListBuilder.prototype.sortTable = function(field, direction) {
        var table = this.getTable();

        this.columns.forEach(function(column) {
            column.sort = null;
            if (column.property === field) {
                column.sort = direction;
            }
        });

        updateTable(table, this.columns, this.activities);
    };

    ListBuilder.prototype.filterTable = function(filterTerm) {
        var table = this.getTable();

        this.columns.forEach(function(column) {
            column.filter = null;
            if (column.property === "endpoint") {
                column.filter = filterTerm;
            }
        });

        updateTable(table, this.columns, this.activities);
    };

    NCI.list = {
        createListBuilder: function(communities) {
            return new ListBuilder(communities);
        }
    };

})();
<commit_msg>Changed order of Activities<commit_after>(function() {

    function createTable(columns, d3Selection, data) {
        var container = d3Selection
                .append("div")
                .classed("fixed-table-container", true)
                .classed("columns", true),
            background = container
                .append("div")
                .classed("header-background", true),
            table = container
                .append("div").classed("fixed-table-container-inner", true)
                .append("table"),

            thead = table.append("thead"),
            tbody = table.append("tbody");

        thead.append("tr");

        updateTable(table, columns, data);

        return container;
    }

    function sortActivities(activities, column, direction) {
        return activities.sort(function(a1, a2) {
            var sort = 0;
            if (a1[column] < a2[column]) {
                sort = -1;
            }
            if (a1[column] > a2[column]) {
                sort = 1;
            }
            return sort*direction;
        })
    }

    function filterActivities(activities, column, filter) {
        var re = stringToRegex(filter);

        return activities.filter(function(d) {
            return re.test(d[column]);
        });
    }

    function updateTable(table, columns, data) {
        var thead = table.select("thead"),
            tbody = table.select("tbody"),
            currentData = data;

        columns.forEach(function(column) {
            if (column.filter) {
                currentData = filterActivities(currentData, column.property, column.filter);
            }
        });

        columns.forEach(function(column) {
            if (column.sort) {
                currentData = sortActivities(currentData, column.property, column.sort);
            }
        });

        updateTableHeader(columns, thead);
        updateTableBody(columns, tbody, currentData);
    }

    function updateTableHeader(columns, thead) {
        var th = thead.select("tr")
            .selectAll("th")
            .data(columns),

            thEnter = th.enter()
                .append("th");

        thEnter.append("span")
            .classed("th-container", true)
            .text(function(column) { return column.text; });

        thEnter.append("div")
            .classed("th-inner", true)
            .text(function(column) { return column.text; });

        th.selectAll(".th-inner")
            .classed("sorted", function(d) {
                return d.sort;
            })
            .classed("desc", function(d) {
                return d.sort === DESC_DIRECTION;
            });
    }

    function updateTableBody(columns, tbody, data) {
        var rows = tbody.selectAll("tr")
            .data(data, function(d) {return d.endpoint});

        var cells = rows.enter()
            .append("tr")
            .selectAll("td")
            .data(function(row) {
                return columns.map(function (column) {
                    var renderer = column.renderer || defaultRenderer;

                    return {column: column, value: renderer(row[column.property])};
                })
            });

        cells.enter()
            .append("td")
            .html(function(d) {return d.value});

        rows.exit()
            .remove();

        rows.order();
    }

    function downloadFile(fileType, fileContent, fileName) {
        $("<a>")
            .attr("href", encodeURI(fileType + fileContent))
            .attr("download", fileName)
            .get(0)
            .click();
    }

    function createCSV(columns, data) {
        var csvRows = [columns.map(function(item) {
                return ['"',
                        item.text.replace('"', '""'),
                        '"'].join("");
            }).join(",")];

        csvRows = csvRows.concat(data.map(function(item) {
            return columns.map(function(column) {
                return item[column.property];
            }).join(",");
        }));

        return csvRows.join("\n");
    }

    function parseActivity(activity, index, activities) {
        function isOutside(endpoint) {
            return activity.Endpoints.indexOf(endpoint) < 0;
        }

        function createEndpoint(endpoint) {
            return {
                activity: activities.length - index,
                endpoint: endpoint,
                internalConnections: 0,
                externalConnections: 0,
                totalConnections: 0,
                outsideConnections: 0,
                external: NCI.isExternal(endpoint)
            }
        }

        function getEndpoint(endpoint) {
            return endpoints[endpoint];
        }

        var endpoints = {};

        activity.Endpoints.forEach(function(endpoint) {
            endpoints[endpoint] = createEndpoint(endpoint);
        });

        activity.Interactions.forEach(
            function(interaction) {
                var endpointA = interaction[0],
                    endpointB = interaction[1];

                function updateInteractionConnections(epA, epB) {
                    var endpoint = getEndpoint(epA),
                        outside = isOutside(epB),
                        external = NCI.isExternal(epB);

                    if (endpoint) {
                        if (outside) {
                            endpoint.outsideConnections += 1;
                        }
                        endpoint[external ? "externalConnections" : "internalConnections"] += 1;
                        endpoint.totalConnections += 1;
                    }
                }

                updateInteractionConnections(endpointA, endpointB);
                updateInteractionConnections(endpointB, endpointA);
            }
        );

        return Object.keys(endpoints).map(function(endpoint) {return endpoints[endpoint]});
    }

    function parseActivities(activities) {
        return Array.prototype.concat.apply([], activities.map(parseActivity));
    }

    function getCommunitiesColumns(communities) {
        return communities.length > 1 ? createActivitiesColumns() : createActivityColumns();
    }

    function getActivityName(communities) {
        return communities.length > 1 ? "activities" : (communities[0].Label);
    }

    function stringToRegex(str) {
        // converts string with wildcards to regex
        // * - zero or more
        // ? - exact one

        str = str.replace(/\./g, "\\.");
        str = str.replace(/\?/g, ".");
        str = str.replace(/\*/g, ".*");

        return new RegExp(str, "g");
    }

    function defaultRenderer(value) {
        return value;
    }

    function createActivityColumns() {
        return [
            {text: "Endpoint", property: "endpoint", sort: null, filter: null},
            {text: "Internal", property: "internalConnections"},
            {text: "External", property: "externalConnections"},
            {text: "Total", property: "totalConnections", sort: DESC_DIRECTION, filter: null},
            {text: "Outside Connections", property: "outsideConnections", sort: null, filter: null},
//            {text: "External", property: "external", sort: null, filter: null}
        ];
    }

    function createActivitiesColumns() {
        return [
            {text: "Endpoint", property: "endpoint", sort: null, filter: null},
            {text: "Internal", property: "internalConnections"},
            {text: "External", property: "externalConnections"},
            {text: "Total", property: "totalConnections", sort: DESC_DIRECTION, filter: null},

//            {text: "External", property: "external", sort: null},
            {text: "Activity", property: "activity", sort: null,
                filter: null, renderer: function(value) {return "Activity #" + value}},
            {text: "Outside Connections", property: "outsideConnections", sort: null, filter: null}
        ]
    }

    function handleHeaderClick(listBuilder) {
        return function(data) {
            var $el = $(this),
                field = data.property,
                direction = $el.hasClass("desc") ? ASC_DIRECTION : DESC_DIRECTION;

            listBuilder.sortTable(field, direction);
        }
    }

    function ListBuilder(communities) {
        this.columns = getCommunitiesColumns(communities);
        this.activityName = getActivityName(communities);
        this.activities = sortActivities(parseActivities(communities));
        this.container = null;
    }

    var ASC_DIRECTION = 1,
        DESC_DIRECTION = -1,
        downloadCSV = downloadFile.bind(null, "data:text/csv;charset=utf-8,");

    ListBuilder.prototype.downloadCSV = function() {
        var columns = this.columns,
            csvName = this.activityName + ".csv",
            activities = this.activities,
            csvContent = createCSV(columns, activities);

        return downloadCSV(csvContent, csvName);
    };

    ListBuilder.prototype.createTable = function(d3Selection) {
        var columns = this.columns,
            activities = this.activities,
            container = createTable(columns, d3Selection, activities);

        container.selectAll(".th-inner").on("click", handleHeaderClick(this));

        this.container = container;

        return this.container;
    };

    ListBuilder.prototype.removeTable = function() {
        if (this.container) {
            this.container.on(".click");
            this.container.remove();
        }
        this.container = null;
    };

    ListBuilder.prototype.getTable = function() {
        return this.container.select("table");
    };

    ListBuilder.prototype.sortTable = function(field, direction) {
        var table = this.getTable();

        this.columns.forEach(function(column) {
            column.sort = null;
            if (column.property === field) {
                column.sort = direction;
            }
        });

        updateTable(table, this.columns, this.activities);
    };

    ListBuilder.prototype.filterTable = function(filterTerm) {
        var table = this.getTable();

        this.columns.forEach(function(column) {
            column.filter = null;
            if (column.property === "endpoint") {
                column.filter = filterTerm;
            }
        });

        updateTable(table, this.columns, this.activities);
    };

    NCI.list = {
        createListBuilder: function(communities) {
            return new ListBuilder(communities);
        }
    };

})();
<|endoftext|>


<commit_before>require('dotenv').config();
const fs = require('file-system');

export const db = process.env.MONGOHQ_URL || process.env.MONGODB_URI || `mongodb://${process.env.DB_USER}:${process.env.DB_PASS}@www.moon.codes/ReactWebpackNode`;

const key = process.env.KEY ? fs.readFileSync(process.env.KEY) : '';
const ca = process.env.CA ? [fs.readFileSync(process.env.CA)] : '';
export const options = process.env.CA ?
  {
      ssl: true,
      sslValidate: true,
      sslCA: ca,
      sslKey: key,
      sslCert: key,
      socketOptions: { keepAlive: 1 }
  } :
  {};

export const serverOptions = process.env.CA ?
  {
    server: options
  } :
  {};

export default {
  db,
  options
};
<commit_msg>fixed db string<commit_after>require('dotenv').config();
const fs = require('file-system');

export const db = process.env.MONGOHQ_URL || process.env.MONGODB_URI || `mongodb://${process.env.DB_USER}:${process.env.DB_PASS}@localhost/ReactWebpackNode`;

const key = process.env.KEY ? fs.readFileSync(process.env.KEY) : '';
const ca = process.env.CA ? [fs.readFileSync(process.env.CA)] : '';
export const options = process.env.CA ?
  {
      ssl: true,
      sslValidate: true,
      sslCA: ca,
      sslKey: key,
      sslCert: key,
      socketOptions: { keepAlive: 1 }
  } :
  {};

export const serverOptions = process.env.CA ?
  {
    server: options
  } :
  {};

export default {
  db,
  options
};
<|endoftext|>