<commit_before>var http = require('http'),
	path = require('path'),
	fs = require('fs'),
	async = require('async'),
	Sandal = require('sandal').extend(require('sandal-autowire'));

module.exports = function(options, callback) {

	if (!callback) {
		callback = options;
		options = {};
	}

	if (!(options instanceof Array)) {
		return createSite(options, function (err, app) {
			if (err) return callback(err);
			callback(null, http.createServer(function (req, res) {
				app(req, res);
			}));
		});
	}

	var error = optionsArrayError(options);
	if (error) return callback(error);

	var startedSites = 0;
	var siteCount = options.length;
	var requestQueue = [];

	var apps = options.reduce(function (apps, options) {
		createSite(options, function (err, app) {
			if (err) {
				console.error(err);
				process.exit(-1);
			}
			options.hosts.forEach(function (host) {
				apps[host] = app;
			});
			startedSites++;
			if (startedSites === siteCount && requestQueue) {
				requestQueue.forEach(function (requestQueueItem) {
					requestQueueItem();
				});
				requestQueue = null;
			}
		});
		return apps;
	}, {});

	if (error) return callback(error);

	callback(null, http.createServer(function (req, res) {
		if (!req || !req.headers || !req.headers.host) {
			res.writeHead(400, {'Content-Type': 'text/plain'});
			res.end('No host header provided\n');
			return;
		}
		var requestQueueItem = function () {
			var app = apps[req.headers.host] || apps['*'];
			if (!app) {
				res.writeHead(404, {'Content-Type': 'text/plain'});
				res.end('Site with host ' + req.headers.host + ' is not available\n');
				return;
			}
			app(req, res);
		};
		if (!apps[req.headers.host] && !apps['*'] && requestQueue) requestQueue.push(requestQueueItem);
		else requestQueueItem();

	}));

};

function optionsArrayError(optionsArray) {
	var hosts = [],
		error = null;
	optionsArray.some(function (options) {
		if (!options.hosts || !(options.hosts instanceof Array) || options.hosts.length === 0) {
			error = new Error('All sites does not have host configured');
		} else {
			options.hosts.some(function (host) {
				if (hosts.indexOf(host) >= 0) {
					error = new Error('There are duplicates in the host configuration (' + host + ')');
					return true;
				}
				hosts.push(host);
			});
		}
		return !!error;
	});
	return error;
}

function createSite(options, callback) {

	setDefaults(options);

	var sandal = new Sandal(),
		siteSandal = new Sandal(),
		express = require('express'),
		swig,
		app = express();

	// Clear swig from require cache to enable multiple instances in same app
	Object.keys(require.cache).forEach(function (cacheKey) {
		if (cacheKey.split(path.sep).indexOf('swig') >= 0) delete require.cache[cacheKey];
	});

	swig = require('swig');
	registerSiteDependencies(siteSandal, options, express, swig, app);
	registerInternalDependencies(sandal, siteSandal, options, express, swig, app);
	siteSandal.resolve('init', function (err, siteInit) {
		if (err) return callback(err);
		async.series(toSortedList(siteInit), function (err) {
			if (err) return callback(err);
			sandal.resolve(['init', 'app'], function (err, fwInit, app) {
				if (err) return callback(err);
				async.series(toSortedList(fwInit), function (err) {
					if (err) return callback(err);
					callback(null, app);
				});
			});
		});
	});
}

function setDefaults(options) {
	options.version = options.version || require(path.join(process.cwd(), 'package.json')).version;
	options.dictionaries = options.dictionaries || [];
	options.staticRoot = options.staticRoot || '/public';
	options.lessPath = toAbsolutePath(options.lessPath || './style');
	options.staticPath = toAbsolutePath(options.staticPath || './public');
	options.scriptPath = toAbsolutePath(options.scriptPath || './script');
	options.libPath = toAbsolutePath(options.libPath || './lib');
	options.initPath = toAbsolutePath(options.initPath || './init');
	options.widgetPath = toAbsolutePath(options.widgetPath || './widgets');
	options.routePath = toAbsolutePath(options.routePath || './routes');
	options.routeMap = options.routeMap || function (model, options, callback) {
		callback(null, model, options);
	};
	options.widgetMap = options.widgetMap || function (model, options, callback) {
		callback(null, model, options);
	};
}

function toAbsolutePath(input) {
	if (input.indexOf('./') === 0 || input.indexOf('../') === 0) return path.join(process.cwd(), input).replace(/\/$/, '');
	return input.replace(/\/$/, '');
}

function registerSiteDependencies(siteSandal, options, express, swig, app) {
	siteSandal
		.object('express', express)
		.object('swig', swig)
		.object('app', app);
	if (options.dependencies) {
		for (var name in options.dependencies) {
			siteSandal.object(name, options.dependencies[name]);
		}
	}
	if (fs.existsSync(options.initPath)) {
		siteSandal.autowire(options.initPath, { groups: ['init'] });
	}
	if (fs.existsSync(options.libPath)) {
		siteSandal.autowire(options.libPath);
	}
	if (!siteSandal.has('init')) siteSandal.object('init', {});
}

function registerInternalDependencies(sandal, siteSandal, options, express, swig, app) {
	sandal
		.object('siteSandal', siteSandal)
		.object('options', options)
		.object('express', express)
		.object('swig', swig)
		.object('app', app)
		.autowire(path.join(__dirname, '/init'), { groups: ['init'] })
		.autowire(path.join(__dirname, '/lib'));
}

function toSortedList(init) {
	return Object.keys(init).sort().map(function (key) {
		return function (done) {
			init[key](done);
		};
	});
}
<commit_msg>Errors in createSite will now print stack trace<commit_after>var http = require('http'),
	path = require('path'),
	fs = require('fs'),
	async = require('async'),
	Sandal = require('sandal').extend(require('sandal-autowire'));

module.exports = function(options, callback) {

	if (!callback) {
		callback = options;
		options = {};
	}

	if (!(options instanceof Array)) {
		return createSite(options, function (err, app) {
			if (err) return callback(err);
			callback(null, http.createServer(function (req, res) {
				app(req, res);
			}));
		});
	}

	var error = optionsArrayError(options);
	if (error) return callback(error);

	var startedSites = 0;
	var siteCount = options.length;
	var requestQueue = [];

	var apps = options.reduce(function (apps, options) {
		createSite(options, function (err, app) {
			if (err) {
				console.error(err.stack);
				process.exit(-1);
			}
			options.hosts.forEach(function (host) {
				apps[host] = app;
			});
			startedSites++;
			if (startedSites === siteCount && requestQueue) {
				requestQueue.forEach(function (requestQueueItem) {
					requestQueueItem();
				});
				requestQueue = null;
			}
		});
		return apps;
	}, {});

	if (error) return callback(error);

	callback(null, http.createServer(function (req, res) {
		if (!req || !req.headers || !req.headers.host) {
			res.writeHead(400, {'Content-Type': 'text/plain'});
			res.end('No host header provided\n');
			return;
		}
		var requestQueueItem = function () {
			var app = apps[req.headers.host] || apps['*'];
			if (!app) {
				res.writeHead(404, {'Content-Type': 'text/plain'});
				res.end('Site with host ' + req.headers.host + ' is not available\n');
				return;
			}
			app(req, res);
		};
		if (!apps[req.headers.host] && !apps['*'] && requestQueue) requestQueue.push(requestQueueItem);
		else requestQueueItem();

	}));

};

function optionsArrayError(optionsArray) {
	var hosts = [],
		error = null;
	optionsArray.some(function (options) {
		if (!options.hosts || !(options.hosts instanceof Array) || options.hosts.length === 0) {
			error = new Error('All sites does not have host configured');
		} else {
			options.hosts.some(function (host) {
				if (hosts.indexOf(host) >= 0) {
					error = new Error('There are duplicates in the host configuration (' + host + ')');
					return true;
				}
				hosts.push(host);
			});
		}
		return !!error;
	});
	return error;
}

function createSite(options, callback) {

	setDefaults(options);

	var sandal = new Sandal(),
		siteSandal = new Sandal(),
		express = require('express'),
		swig,
		app = express();

	// Clear swig from require cache to enable multiple instances in same app
	Object.keys(require.cache).forEach(function (cacheKey) {
		if (cacheKey.split(path.sep).indexOf('swig') >= 0) delete require.cache[cacheKey];
	});

	swig = require('swig');
	registerSiteDependencies(siteSandal, options, express, swig, app);
	registerInternalDependencies(sandal, siteSandal, options, express, swig, app);
	siteSandal.resolve('init', function (err, siteInit) {
		if (err) return callback(err);
		async.series(toSortedList(siteInit), function (err) {
			if (err) return callback(err);
			sandal.resolve(['init', 'app'], function (err, fwInit, app) {
				if (err) return callback(err);
				async.series(toSortedList(fwInit), function (err) {
					if (err) return callback(err);
					callback(null, app);
				});
			});
		});
	});
}

function setDefaults(options) {
	options.version = options.version || require(path.join(process.cwd(), 'package.json')).version;
	options.dictionaries = options.dictionaries || [];
	options.staticRoot = options.staticRoot || '/public';
	options.lessPath = toAbsolutePath(options.lessPath || './style');
	options.staticPath = toAbsolutePath(options.staticPath || './public');
	options.scriptPath = toAbsolutePath(options.scriptPath || './script');
	options.libPath = toAbsolutePath(options.libPath || './lib');
	options.initPath = toAbsolutePath(options.initPath || './init');
	options.widgetPath = toAbsolutePath(options.widgetPath || './widgets');
	options.routePath = toAbsolutePath(options.routePath || './routes');
	options.routeMap = options.routeMap || function (model, options, callback) {
		callback(null, model, options);
	};
	options.widgetMap = options.widgetMap || function (model, options, callback) {
		callback(null, model, options);
	};
}

function toAbsolutePath(input) {
	if (input.indexOf('./') === 0 || input.indexOf('../') === 0) return path.join(process.cwd(), input).replace(/\/$/, '');
	return input.replace(/\/$/, '');
}

function registerSiteDependencies(siteSandal, options, express, swig, app) {
	siteSandal
		.object('express', express)
		.object('swig', swig)
		.object('app', app);
	if (options.dependencies) {
		for (var name in options.dependencies) {
			siteSandal.object(name, options.dependencies[name]);
		}
	}
	if (fs.existsSync(options.initPath)) {
		siteSandal.autowire(options.initPath, { groups: ['init'] });
	}
	if (fs.existsSync(options.libPath)) {
		siteSandal.autowire(options.libPath);
	}
	if (!siteSandal.has('init')) siteSandal.object('init', {});
}

function registerInternalDependencies(sandal, siteSandal, options, express, swig, app) {
	sandal
		.object('siteSandal', siteSandal)
		.object('options', options)
		.object('express', express)
		.object('swig', swig)
		.object('app', app)
		.autowire(path.join(__dirname, '/init'), { groups: ['init'] })
		.autowire(path.join(__dirname, '/lib'));
}

function toSortedList(init) {
	return Object.keys(init).sort().map(function (key) {
		return function (done) {
			init[key](done);
		};
	});
}
<|endoftext|>


<commit_before>//= require "jquery"
//= require "jquery.flot"
//= require "jquery.flot.time"
//= require "jquery.isotope"
//= require "jquery.pin"
//= require "share"
//= require_self

$(function() {
  var share = new Share("#share-button-top", {
    networks: {
      facebook: {
        app_id: "1604147083144211",
      }
    }
  });

  $(".navbar").pin()

  var sortAscending = {title: true};

  $(".projects").isotope({
    layoutMode: "fitRows",
    getSortData: {
      stars: "[data-stars] parseInt",
      forks: "[data-forks] parseInt",
      issues: "[data-issues] parseInt",
      language: "[data-language]",
      title: "[data-title]"
    }
  });

  $("select[name='filter']").change(function(e) {
    console.log("Filter by: %o", $(this).val());
    $(".projects").isotope({filter: $(this).val().replace(/^.lang-./, '.lang-')});
  });

  $("select[name='sort']").change(function(e) {
    var val = $(this).val();
    $(".projects").isotope({sortBy: val, sortAscending: sortAscending[val] || false});
  });
});
<commit_msg>fix broken language filtering<commit_after>//= require "jquery"
//= require "jquery.flot"
//= require "jquery.flot.time"
//= require "jquery.isotope"
//= require "jquery.pin"
//= require "share"
//= require_self

$(function() {
  var share = new Share("#share-button-top", {
    networks: {
      facebook: {
        app_id: "1604147083144211",
      }
    }
  });

  $(".navbar").pin()

  var sortAscending = {title: true};

  $(".projects").isotope({
    layoutMode: "fitRows",
    getSortData: {
      stars: "[data-stars] parseInt",
      forks: "[data-forks] parseInt",
      issues: "[data-issues] parseInt",
      language: "[data-language]",
      title: "[data-title]"
    }
  });

  $("select[name='filter']").change(function(e) {
    console.log("Filter by: %o", $(this).val());
    $(".projects").isotope({filter: $(this).val().replace(/^\.lang-\./, '.lang-')});
  });

  $("select[name='sort']").change(function(e) {
    var val = $(this).val();
    $(".projects").isotope({sortBy: val, sortAscending: sortAscending[val] || false});
  });
});
<|endoftext|>


<commit_before>;(function($$){

	var CanvasRenderer = $$('renderer', 'canvas');

	CanvasRenderer.prototype.getPixelRatio = function(){
		var canvas = this.data.canvases[0];
		var context = canvas.getContext("2d");

		var backingStore = context.backingStorePixelRatio ||
			context.webkitBackingStorePixelRatio ||
			context.mozBackingStorePixelRatio ||
			context.msBackingStorePixelRatio ||
			context.oBackingStorePixelRatio ||
			context.backingStorePixelRatio || 1;

		//console.log(window.devicePixelRatio, backingStore);

		var isFirefox = typeof InstallTrigger !== 'undefined';

		if( isFirefox ){ // because ff can't scale canvas properly
			return 1;
		}

		return (window.devicePixelRatio || 1) / backingStore;
	}

	// Resize canvas
	CanvasRenderer.prototype.matchCanvasSize = function(container) {
		var data = this.data; var width = container.clientWidth; var height = container.clientHeight;

		var canvas, canvasWidth = width, canvasHeight = height;
		var pixelRatio = this.getPixelRatio();

		// apply pixel ratio
		canvasWidth *= pixelRatio;
		canvasHeight *= pixelRatio;

		var canvasContainer = data.canvasContainer;
		canvasContainer.style.width = width + 'px';
		canvasContainer.style.height = height + 'px';

		for (var i = 0; i < CanvasRenderer.CANVAS_LAYERS; i++) {

			canvas = data.canvases[i];

			if (canvas.width !== canvasWidth || canvas.height !== canvasHeight) {

				canvas.width = canvasWidth;
				canvas.height = canvasHeight;

				canvas.style.width = width + 'px';
				canvas.style.height = height + 'px';
			}
		}

		for (var i = 0; i < CanvasRenderer.BUFFER_COUNT; i++) {

			canvas = data.bufferCanvases[i];

			if (canvas.width !== canvasWidth || canvas.height !== canvasHeight) {

				canvas.width = canvasWidth;
				canvas.height = canvasHeight;
			}
		}

	}

	CanvasRenderer.prototype.renderTo = function( cxt, zoom, pan ){
		this.redraw({
			forcedContext: cxt,
			forcedZoom: zoom,
			forcedPan: pan,
			drawAllLayers: true
		});
	};

	// Redraw frame
	CanvasRenderer.prototype.redraw = function( options ) {
		options = options || {};

		var forcedContext = options.forcedContext;
		var drawAllLayers = options.drawAllLayers;
		var forcedZoom = options.forcedZoom;
		var forcedPan = options.forcedPan;
		var r = this;
		var pixelRatio = this.getPixelRatio();
		var cy = r.data.cy; var data = r.data;

		clearTimeout( this.redrawTimeout );

		if( this.averageRedrawTime === undefined ){ this.averageRedrawTime = 0; }

		var minRedrawLimit = 1000/60; // people can't see much better than 60fps
		var maxRedrawLimit = 1000; // don't cap max b/c it's more important to be responsive than smooth

		var redrawLimit = this.averageRedrawTime; // estimate the ideal redraw limit based on how fast we can draw
		redrawLimit = Math.max(minRedrawLimit, redrawLimit);
		redrawLimit = Math.min(redrawLimit, maxRedrawLimit);

		//console.log('--\nideal: %i; effective: %i', this.averageRedrawTime, redrawLimit);

		if( this.lastDrawTime === undefined ){ this.lastDrawTime = 0; }

		var nowTime = +new Date;
		var timeElapsed = nowTime - this.lastDrawTime;
		var callAfterLimit = timeElapsed >= redrawLimit;

		if( !forcedContext ){
			if( !callAfterLimit ){
				clearTimeout( this.redrawTimeout );
				this.redrawTimeout = setTimeout(function(){
					r.redraw();
				}, redrawLimit);
				return;
			}

			this.lastDrawTime = nowTime;
		}

		var startTime = nowTime;

		var looperMax = 100;
		//console.log('-- redraw --')

		// console.time('init'); for( var looper = 0; looper <= looperMax; looper++ ){

		// } console.timeEnd('init')

		function drawToContext(){
			var nodes = r.getCachedNodes(); var edges = r.getCachedEdges();

			if( !forcedContext ){
				r.matchCanvasSize(data.container);
			}

			var zoom = cy.zoom();
			var effectiveZoom = forcedZoom !== undefined ? forcedZoom : zoom;
			var pan = cy.pan();
			var effectivePan = {
				x: pan.x,
				y: pan.y
			};

			if( forcedPan ){
				effectivePan = forcedPan;
			}

			// apply pixel ratio
			effectiveZoom *= pixelRatio;
			effectivePan.x *= pixelRatio;
			effectivePan.y *= pixelRatio;

			var elements;
			var elesInDragLayer;
			var elesNotInDragLayer;
			var element;

			function setContextTransform(context){
				context.setTransform(1, 0, 0, 1, 0, 0);
				!forcedContext && context.clearRect(0, 0, context.canvas.width, context.canvas.height);

				if( !drawAllLayers ){
					context.translate(effectivePan.x, effectivePan.y);
					context.scale(effectiveZoom, effectiveZoom);
				}
				if( forcedPan ){
					context.translate(forcedPan.x, forcedPan.y);
				}
				if( forcedZoom ){
					context.scale(forcedZoom, forcedZoom);
				}
			}

			if (data.canvasNeedsRedraw[CanvasRenderer.DRAG] || data.canvasNeedsRedraw[CanvasRenderer.NODE] || drawAllLayers) {
				//NB : VERY EXPENSIVE
				//console.time('edgectlpts'); for( var looper = 0; looper <= looperMax; looper++ ){

				if( r.hideEdgesOnViewport && (r.pinching || r.hoverData.dragging || r.data.wheel || r.swipePanning) ){
				} else {
					r.findEdgeControlPoints(edges);
				}

				//} console.timeEnd('edgectlpts')

				// console.time('sort'); for( var looper = 0; looper <= looperMax; looper++ ){
				elements = r.getCachedZSortedEles();
				// } console.timeEnd('sort')

				elesInDragLayer = [];
				elesNotInDragLayer = [];

				for (var index = 0; index < elements.length; index++) {
					element = elements[index];

					if ( element._private.rscratch.inDragLayer ) {
						elesInDragLayer.push( element );
					} else {
						elesNotInDragLayer.push( element );
					}
				}

				// console.time('updatecompounds'); for( var looper = 0; looper <= looperMax; looper++ ){
				// no need to update graph if there is no compound node
				if ( cy.hasCompoundNodes() )
				{
					r.updateAllCompounds(elements);
				}
				// } console.timeEnd('updatecompounds')
			}

			function drawElements( eleList, context ){
				var edges = [];

				for (var i = 0; i < eleList.length; i++) {
					element = eleList[i];

					if ( element.isNode() ) {
						r.drawNode(context, element);
						r.drawNodeText(context, element);
						r.drawNode(context, element, true);

					} else if ( element.isEdge() ) {
						r.drawEdge(context, element);
						edges.push( element );
					}
				}

				for (var i = 0; i < edges.length; i++) {
					element = edges[i];

					r.drawEdgeText(context, element);
					r.drawEdge(context, element, true);
				}
			}

			// console.time('drawing'); for( var looper = 0; looper <= looperMax; looper++ ){
			if (data.canvasNeedsRedraw[CanvasRenderer.NODE] || drawAllLayers) {
				// console.log("redrawing node layer");

				var context = forcedContext || data.canvases[CanvasRenderer.NODE].getContext("2d");

				setContextTransform( context );
				drawElements(elesNotInDragLayer, context);

				if( !drawAllLayers ){
					data.canvasNeedsRedraw[CanvasRenderer.NODE] = false;
				}
			}

			if (data.canvasNeedsRedraw[CanvasRenderer.DRAG] || drawAllLayers) {

				var context = forcedContext || data.canvases[CanvasRenderer.DRAG].getContext("2d");

				setContextTransform( context );
				drawElements(elesInDragLayer, context);

				if( !drawAllLayers ){
					data.canvasNeedsRedraw[CanvasRenderer.DRAG] = false;
				}
			}

			if (data.canvasNeedsRedraw[CanvasRenderer.SELECT_BOX] && !drawAllLayers) {
				// console.log("redrawing selection box");

				var context = forcedContext || data.canvases[CanvasRenderer.SELECT_BOX].getContext("2d");

				setContextTransform( context );

				var coreStyle = cy.style()._private.coreStyle;

				if (data.select[4] == 1) {
					var zoom = data.cy.zoom();
					var borderWidth = coreStyle["selection-box-border-width"].value / zoom;

					context.lineWidth = borderWidth;
					context.fillStyle = "rgba("
						+ coreStyle["selection-box-color"].value[0] + ","
						+ coreStyle["selection-box-color"].value[1] + ","
						+ coreStyle["selection-box-color"].value[2] + ","
						+ coreStyle["selection-box-opacity"].value + ")";

					context.fillRect(
						data.select[0],
						data.select[1],
						data.select[2] - data.select[0],
						data.select[3] - data.select[1]);

					if (borderWidth > 0) {
						context.strokeStyle = "rgba("
							+ coreStyle["selection-box-border-color"].value[0] + ","
							+ coreStyle["selection-box-border-color"].value[1] + ","
							+ coreStyle["selection-box-border-color"].value[2] + ","
							+ coreStyle["selection-box-opacity"].value + ")";

						context.strokeRect(
							data.select[0],
							data.select[1],
							data.select[2] - data.select[0],
							data.select[3] - data.select[1]);
					}
				}

				if( data.bgActivePosistion ){
					var zoom = data.cy.zoom();
					var pos = data.bgActivePosistion;

					context.fillStyle = "rgba("
						+ coreStyle["active-bg-color"].value[0] + ","
						+ coreStyle["active-bg-color"].value[1] + ","
						+ coreStyle["active-bg-color"].value[2] + ","
						+ coreStyle["active-bg-opacity"].value + ")";

					context.beginPath();
					context.arc(pos.x, pos.y, coreStyle["active-bg-size"].pxValue / zoom, 0, 2 * Math.PI);
					context.fill();
				}

				if( !drawAllLayers ){
					data.canvasNeedsRedraw[CanvasRenderer.SELECT_BOX] = false;
				}
			}

			// } console.timeEnd('drawing')

			var endTime = +new Date;

			if( r.averageRedrawTime === undefined ){
				r.averageRedrawTime = endTime - startTime;
			}

			// use a weighted average with a bias from the previous average so we don't spike so easily
			r.averageRedrawTime = r.averageRedrawTime/2 + (endTime - startTime)/2;
			//console.log('actual: %i, average: %i', endTime - startTime, this.averageRedrawTime);
		}

		if( !forcedContext ){
			setTimeout(drawToContext, 0); // makes direct renders to screen a bit more responsive
		} else {
			drawToContext();
		}

		if( !forcedContext && !r.initrender ){
			r.initrender = true;
			cy.trigger('initrender');
		}

	};

})( cytoscape );
<commit_msg>fix #417<commit_after>;(function($$){

	var CanvasRenderer = $$('renderer', 'canvas');

	CanvasRenderer.prototype.getPixelRatio = function(){
		var canvas = this.data.canvases[0];
		var context = canvas.getContext("2d");

		var backingStore = context.backingStorePixelRatio ||
			context.webkitBackingStorePixelRatio ||
			context.mozBackingStorePixelRatio ||
			context.msBackingStorePixelRatio ||
			context.oBackingStorePixelRatio ||
			context.backingStorePixelRatio || 1;

		//console.log(window.devicePixelRatio, backingStore);

		var isFirefox = typeof InstallTrigger !== 'undefined';

		if( isFirefox ){ // because ff can't scale canvas properly
			return 1;
		}

		return (window.devicePixelRatio || 1) / backingStore;
	}

	// Resize canvas
	CanvasRenderer.prototype.matchCanvasSize = function(container) {
		var data = this.data; var width = container.clientWidth; var height = container.clientHeight;

		var canvas, canvasWidth = width, canvasHeight = height;
		var pixelRatio = this.getPixelRatio();

		// apply pixel ratio
		canvasWidth *= pixelRatio;
		canvasHeight *= pixelRatio;

		var canvasContainer = data.canvasContainer;
		canvasContainer.style.width = width + 'px';
		canvasContainer.style.height = height + 'px';

		for (var i = 0; i < CanvasRenderer.CANVAS_LAYERS; i++) {

			canvas = data.canvases[i];

			if (canvas.width !== canvasWidth || canvas.height !== canvasHeight) {

				canvas.width = canvasWidth;
				canvas.height = canvasHeight;

				canvas.style.width = width + 'px';
				canvas.style.height = height + 'px';
			}
		}

		for (var i = 0; i < CanvasRenderer.BUFFER_COUNT; i++) {

			canvas = data.bufferCanvases[i];

			if (canvas.width !== canvasWidth || canvas.height !== canvasHeight) {

				canvas.width = canvasWidth;
				canvas.height = canvasHeight;
			}
		}

	}

	CanvasRenderer.prototype.renderTo = function( cxt, zoom, pan ){
		this.redraw({
			forcedContext: cxt,
			forcedZoom: zoom,
			forcedPan: pan,
			drawAllLayers: true
		});
	};

	// Redraw frame
	CanvasRenderer.prototype.redraw = function( options ) {
		options = options || {};

		var forcedContext = options.forcedContext;
		var drawAllLayers = options.drawAllLayers;
		var forcedZoom = options.forcedZoom;
		var forcedPan = options.forcedPan;
		var r = this;
		var pixelRatio = this.getPixelRatio();
		var cy = r.data.cy; var data = r.data;

		clearTimeout( this.redrawTimeout );

		if( this.averageRedrawTime === undefined ){ this.averageRedrawTime = 0; }

		var minRedrawLimit = 1000/60; // people can't see much better than 60fps
		var maxRedrawLimit = 1000; // don't cap max b/c it's more important to be responsive than smooth

		var redrawLimit = this.averageRedrawTime; // estimate the ideal redraw limit based on how fast we can draw
		redrawLimit = Math.max(minRedrawLimit, redrawLimit);
		redrawLimit = Math.min(redrawLimit, maxRedrawLimit);

		//console.log('--\nideal: %i; effective: %i', this.averageRedrawTime, redrawLimit);

		if( this.lastDrawTime === undefined ){ this.lastDrawTime = 0; }

		var nowTime = +new Date;
		var timeElapsed = nowTime - this.lastDrawTime;
		var callAfterLimit = timeElapsed >= redrawLimit;

		if( !forcedContext ){
			if( !callAfterLimit ){
				clearTimeout( this.redrawTimeout );
				this.redrawTimeout = setTimeout(function(){
					r.redraw();
				}, redrawLimit);
				return;
			}

			this.lastDrawTime = nowTime;
		}

		var startTime = nowTime;

		var looperMax = 100;
		//console.log('-- redraw --')

		// console.time('init'); for( var looper = 0; looper <= looperMax; looper++ ){

		// } console.timeEnd('init')

		function drawToContext(){
			var nodes = r.getCachedNodes(); var edges = r.getCachedEdges();

			if( !forcedContext ){
				r.matchCanvasSize(data.container);
			}

			var zoom = cy.zoom();
			var effectiveZoom = forcedZoom !== undefined ? forcedZoom : zoom;
			var pan = cy.pan();
			var effectivePan = {
				x: pan.x,
				y: pan.y
			};

			if( forcedPan ){
				effectivePan = forcedPan;
			}

			// apply pixel ratio
			effectiveZoom *= pixelRatio;
			effectivePan.x *= pixelRatio;
			effectivePan.y *= pixelRatio;

			var elements;
			var elesInDragLayer;
			var elesNotInDragLayer;
			var element;

			function setContextTransform(context){
				context.setTransform(1, 0, 0, 1, 0, 0);
				!forcedContext && context.clearRect(0, 0, context.canvas.width, context.canvas.height);

				if( !drawAllLayers ){
					context.translate(effectivePan.x, effectivePan.y);
					context.scale(effectiveZoom, effectiveZoom);
				}
				if( forcedPan ){
					context.translate(forcedPan.x, forcedPan.y);
				}
				if( forcedZoom ){
					context.scale(forcedZoom, forcedZoom);
				}
			}

			if (data.canvasNeedsRedraw[CanvasRenderer.DRAG] || data.canvasNeedsRedraw[CanvasRenderer.NODE] || drawAllLayers) {
				//NB : VERY EXPENSIVE
				//console.time('edgectlpts'); for( var looper = 0; looper <= looperMax; looper++ ){

				if( r.hideEdgesOnViewport && (r.pinching || r.hoverData.dragging || r.data.wheel || r.swipePanning) ){
				} else {
					r.findEdgeControlPoints(edges);
				}

				//} console.timeEnd('edgectlpts')

				// console.time('sort'); for( var looper = 0; looper <= looperMax; looper++ ){
				elements = r.getCachedZSortedEles();
				// } console.timeEnd('sort')

				elesInDragLayer = [];
				elesNotInDragLayer = [];

				for (var index = 0; index < elements.length; index++) {
					element = elements[index];

					if ( element._private.rscratch.inDragLayer ) {
						elesInDragLayer.push( element );
					} else {
						elesNotInDragLayer.push( element );
					}
				}

				// console.time('updatecompounds'); for( var looper = 0; looper <= looperMax; looper++ ){
				// no need to update graph if there is no compound node
				if ( cy.hasCompoundNodes() )
				{
					r.updateAllCompounds(elements);
				}
				// } console.timeEnd('updatecompounds')
			}

			function drawElements( eleList, context ){
				var edges = [];
				var nodes = [];

				for (var i = 0; i < eleList.length; i++) {
					ele = eleList[i];

					if ( ele.isNode() ) {
						nodes.push( ele );

					} else if ( ele.isEdge() ) {
						r.drawEdge(context, ele);
						edges.push( ele );
					}
				}

				for (var i = 0; i < edges.length; i++) {
					ele = edges[i];

					r.drawEdgeText(context, ele);
					r.drawEdge(context, ele, true);
				}

				for( var i = 0; i < nodes.length; i++ ){
					var ele = nodes[i];

					r.drawNode(context, ele);
					r.drawNodeText(context, ele);
					r.drawNode(context, ele, true);
				}
			}

			// console.time('drawing'); for( var looper = 0; looper <= looperMax; looper++ ){
			if (data.canvasNeedsRedraw[CanvasRenderer.NODE] || drawAllLayers) {
				// console.log("redrawing node layer");

				var context = forcedContext || data.canvases[CanvasRenderer.NODE].getContext("2d");

				setContextTransform( context );
				drawElements(elesNotInDragLayer, context);

				if( !drawAllLayers ){
					data.canvasNeedsRedraw[CanvasRenderer.NODE] = false;
				}
			}

			if (data.canvasNeedsRedraw[CanvasRenderer.DRAG] || drawAllLayers) {

				var context = forcedContext || data.canvases[CanvasRenderer.DRAG].getContext("2d");

				setContextTransform( context );
				drawElements(elesInDragLayer, context);

				if( !drawAllLayers ){
					data.canvasNeedsRedraw[CanvasRenderer.DRAG] = false;
				}
			}

			if (data.canvasNeedsRedraw[CanvasRenderer.SELECT_BOX] && !drawAllLayers) {
				// console.log("redrawing selection box");

				var context = forcedContext || data.canvases[CanvasRenderer.SELECT_BOX].getContext("2d");

				setContextTransform( context );

				var coreStyle = cy.style()._private.coreStyle;

				if (data.select[4] == 1) {
					var zoom = data.cy.zoom();
					var borderWidth = coreStyle["selection-box-border-width"].value / zoom;

					context.lineWidth = borderWidth;
					context.fillStyle = "rgba("
						+ coreStyle["selection-box-color"].value[0] + ","
						+ coreStyle["selection-box-color"].value[1] + ","
						+ coreStyle["selection-box-color"].value[2] + ","
						+ coreStyle["selection-box-opacity"].value + ")";

					context.fillRect(
						data.select[0],
						data.select[1],
						data.select[2] - data.select[0],
						data.select[3] - data.select[1]);

					if (borderWidth > 0) {
						context.strokeStyle = "rgba("
							+ coreStyle["selection-box-border-color"].value[0] + ","
							+ coreStyle["selection-box-border-color"].value[1] + ","
							+ coreStyle["selection-box-border-color"].value[2] + ","
							+ coreStyle["selection-box-opacity"].value + ")";

						context.strokeRect(
							data.select[0],
							data.select[1],
							data.select[2] - data.select[0],
							data.select[3] - data.select[1]);
					}
				}

				if( data.bgActivePosistion ){
					var zoom = data.cy.zoom();
					var pos = data.bgActivePosistion;

					context.fillStyle = "rgba("
						+ coreStyle["active-bg-color"].value[0] + ","
						+ coreStyle["active-bg-color"].value[1] + ","
						+ coreStyle["active-bg-color"].value[2] + ","
						+ coreStyle["active-bg-opacity"].value + ")";

					context.beginPath();
					context.arc(pos.x, pos.y, coreStyle["active-bg-size"].pxValue / zoom, 0, 2 * Math.PI);
					context.fill();
				}

				if( !drawAllLayers ){
					data.canvasNeedsRedraw[CanvasRenderer.SELECT_BOX] = false;
				}
			}

			// } console.timeEnd('drawing')

			var endTime = +new Date;

			if( r.averageRedrawTime === undefined ){
				r.averageRedrawTime = endTime - startTime;
			}

			// use a weighted average with a bias from the previous average so we don't spike so easily
			r.averageRedrawTime = r.averageRedrawTime/2 + (endTime - startTime)/2;
			//console.log('actual: %i, average: %i', endTime - startTime, this.averageRedrawTime);
		}

		if( !forcedContext ){
			setTimeout(drawToContext, 0); // makes direct renders to screen a bit more responsive
		} else {
			drawToContext();
		}

		if( !forcedContext && !r.initrender ){
			r.initrender = true;
			cy.trigger('initrender');
		}

	};

})( cytoscape );
<|endoftext|>


<commit_before>/*
TODO
- Check whether files exist before uploading (will always overwrite as-is)
- Support multiple retry attempts if a file exists (see FS Adapter)
*/

// Mirroring keystone 0.4's support of node 0.12.
var assign = require('object-assign');
var debug = require('debug')('keystone-s3');
var ensureCallback = require('keystone-storage-namefunctions/ensureCallback');
var fs = require('fs');
var S3 = require('aws-sdk/clients/s3');
var nameFunctions = require('keystone-storage-namefunctions');
var pathlib = require('path');

var DEFAULT_OPTIONS = {
	Bucket: process.env.S3_BUCKET,
	generateFilename: nameFunctions.randomFilename,
};

var s3 = new S3({
	accessKeyId: process.env.S3_KEY,
	secretAccessKey: process.env.S3_SECRET,
	region: process.env.S3_REGION || 'us-east-1',
});

// This constructor is usually called indirectly by the Storage class
// in keystone.

// S3-specific options should be specified in an `options.s3` field,
// which can contain the following options: { key, secret, bucket, region,
// headers, path }.

// The schema can contain the additional fields { path, bucket, etag }.

// See README.md for details and usage examples.

function S3Adapter (options, schema) {
	this.options = assign({}, DEFAULT_OPTIONS, options.s3);

	// Support `defaultHeaders` option alias for `headers`
	// TODO: Remove me with the next major version bump
	if (this.options.defaultHeaders) {
		this.options.headers = this.options.defaultHeaders;
	}

	// If path is specified it must be absolute.
	if (options.path != null && !pathlib.isAbsolute(options.path)) {
		throw Error('Configuration error: S3 path must be absolute');
	}

	// Ensure the generateFilename option takes a callback
	this.options.generateFilename = ensureCallback(this.options.generateFilename);
}

S3Adapter.compatibilityLevel = 1;

// All the extra schema fields supported by this adapter.
S3Adapter.SCHEMA_TYPES = {
	filename: String,
	bucket: String,
	path: String,
	etag: String,
};

S3Adapter.SCHEMA_FIELD_DEFAULTS = {
	filename: true,
	bucket: false,
	path: false,
	etag: false,
};

// Get the full, absolute path name for the specified file.
S3Adapter.prototype._resolveFilename = function (file) {
	// Just like the bucket, the schema can store the path for files. If the path
	// isn't stored we'll assume all the files are in the path specified in the
	// s3.path option. If that doesn't exist we'll assume the file is in the root
	// of the bucket. (Whew!)
	var path = file.path || this.options.path || '/';
	var filename = pathlib.posix.resolve(path, file.filename);
	return (filename.length && filename[0] === '/') ? filename.substring(1) : filename;
};

S3Adapter.prototype._awsParams = function (file) {
	if (file && file.bucket && file.bucket !== this.options.Bucket) {
		var s3options = assign({}, this.options, { Bucket: file.bucket });
		return s3options;
	} else {
		return this.options;
	}
};

S3Adapter.prototype.uploadFile = function (file, callback) {
	var self = this;
	this.options.generateFilename(file, 0, function (err, filename) {
		if (err) return callback(err);

		// The expanded path of the file on the filesystem.
		var localpath = file.path;

		// The destination path inside the S3 bucket.
		file.path = self.options.path;
		file.filename = filename;
		var fullpath = self._resolveFilename(file);

		debug('Uploading file %s', filename);

		var fileStream = fs.createReadStream(localpath);
		fileStream.on('error', function (err) {
			if (err) return callback(err);
		});

		var params = assign({}, {
			Key: fullpath,
			Body: fileStream,
		}, self._awsParams());

		s3.upload(params, function (err, data) {
			if (err) return callback(err);
			// We'll annotate the file with a bunch of extra properties. These won't
			// be saved in the database unless the corresponding schema options are
			// set.
			file.filename = filename;
			file.etag = data.ETag; // TODO: This etag is double-quoted (??why?)

			// file.url is automatically populated by keystone's Storage class so we
			// don't need to set it here.

			// The path and bucket can be stored on a per-file basis if you want.
			// The effect of this is that you can have some (eg, old) files in your
			// collection stored in different bucket / different path inside your
			// bucket. This means you can do slow data migrations. Note that if you
			// *don't* store these values you can arguably migrate your data more
			// easily - just move it all, reconfigure and restart your server.
			file.path = self.options.path;
			file.bucket = self.options.Bucket;

			debug('file upload successful');
			callback(null, file);
		});
	});
};

// Note that this will provide a public URL for the file, but it will only
// work if:
// - the bucket is public (best) or
// - the file is set to a canned ACL (ie, headers:{ 'x-amz-acl': 'public-read' } )
// - you pass credentials during your request for the file content itself
S3Adapter.prototype.getFileURL = function (file) {
	// Consider providing an option to use insecure http. I can't think of any
	// sensible use case for plain http though. https should be used everywhere.
	if (typeof this.options.publicUrl === 'function') {
		return this.options.publicUrl(file);
	}
	return 'https://' + this.options.Bucket + '.s3.amazonaws.com' + (this.options.path.length > 0 ? this.options.path : '') + '/' + file.filename;
};

S3Adapter.prototype.removeFile = function (file, callback) {
	var fullpath = this._resolveFilename(file);

	var params = assign({}, {
		Key: fullpath,
	}, self._awsParams());

	s3.deleteObject(params, function (err, data) {
		if (err) return callback(err);
		callback();
	});
};

// Check if a file with the specified filename already exists. Callback called
// with the file headers if the file exists, null otherwise.
S3Adapter.prototype.fileExists = function (filename, callback) {
	var fullpath = this._resolveFilename({ filename: filename });

	var params = assign({}, {
		Key: fullpath,
	}, self._awsParams());

	s3.getObject(params, function (err, data) {
		if (err) return callback(err);
		else		 callback(null, data);
	});
};

module.exports = S3Adapter;
<commit_msg>removes broken absolute path validation<commit_after>/*
TODO
- Check whether files exist before uploading (will always overwrite as-is)
- Support multiple retry attempts if a file exists (see FS Adapter)
*/

// Mirroring keystone 0.4's support of node 0.12.
var assign = require('object-assign');
var debug = require('debug')('keystone-s3');
var ensureCallback = require('keystone-storage-namefunctions/ensureCallback');
var fs = require('fs');
var S3 = require('aws-sdk/clients/s3');
var nameFunctions = require('keystone-storage-namefunctions');
var pathlib = require('path');

var DEFAULT_OPTIONS = {
	Bucket: process.env.S3_BUCKET,
	generateFilename: nameFunctions.randomFilename,
};

var s3 = new S3({
	accessKeyId: process.env.S3_KEY,
	secretAccessKey: process.env.S3_SECRET,
	region: process.env.S3_REGION || 'us-east-1',
});

// This constructor is usually called indirectly by the Storage class
// in keystone.

// S3-specific options should be specified in an `options.s3` field,
// which can contain the following options: { key, secret, bucket, region,
// headers, path }.

// The schema can contain the additional fields { path, bucket, etag }.

// See README.md for details and usage examples.

function S3Adapter (options, schema) {
	this.options = assign({}, DEFAULT_OPTIONS, options.s3);

	// Support `defaultHeaders` option alias for `headers`
	// TODO: Remove me with the next major version bump
	if (this.options.defaultHeaders) {
		this.options.headers = this.options.defaultHeaders;
		throw Error('Configuration error: S3 path must be absolute');
	}

	// Ensure the generateFilename option takes a callback
	this.options.generateFilename = ensureCallback(this.options.generateFilename);
}

S3Adapter.compatibilityLevel = 1;

// All the extra schema fields supported by this adapter.
S3Adapter.SCHEMA_TYPES = {
	filename: String,
	bucket: String,
	path: String,
	etag: String,
};

S3Adapter.SCHEMA_FIELD_DEFAULTS = {
	filename: true,
	bucket: false,
	path: false,
	etag: false,
};

// Get the full, absolute path name for the specified file.
S3Adapter.prototype._resolveFilename = function (file) {
	// Just like the bucket, the schema can store the path for files. If the path
	// isn't stored we'll assume all the files are in the path specified in the
	// s3.path option. If that doesn't exist we'll assume the file is in the root
	// of the bucket. (Whew!)
	var path = file.path || this.options.path || '/';
	var filename = pathlib.posix.resolve(path, file.filename);
	return (filename.length && filename[0] === '/') ? filename.substring(1) : filename;
};

S3Adapter.prototype._awsParams = function (file) {
	if (file && file.bucket && file.bucket !== this.options.Bucket) {
		var s3options = assign({}, this.options, { Bucket: file.bucket });
		return s3options;
	} else {
		return this.options;
	}
};

S3Adapter.prototype.uploadFile = function (file, callback) {
	var self = this;
	this.options.generateFilename(file, 0, function (err, filename) {
		if (err) return callback(err);

		// The expanded path of the file on the filesystem.
		var localpath = file.path;

		// The destination path inside the S3 bucket.
		file.path = self.options.path;
		file.filename = filename;
		var fullpath = self._resolveFilename(file);

		debug('Uploading file %s', filename);

		var fileStream = fs.createReadStream(localpath);
		fileStream.on('error', function (err) {
			if (err) return callback(err);
		});

		var params = assign({}, {
			Key: fullpath,
			Body: fileStream,
		}, self._awsParams());

		s3.upload(params, function (err, data) {
			if (err) return callback(err);
			// We'll annotate the file with a bunch of extra properties. These won't
			// be saved in the database unless the corresponding schema options are
			// set.
			file.filename = filename;
			file.etag = data.ETag; // TODO: This etag is double-quoted (??why?)

			// file.url is automatically populated by keystone's Storage class so we
			// don't need to set it here.

			// The path and bucket can be stored on a per-file basis if you want.
			// The effect of this is that you can have some (eg, old) files in your
			// collection stored in different bucket / different path inside your
			// bucket. This means you can do slow data migrations. Note that if you
			// *don't* store these values you can arguably migrate your data more
			// easily - just move it all, reconfigure and restart your server.
			file.path = self.options.path;
			file.bucket = self.options.Bucket;

			debug('file upload successful');
			callback(null, file);
		});
	});
};

// Note that this will provide a public URL for the file, but it will only
// work if:
// - the bucket is public (best) or
// - the file is set to a canned ACL (ie, headers:{ 'x-amz-acl': 'public-read' } )
// - you pass credentials during your request for the file content itself
S3Adapter.prototype.getFileURL = function (file) {
	// Consider providing an option to use insecure http. I can't think of any
	// sensible use case for plain http though. https should be used everywhere.
	if (typeof this.options.publicUrl === 'function') {
		return this.options.publicUrl(file);
	}
	return 'https://' + this.options.Bucket + '.s3.amazonaws.com' + (this.options.path.length > 0 ? this.options.path : '') + '/' + file.filename;
};

S3Adapter.prototype.removeFile = function (file, callback) {
	var fullpath = this._resolveFilename(file);

	var params = assign({}, {
		Key: fullpath,
	}, self._awsParams());

	s3.deleteObject(params, function (err, data) {
		if (err) return callback(err);
		callback();
	});
};

// Check if a file with the specified filename already exists. Callback called
// with the file headers if the file exists, null otherwise.
S3Adapter.prototype.fileExists = function (filename, callback) {
	var fullpath = this._resolveFilename({ filename: filename });

	var params = assign({}, {
		Key: fullpath,
	}, self._awsParams());

	s3.getObject(params, function (err, data) {
		if (err) return callback(err);
		else		 callback(null, data);
	});
};

module.exports = S3Adapter;
<|endoftext|>


<commit_before>$(function() {
  ;(function(w,d){
    w.___gcfg = {lang:"ja"};
    var s,e = d.getElementsByTagName("script")[0],
    a = function(u,f){if(!d.getElementById(f)){s = d.createElement("script");
      s.src = u;if(f){s.id = f;}e.parentNode.insertBefore(s,e);}};
    a("//platform.twitter.com/widgets.js","twitter-wjs");
    a("//connect.facebook.net/ja_JP/sdk.js#xfbml=1&version=v2.0","facebook-jssdk");
  })(this, document);

  $('.carousel').slick({
    dots: true,
    arrows: false,
    infinite: true,
    autoplay: true,
    autoplaySpeed: 5000,
    speed: 300,
    slidesToShow: 5,
    slidesToScroll: 5,
    responsive: [
      {
        breakpoint: 1024,
        settings: {
          slidesToShow: 3,
          slidesToScroll: 3,
          infinite: true,
          dots: true
        }
      },
      {
        breakpoint: 600,
        settings: {
          slidesToShow: 2,
          slidesToScroll: 2
        }
      },
      {
        breakpoint: 480,
        settings: {
          autoplay: true,
          autoplaySpeed: 2000,
          slidesToShow: 1,
          slidesToScroll: 1
        }
      }
    ]
  });

  var latlng = new google.maps.LatLng(34.802760, 135.771273);
  var options = {
      zoom: 16,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      scrollwheel: false
  };
  var map = new google.maps.Map(document.getElementById('map'), options);
  var styles =
    [{"featureType":"landscape","stylers":[{"saturation":-100},{"lightness":65},{"visibility":"on"}]},{"featureType":"poi","stylers":[{"saturation":-100},{"lightness":51},{"visibility":"simplified"}]},{"featureType":"road.highway","stylers":[{"saturation":-100},{"visibility":"simplified"}]},{"featureType":"road.arterial","stylers":[{"saturation":-100},{"lightness":30},{"visibility":"on"}]},{"featureType":"road.local","stylers":[{"saturation":-100},{"lightness":40},{"visibility":"on"}]},{"featureType":"transit","stylers":[{"saturation":-100},{"visibility":"simplified"}]},{"featureType":"administrative.province","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"labels","stylers":[{"visibility":"on"},{"lightness":-25},{"saturation":-100}]},{"featureType":"water","elementType":"geometry","stylers":[{"hue":"#ffff00"},{"lightness":-25},{"saturation":-97}]}];
  map.setOptions({styles: styles});

  var marker = new google.maps.Marker({
    position: map.getCenter(),
    title: 'ローム記念館',
    map: map
  });
});
<commit_msg>Remove unused semicolon<commit_after>$(function() {
  (function (w, d) {
    w.___gcfg = {lang:"ja"};
    var s,e = d.getElementsByTagName("script")[0],
    a = function(u,f){if(!d.getElementById(f)){s = d.createElement("script");
      s.src = u;if(f){s.id = f;}e.parentNode.insertBefore(s,e);}};
    a("//platform.twitter.com/widgets.js","twitter-wjs");
    a("//connect.facebook.net/ja_JP/sdk.js#xfbml=1&version=v2.0","facebook-jssdk");
  })(this, document);

  $('.carousel').slick({
    dots: true,
    arrows: false,
    infinite: true,
    autoplay: true,
    autoplaySpeed: 5000,
    speed: 300,
    slidesToShow: 5,
    slidesToScroll: 5,
    responsive: [
      {
        breakpoint: 1024,
        settings: {
          slidesToShow: 3,
          slidesToScroll: 3,
          infinite: true,
          dots: true
        }
      },
      {
        breakpoint: 600,
        settings: {
          slidesToShow: 2,
          slidesToScroll: 2
        }
      },
      {
        breakpoint: 480,
        settings: {
          autoplay: true,
          autoplaySpeed: 2000,
          slidesToShow: 1,
          slidesToScroll: 1
        }
      }
    ]
  });

  var latlng = new google.maps.LatLng(34.802760, 135.771273);
  var options = {
      zoom: 16,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      scrollwheel: false
  };
  var map = new google.maps.Map(document.getElementById('map'), options);
  var styles =
    [{"featureType":"landscape","stylers":[{"saturation":-100},{"lightness":65},{"visibility":"on"}]},{"featureType":"poi","stylers":[{"saturation":-100},{"lightness":51},{"visibility":"simplified"}]},{"featureType":"road.highway","stylers":[{"saturation":-100},{"visibility":"simplified"}]},{"featureType":"road.arterial","stylers":[{"saturation":-100},{"lightness":30},{"visibility":"on"}]},{"featureType":"road.local","stylers":[{"saturation":-100},{"lightness":40},{"visibility":"on"}]},{"featureType":"transit","stylers":[{"saturation":-100},{"visibility":"simplified"}]},{"featureType":"administrative.province","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"labels","stylers":[{"visibility":"on"},{"lightness":-25},{"saturation":-100}]},{"featureType":"water","elementType":"geometry","stylers":[{"hue":"#ffff00"},{"lightness":-25},{"saturation":-97}]}];
  map.setOptions({styles: styles});

  var marker = new google.maps.Marker({
    position: map.getCenter(),
    title: 'ローム記念館',
    map: map
  });
});
<|endoftext|>


<commit_before>var fs = require('fs');
var browser = require('./browser');
var recorder = require('./recorder');
var playback = require('./playback');
var mkdirp = require('mkdirp');
var colors = require('colors');

var DEFAULT_SCREEN_SIZE = [1024, 768];
// TODO: integration with remote environment

function _getTaskFolderName(taskName) {
  return process.cwd() + '/' + taskName + '.huxley';
}

// the signature of the operation passed:
// operation(singleTaskObj, callback)
function _operateOnEachTask(operation) {
  var tasks;
  try {
    tasks = require(process.cwd() + '/Huxleyfile.json');
  } catch (e) {
    // TODO: maybe not console
    console.error('No Huxleyfile.json found!'.red);
    return;
  }

  // TODO: throw if no task
  var currentTaskCount = 0;

  operation(tasks[currentTaskCount], function runNextTask() {
    if (currentTaskCount === tasks.length - 1) {
      process.stdin.pause();
      console.log('All done successfully!'.green);
    } else {
      console.log('\nNext task...');
      operation(tasks[++currentTaskCount], runNextTask);
    }
  });
}

function _recordTask(task, next) {
  var driver = browser.getNewDriver();
  var screenSize = task.screenSize || DEFAULT_SCREEN_SIZE;

  browser.openToUrl(driver, task.url, screenSize[0], screenSize[1], function() {
    console.log('Running test: ' + task.name);
    recorder.start(driver, function(screenShotTimes, recordingStartTime) {
      recorder.stop(driver, screenShotTimes, function(allEvents) {
        var processedTaskEvents =
          _processRawTaskEvents(allEvents, recordingStartTime);

        _saveTaskAsJsonToFolder(task.name, processedTaskEvents, function() {
          console.log(
            '\nDon\'t move! Simulating the recording now...\n'.bold.yellow
          );

          browser.quit(driver, function() {
            _playbackTaskAndSaveScreenshot(task, function() {
              next();
            });
          });
        });
      });
    });
  });
}

function _processRawTaskEvents(events, recordingStartTime) {
  // a single task freshly out of a recording session looks like this (first
  // item is time):
  // [1377491482885, 'keypress', 'D']
  // turn it into:
  // {
  //   "action": "keypress",
  //   "offsetTime": 2100,
  //   "key": "D"
  // }
  return events.map(function(event) {
    var action = event[1];
    var obj = {
      action: action,
      offsetTime: event[0] - recordingStartTime,
    };

    switch (action) {
      case 'click':
        obj.pos = event[2];
        break;
      case 'keypress':
        obj.key = event[2];
        break;
      case 'screenshot':
        obj.index = event[2];
        break;
      default:
        // TODO: really throw?
        throw 'Unrecognized user event.'.red;
    }

    return obj;
  });
}

function _saveTaskAsJsonToFolder(taskName, taskEvents, next) {
  // `taskEvents` should already have been processed by `_processRawTaskEvents`
  var folderPath = _getTaskFolderName(taskName);
  // TODO: err
  mkdirp(folderPath, function(err) {
    fs.writeFile(folderPath + '/record.json',
                JSON.stringify(taskEvents, null, 2), // prettify, 2 spaces indent
                function(err) {
      // TODO: err
      next();
    });
  });
}

function _playbackTaskAndSaveScreenshot(task, next) {
  var taskEvents;
  try {
    taskEvents = require(_getTaskFolderName(task.name) + '/record.json');
  } catch (e) {
    console.error('Cannot find info on recorded actions.'.red);
    return;
  }

  var driver = browser.getNewDriver();
  var screenSize = task.screenSize || DEFAULT_SCREEN_SIZE;

  browser.openToUrl(driver, task.url, screenSize[0], screenSize[1], function() {
    console.log('Running test: ' + task.name);

    var options = {
      taskPath: _getTaskFolderName(task.name),
      sleepFactor: task.sleepFactor
    };
    playback(driver, taskEvents, options, function() {
      browser.quit(driver, function() {
        next();
      });
    });
  });
}

function _playbackTaskAndCompareScreenshot(task, next) {
  var taskEvents;
  try {
    taskEvents = require(_getTaskFolderName(task.name) + '/record.json');
  } catch (e) {
    console.error('Cannot find info on recorded actions.'.red);
    return;
  }

  var driver = browser.getNewDriver();
  var screenSize = task.screenSize || DEFAULT_SCREEN_SIZE;

  browser.openToUrl(driver, task.url, screenSize[0], screenSize[1], function() {
    console.log('Running test: ' + task.name);

    var options = {
      taskPath: _getTaskFolderName(task.name),
      sleepFactor: task.sleepFactor,
      compareWithOldImages: true
    };
    playback(driver, taskEvents, options, function() {
      browser.quit(driver, function() {
        next();
      });
    });
  });
}

function recordTasks() {
  _operateOnEachTask(_recordTask);
}

function playbackTasksAndSaveScreenshots() {
  _operateOnEachTask(_playbackTaskAndSaveScreenshot);
}

function playbackTasksAndCompareScrenshots() {
  _operateOnEachTask(_playbackTaskAndCompareScreenshot);
}

module.exports = {
  recordTasks: recordTasks,
  playbackTasksAndSaveScreenshots: playbackTasksAndSaveScreenshots,
  playbackTasksAndCompareScrenshots: playbackTasksAndCompareScrenshots,
};

// recordTasks();

<commit_msg>refactor; playback and compare is really similar to playback and override<commit_after>var fs = require('fs');
var browser = require('./browser');
var recorder = require('./recorder');
var playback = require('./playback');
var mkdirp = require('mkdirp');
var colors = require('colors');

var DEFAULT_SCREEN_SIZE = [1024, 768];
// TODO: integration with remote environment

function _getTaskFolderName(taskName) {
  return process.cwd() + '/' + taskName + '.huxley';
}

// the signature of the operation passed:
// operation(singleTaskObj, callback)
function _operateOnEachTask(operation) {
  var tasks;
  try {
    tasks = require(process.cwd() + '/Huxleyfile.json');
  } catch (e) {
    // TODO: maybe not console
    console.error('No Huxleyfile.json found!'.red);
    return;
  }

  // TODO: throw if no task
  var currentTaskCount = 0;

  operation(tasks[currentTaskCount], function runNextTask() {
    if (currentTaskCount === tasks.length - 1) {
      process.stdin.pause();
      console.log('\nAll done successfully!'.green);
    } else {
      console.log('\nNext task...\n');
      operation(tasks[++currentTaskCount], runNextTask);
    }
  });
}

function _recordTask(task, next) {
  var driver = browser.getNewDriver();
  var screenSize = task.screenSize || DEFAULT_SCREEN_SIZE;

  browser.openToUrl(driver, task.url, screenSize[0], screenSize[1], function() {
    console.log('Running test: ' + task.name);
    recorder.start(driver, function(screenShotTimes, recordingStartTime) {
      recorder.stop(driver, screenShotTimes, function(allEvents) {
        var processedTaskEvents =
          _processRawTaskEvents(allEvents, recordingStartTime);

        _saveTaskAsJsonToFolder(task.name, processedTaskEvents, function() {
          console.log(
            '\nDon\'t move! Simulating the recording now...\n'.bold.yellow
          );

          browser.quit(driver, function() {
            _playbackTaskAndSaveScreenshot(task, function() {
              next();
            });
          });
        });
      });
    });
  });
}

function _processRawTaskEvents(events, recordingStartTime) {
  // a single task freshly out of a recording session looks like this (first
  // item is time):
  // [1377491482885, 'keypress', 'D']
  // turn it into:
  // {
  //   "action": "keypress",
  //   "offsetTime": 2100,
  //   "key": "D"
  // }
  return events.map(function(event) {
    var action = event[1];
    var obj = {
      action: action,
      offsetTime: event[0] - recordingStartTime,
    };

    switch (action) {
      case 'click':
        obj.pos = event[2];
        break;
      case 'keypress':
        obj.key = event[2];
        break;
      case 'screenshot':
        obj.index = event[2];
        break;
      default:
        // TODO: really throw?
        throw 'Unrecognized user event.'.red;
    }

    return obj;
  });
}

function _saveTaskAsJsonToFolder(taskName, taskEvents, next) {
  // `taskEvents` should already have been processed by `_processRawTaskEvents`
  var folderPath = _getTaskFolderName(taskName);
  // TODO: err
  mkdirp(folderPath, function(err) {
    fs.writeFile(folderPath + '/record.json',
                JSON.stringify(taskEvents, null, 2), // prettify, 2 spaces indent
                function(err) {
      // TODO: err
      next();
    });
  });
}

function _playbackTaskAndSaveScreenshot(task, next) {
  _playbackTask(task, false, next);
}

function _playbackTaskAndCompareScreenshot(task, next) {
  _playbackTask(task, true, next);
}

function _playbackTask(task, compareInsteadOfOverride, next) {
  var taskEvents;
  try {
    taskEvents = require(_getTaskFolderName(task.name) + '/record.json');
  } catch (e) {
    console.error('Cannot find info on recorded actions.'.red);
    return;
  }

  var driver = browser.getNewDriver();
  var screenSize = task.screenSize || DEFAULT_SCREEN_SIZE;

  browser.openToUrl(driver, task.url, screenSize[0], screenSize[1], function() {
    console.log('Running test: ' + task.name);

    var options = {
      taskPath: _getTaskFolderName(task.name),
      sleepFactor: task.sleepFactor,
      compareWithOldImages: compareInsteadOfOverride
    };
    playback(driver, taskEvents, options, function() {
      browser.quit(driver, function() {
        next();
      });
    });
  });
}

function recordTasks() {
  _operateOnEachTask(_recordTask);
}

function playbackTasksAndSaveScreenshots() {
  _operateOnEachTask(_playbackTaskAndSaveScreenshot);
}

function playbackTasksAndCompareScrenshots() {
  _operateOnEachTask(_playbackTaskAndCompareScreenshot);
}

module.exports = {
  recordTasks: recordTasks,
  playbackTasksAndSaveScreenshots: playbackTasksAndSaveScreenshots,
  playbackTasksAndCompareScrenshots: playbackTasksAndCompareScrenshots,
};

// recordTasks();

<|endoftext|>


<commit_before>(function(global) {       // IIFE for legacy non-module usage
'use strict';

var tagNameRegex = /^([a-z]+)(?:\:([a-z]+))?/           // matches 'input' or 'input:text'
var propsRegex = /((?:#|\.)[\w-]+)|(\[\w+(?:=[^\]=]+)?\])/g // matches all further properties
var attrRegex = /\[(\w+)(?:=([^\]=]+))?\]/              // matches '[foo=bar]' or '[foo]'

// Error subclass to throw for parsing errors
function ParseError(input) {
    this.message = input
    this.stack = new Error().stack
}
ParseError.prototype = Object.create(Error.prototype)
ParseError.prototype.name = 'JSnoXParseError'

// Convert a tag specification string into an object
// eg. 'input:checkbox#foo.bar[name=asdf]' produces the output:
// {
//   tagName: 'input',
//   props: {
//     type: 'checkbox',
//     id: 'foo',
//     className: 'bar',
//     name: 'asdf'
//   }
// }
function parseTagSpec(specString) {
    if (!specString.match) throw new ParseError(specString) // We didnt' receive a string

    // Parse tagName, and optional type attribute
    var tagMatch = specString.match(tagNameRegex)
    if (!tagMatch) throw new ParseError(specString)

    // Provide the specString as a default key, which can always be overridden
    // by the props hash (for when two siblings have the same specString)
    var tagName = tagMatch[1]
    var props = { key: specString }
    var classes = []
    if (tagMatch[2]) props.type = tagMatch[2]
    else if (tagName === 'button') props.type = 'button' // Saner default for <button>

    var matches = (specString || '').match(propsRegex)
    matches && matches.forEach(function(str) {
        if (!str) return
        else if (str[0] === '#') props.id = str.slice(1)
        else if (str[0] === '.') classes.push(str.slice(1))
        else if (str[0] === '[') {
            var match = str.match(attrRegex)
            if (match) props[match[1]] = match[2] || true    // If no attr value given, use true
        }
    })
    if (classes.length) props.className = classes.join(' ')
    return {
        tagName: tagName,
        props: props
    }
}

// Merge two objects, producing a new object with their properties
// (the className property is treated as a special cases)
function extend(obj1, obj2) {
    var output = {}
    obj1 = obj1 || {}
    obj2 = obj2 || {}

    for (var k in obj1) output[k] = obj1[k]
    for (var l in obj2) output[l] = obj2[l]

    // className is a special case: we want to return the combination
    // of strings if both objects contain className
    var combinedClass = obj1.className && obj2.className &&
                        [obj1.className, obj2.className].join(' ')
    if (combinedClass) output.className = combinedClass

    return output
}

function jsnox(React) {
    var client = function(componentType, props, children) {
        // Handle case where props arg is not specified (it's optional)
        if (Array.isArray(props) || typeof props === 'string') {
            children = props
            props = null
        }

        if (typeof componentType === 'function') {
            // For custom componenents, attempt to provide a default "key" prop.
            // This can prevent the "Each child in an array should have a
            // unique key prop" warning when the element doesn't have any
            // siblings of the same type. Provide a displayName for your custom
            // components to make this more useful (and help with debugging).
            var fakeKey = componentType.displayName || 'customElement'
            props = props || {}
            if (!props.key) props.key = fakeKey
        } else {
            // Parse the provided string into a hash of props
            var spec = parseTagSpec(componentType || '')
            componentType = spec.tagName
            props = extend(spec.props, props)
        }

        return React.createElement(componentType, props, children)
    }
    client.ParseError = ParseError
    return client
}

// Export for CommonJS, or else add a global jsnox variable:
if (typeof(module) !== 'undefined') module.exports = jsnox
else global.jsnox = jsnox

}(this))
<commit_msg>memoize parseTagSpec<commit_after>(function(global) {       // IIFE for legacy non-module usage
'use strict';

var tagNameRegex = /^([a-z]+)(?:\:([a-z]+))?/           // matches 'input' or 'input:text'
var propsRegex = /((?:#|\.)[\w-]+)|(\[\w+(?:=[^\]=]+)?\])/g // matches all further properties
var attrRegex = /\[(\w+)(?:=([^\]=]+))?\]/              // matches '[foo=bar]' or '[foo]'

// Error subclass to throw for parsing errors
function ParseError(input) {
    this.message = input
    this.stack = new Error().stack
}
ParseError.prototype = Object.create(Error.prototype)
ParseError.prototype.name = 'JSnoXParseError'

var specCache = {};

// Convert a tag specification string into an object
// eg. 'input:checkbox#foo.bar[name=asdf]' produces the output:
// {
//   tagName: 'input',
//   props: {
//     type: 'checkbox',
//     id: 'foo',
//     className: 'bar',
//     name: 'asdf'
//   }
// }
function parseTagSpec(specString) {
    if (!specString.match) throw new ParseError(specString) // We didnt' receive a string

    if (specCache[specString]) return specCache[specString];

    // Parse tagName, and optional type attribute
    var tagMatch = specString.match(tagNameRegex)
    if (!tagMatch) throw new ParseError(specString)

    // Provide the specString as a default key, which can always be overridden
    // by the props hash (for when two siblings have the same specString)
    var tagName = tagMatch[1]
    var props = { key: specString }
    var classes = []
    if (tagMatch[2]) props.type = tagMatch[2]
    else if (tagName === 'button') props.type = 'button' // Saner default for <button>

    var matches = (specString || '').match(propsRegex)
    matches && matches.forEach(function(str) {
        if (!str) return
        else if (str[0] === '#') props.id = str.slice(1)
        else if (str[0] === '.') classes.push(str.slice(1))
        else if (str[0] === '[') {
            var match = str.match(attrRegex)
            if (match) props[match[1]] = match[2] || true    // If no attr value given, use true
        }
    })
    if (classes.length) props.className = classes.join(' ')

    var spec = {
        tagName: tagName,
        props: props
    };

    specCache[specString] = spec

    return spec
}

// Merge two objects, producing a new object with their properties
// (the className property is treated as a special cases)
function extend(obj1, obj2) {
    var output = {}
    obj1 = obj1 || {}
    obj2 = obj2 || {}

    for (var k in obj1) output[k] = obj1[k]
    for (var l in obj2) output[l] = obj2[l]

    // className is a special case: we want to return the combination
    // of strings if both objects contain className
    var combinedClass = obj1.className && obj2.className &&
                        [obj1.className, obj2.className].join(' ')
    if (combinedClass) output.className = combinedClass

    return output
}

function jsnox(React) {
    var client = function(componentType, props, children) {
        // Handle case where props arg is not specified (it's optional)
        if (Array.isArray(props) || typeof props === 'string') {
            children = props
            props = null
        }

        if (typeof componentType === 'function') {
            // For custom componenents, attempt to provide a default "key" prop.
            // This can prevent the "Each child in an array should have a
            // unique key prop" warning when the element doesn't have any
            // siblings of the same type. Provide a displayName for your custom
            // components to make this more useful (and help with debugging).
            var fakeKey = componentType.displayName || 'customElement'
            props = props || {}
            if (!props.key) props.key = fakeKey
        } else {
            // Parse the provided string into a hash of props
            var spec = parseTagSpec(componentType || '')
            componentType = spec.tagName
            props = extend(spec.props, props)
        }

        return React.createElement(componentType, props, children)
    }
    client.ParseError = ParseError
    return client
}

// Export for CommonJS, or else add a global jsnox variable:
if (typeof(module) !== 'undefined') module.exports = jsnox
else global.jsnox = jsnox

}(this))
<|endoftext|>


<commit_before>var factory = (function () {

    var exports = {};
    var className = 'widget';
    var loadIndicatorClassName = 'widget-load-indicator';

    /**
     * Load widget
     *
     * @param uri
     * @param containerEl
     * @param options
     * @returns {Object}
     */
    exports.load = function (uri, containerEl, options) {
		var widget = {},
		    element = document.createElement('div'),
            display = '';

	    // Loading content
	    var loadingDiv, loadingStyle;

		// ensure options is an object
		options = options || {};

	    // Params to be passed along with view requests
	    var params = utils.clone(options) || {};

	    // element properties
	    element.className = className;
	    element.style.position = "relative";
	    element.style.width = '100%';
	    element.style.height = '100%';

	    // add event dispatcher behavior to widget
	    dispatcher(widget);

		// Initially show loading indicator
		if (!options.hideLoadingIndicator) {
			showLoadingIndicator(true);
		}

	    // Load widget content.
	    // We can't load the content until authorization is successful
	    if(auth.isPending() || auth.isIdle()) {
		    auth.on('success', function success() {
			    //auth.off('success', success);// TODO: bug, this clears all success handlers added
			    loadContent(config.baseUrl + uri, utils.extend(params, auth.data));
		    });
		    auth.on('error', function error() {
			    //auth.off('error', error);
			    showLoadingIndicator(false);
		    });
	    } else if(auth.isSuccess()) {
		    loadContent(config.baseUrl + uri, utils.extend(params, auth.data));
	    } else {
		    showLoadingIndicator(false);
	    }

        /**
         * Show the widget
         */
        widget.show = function () {
            widget.fire('show');
        };

        /**
         * Hide the widget
         */
        widget.hide = function () {
            widget.fire('hide');
        };

        /**
         * Destroy the widget
         */
        widget.destroy = function () {
	        widget.fire('destroy');
        };

	    /**
	     * Widget ready event handler
	     */
	    widget.on("ready", function() {
		    showLoadingIndicator(false);
	    });

	    /**
	     * Widget show event handler
	     */
	    widget.on("show", function() {
		    if (widget.element.parentNode.style.display === 'none') {
			    widget.element.parentNode.style.display = display;
		    }
		    widget.fire('shown');
	    });

	    /**
	     * Widget hide event handler
	     */
	    widget.on('hide', function() {
		    if (!display) {
			    display = widget.element.parentNode.style.display;
			    widget.element.parentNode.style.display = 'none';
		    }
		    widget.fire('hidden');
	    });

	    /**
	     * Widget destroy event handler
	     */
	    widget.on('destroy', function() {
		    widget.element.parentNode.removeChild(element);
		    widget.fire('destroyed');
	    });

        /**
         * Widget destroyed event handler
         */
        widget.on("destroyed", function() {
	        showLoadingIndicator(false);
            widget.off();
        });

		// resolve container
		if (!utils.isElement(containerEl)) {
			if (!containerEl) { // null or undefined
				containerEl = document.createElement('div');
				containerEl.setAttribute('style', 'position:absolute;top:0;left:0;width:100%;height:100%;z-index:99999');
				document.body.appendChild(containerEl);
			} else if (typeof containerEl === 'object') { // container is acting as a set of style options
				containerEl = document.createElement('div');
				containerEl.setAttribute('style', utils.styleToString(containerEl));
				document.body.appendChild(containerEl);
			}
		}

        // clear container content
        while (containerEl.firstChild) {
            var el = containerEl.firstChild;
	        el.widget.destroy();
        }

        // add element to container
		containerEl.appendChild(element);

	    // expose element on widget
	    widget.element = element;

	    // add a reference from the element back to the widget
	    widget.element.widget = widget;

	    /**
	     * Load widget content
	     *
	     * @param url
	     * @param params
	     */
	    function loadContent(url, params) {

		    params = params || {};

		    if(!utils.isEmptyObject(params)) {
			    url += (url.indexOf("?") === -1 ? "?" : "&") + utils.serialize(params);
		    }

		    // make request for view
		    utils.sendRequest("GET", url, {}, function(status, html) {

			    var tElement = document.createElement('div');
			    tElement.innerHTML = html;

			    // clone and remove scripts for later insert
			    // so that they will get executed by the browser
			    var clonedScripts = [];
			    var scripts = tElement.getElementsByTagName('script');
			    var i = scripts.length;

			    while (i--) {
				    var script = document.createElement("script");
				    var props = ['type', 'src', 'text'];
				    for(var k = 0; k < props.length; k++) {
					    var prop = props[k];
					    if(scripts[i][prop]) {
						    script[prop] = scripts[i][prop];
					    }
				    }
				    clonedScripts.unshift(script);

				    // remove script
				    scripts[i].parentNode.removeChild(scripts[i]);
			    }

			    // Insert template element children
			    for(i = 0 ; i < tElement.children.length ; i++) {
				    element.appendChild(tElement.children[i]);
			    }

			    // insert scripts
			    for(i = 0; i < clonedScripts.length; i++) {
				    element.lastChild.appendChild(clonedScripts[i]);
			    }

			    widget.fire('loaded');
		    });
	    }

	    /**
	     * Show loading indicator
	     *
	     * @param value
	     */
	    function showLoadingIndicator(value) {
		    if(value) {
			    // create loading style
			    loadingStyle = document.createElement('style');
			    loadingStyle.type = 'text/css';
			    loadingStyle.innerHTML = '@@loadingStyle';
			    element.appendChild(loadingStyle);

			    // create loading dev
			    loadingDiv = document.createElement('div');
			    loadingDiv.className = loadIndicatorClassName;
			    utils.forEach([
				    'G', 'N', 'I', 'D', 'A', 'O', 'L'
			    ], function(letter) {
				    var letterDiv = document.createElement('div');
				    letterDiv.innerText = letter;
				    loadingDiv.appendChild(letterDiv);
			    });
			    element.appendChild(loadingDiv);
		    } else {
			    if(loadingDiv) {
				    loadingDiv.parentElement.removeChild(loadingDiv);
			    }
			    if(loadingStyle) {
				    loadingStyle.parentElement.removeChild(loadingStyle);
			    }
			    loadingDiv = false;
			    loadingStyle = false;
		    }
	    }

        return widget;
    };

    dispatcher(exports);

    return exports;
})();<commit_msg>Added options to widget object<commit_after>var factory = (function () {

    var exports = {};
    var className = 'widget';
    var loadIndicatorClassName = 'widget-load-indicator';

    /**
     * Load widget
     *
     * @param uri
     * @param containerEl
     * @param options
     * @returns {Object}
     */
    exports.load = function (uri, containerEl, options) {
		var widget = {},
		    element = document.createElement('div'),
            display = '';

	    // Loading content
	    var loadingDiv, loadingStyle;

		// ensure options is an object
		options = options || {};

	    // Params to be passed along with view requests
	    var params = utils.clone(options) || {};

	    // element properties
	    element.className = className;
	    element.style.position = "relative";
	    element.style.width = '100%';
	    element.style.height = '100%';

	    // add event dispatcher behavior to widget
	    dispatcher(widget);

		// Initially show loading indicator
		if (!options.hideLoadingIndicator) {
			showLoadingIndicator(true);
		}

	    // Load widget content.
	    // We can't load the content until authorization is successful
	    if(auth.isPending() || auth.isIdle()) {
		    auth.on('success', function success() {
			    //auth.off('success', success);// TODO: bug, this clears all success handlers added
			    loadContent(config.baseUrl + uri, utils.extend(params, auth.data));
		    });
		    auth.on('error', function error() {
			    //auth.off('error', error);
			    showLoadingIndicator(false);
		    });
	    } else if(auth.isSuccess()) {
		    loadContent(config.baseUrl + uri, utils.extend(params, auth.data));
	    } else {
		    showLoadingIndicator(false);
	    }

        /**
         * Show the widget
         */
        widget.show = function () {
            widget.fire('show');
        };

        /**
         * Hide the widget
         */
        widget.hide = function () {
            widget.fire('hide');
        };

        /**
         * Destroy the widget
         */
        widget.destroy = function () {
	        widget.fire('destroy');
        };

	    /**
	     * Widget ready event handler
	     */
	    widget.on("ready", function() {
		    showLoadingIndicator(false);
	    });

	    /**
	     * Widget show event handler
	     */
	    widget.on("show", function() {
		    if (widget.element.parentNode.style.display === 'none') {
			    widget.element.parentNode.style.display = display;
		    }
		    widget.fire('shown');
	    });

	    /**
	     * Widget hide event handler
	     */
	    widget.on('hide', function() {
		    if (!display) {
			    display = widget.element.parentNode.style.display;
			    widget.element.parentNode.style.display = 'none';
		    }
		    widget.fire('hidden');
	    });

	    /**
	     * Widget destroy event handler
	     */
	    widget.on('destroy', function() {
		    widget.element.parentNode.removeChild(element);
		    widget.fire('destroyed');
	    });

        /**
         * Widget destroyed event handler
         */
        widget.on("destroyed", function() {
	        showLoadingIndicator(false);
            widget.off();
        });

		// resolve container
		if (!utils.isElement(containerEl)) {
			if (!containerEl) { // null or undefined
				containerEl = document.createElement('div');
				containerEl.setAttribute('style', 'position:absolute;top:0;left:0;width:100%;height:100%;z-index:99999');
				document.body.appendChild(containerEl);
			} else if (typeof containerEl === 'object') { // container is acting as a set of style options
				containerEl = document.createElement('div');
				containerEl.setAttribute('style', utils.styleToString(containerEl));
				document.body.appendChild(containerEl);
			}
		}

        // clear container content
        while (containerEl.firstChild) {
            var el = containerEl.firstChild;
	        el.widget.destroy();
        }

        // add element to container
		containerEl.appendChild(element);

	    // expose element on widget
	    widget.element = element;
	    widget.options = options;

	    // add a reference from the element back to the widget
	    widget.element.widget = widget;

	    /**
	     * Load widget content
	     *
	     * @param url
	     * @param params
	     */
	    function loadContent(url, params) {

		    params = params || {};

		    if(!utils.isEmptyObject(params)) {
			    url += (url.indexOf("?") === -1 ? "?" : "&") + utils.serialize(params);
		    }

		    // make request for view
		    utils.sendRequest("GET", url, {}, function(status, html) {

			    var tElement = document.createElement('div');
			    tElement.innerHTML = html;

			    // clone and remove scripts for later insert
			    // so that they will get executed by the browser
			    var clonedScripts = [];
			    var scripts = tElement.getElementsByTagName('script');
			    var i = scripts.length;

			    while (i--) {
				    var script = document.createElement("script");
				    var props = ['type', 'src', 'text'];
				    for(var k = 0; k < props.length; k++) {
					    var prop = props[k];
					    if(scripts[i][prop]) {
						    script[prop] = scripts[i][prop];
					    }
				    }
				    clonedScripts.unshift(script);

				    // remove script
				    scripts[i].parentNode.removeChild(scripts[i]);
			    }

			    // Insert template element children
			    for(i = 0 ; i < tElement.children.length ; i++) {
				    element.appendChild(tElement.children[i]);
			    }

			    // insert scripts
			    for(i = 0; i < clonedScripts.length; i++) {
				    element.lastChild.appendChild(clonedScripts[i]);
			    }

			    widget.fire('loaded');
		    });
	    }

	    /**
	     * Show loading indicator
	     *
	     * @param value
	     */
	    function showLoadingIndicator(value) {
		    if(value) {
			    // create loading style
			    loadingStyle = document.createElement('style');
			    loadingStyle.type = 'text/css';
			    loadingStyle.innerHTML = '@@loadingStyle';
			    element.appendChild(loadingStyle);

			    // create loading dev
			    loadingDiv = document.createElement('div');
			    loadingDiv.className = loadIndicatorClassName;
			    utils.forEach([
				    'G', 'N', 'I', 'D', 'A', 'O', 'L'
			    ], function(letter) {
				    var letterDiv = document.createElement('div');
				    letterDiv.innerText = letter;
				    loadingDiv.appendChild(letterDiv);
			    });
			    element.appendChild(loadingDiv);
		    } else {
			    if(loadingDiv) {
				    loadingDiv.parentElement.removeChild(loadingDiv);
			    }
			    if(loadingStyle) {
				    loadingStyle.parentElement.removeChild(loadingStyle);
			    }
			    loadingDiv = false;
			    loadingStyle = false;
		    }
	    }

        return widget;
    };

    dispatcher(exports);

    return exports;
})();<|endoftext|>


<commit_before>var express = require('express'),
	exphbs = require('express-handlebars'),
    jf = require('jsonfile'),
    moment = require('moment'),
    request = require('request'),
    MongoClient = require('mongodb').MongoClient,
    passport = require('passport'),
    GitHubStrategy = require('passport-github').Strategy,
    session = require('express-session'),
    github = require('octonode'),
    Sync = require('sync');
var GITHUB_CLIENT_ID = "false";
var GITHUB_CLIENT_SECRET = "false";
console.log("Connecting...");
MongoClient.connect(process.env.MONGOLAB_URI, function(err, db) {
    if(err) throw err;
    channels = db.collection('channels');
    console.log("Loading channels...");
    // Passport session setup.
    //   To support persistent login sessions, Passport needs to be able to
    //   serialize users into and deserialize users out of the session.  Typically,
    //   this will be as simple as storing the user ID when serializing, and finding
    //   the user by ID when deserializing.  However, since this example does not
    //   have a database of user records, the complete GitHub profile is serialized
    //   and deserialized.
    passport.serializeUser(function(user, done) {
        done(null, user);
    });

    passport.deserializeUser(function(obj, done) {
        done(null, obj);
    });

    // Use the GitHubStrategy within Passport.
    //   Strategies in Passport require a `verify` function, which accept
    //   credentials (in this case, an accessToken, refreshToken, and GitHub
    //   profile), and invoke a callback with a user object.
    passport.use(new GitHubStrategy({
            clientID: GITHUB_CLIENT_ID,
            clientSecret: GITHUB_CLIENT_SECRET,
            callbackURL: "https://octoclap.herokuapp.com/auth/github/callback",
            scope: ["user", "repo", "read:org"]
        },
        function(accessToken, refreshToken, profile, done) {
            // asynchronous verification, for effect...
            process.nextTick(function () {

                // To keep the example simple, the user's GitHub profile is returned to
                // represent the logged-in user.  In a typical application, you would want
                // to associate the GitHub account with a user record in your database,
                // and return that user instead.
                profile.accessToken = accessToken;
                profile.refreshToken = refreshToken;
                profile.repos = [];
                var client = github.client(accessToken);
                var me = client.me();
                me.repos(1, 100, function(err, data){
                    profile.repos = profile.repos.concat(data);
                });
                me.orgs(1, 100, function(err, data){
                    client.org(data[0].login).repos(1, 100, function (err, orgRepos) {
                        profile.repos = profile.repos.concat(orgRepos);
                    });
                });
                return done(null, profile); //WARNING: Race condition!!!
            });
        }
    ));
    var app = express();
    app.use(session({
        secret: 'keyboard cat'
    }));
    app.use(passport.initialize());
    app.use(passport.session());
    app.get('/auth/github',
        passport.authenticate('github'),
        function(req, res){
            // The request will be redirected to GitHub for authentication, so this
            // function will not be called.
        });

    // GET /auth/github/callback
    //   Use passport.authenticate() as route middleware to authenticate the
    //   request.  If authentication fails, the user will be redirected back to the
    //   login page.  Otherwise, the primary route function function will be called,
    //   which, in this example, will redirect the user to the home page.
    app.get('/auth/github/callback',
        passport.authenticate('github', { failureRedirect: '/login' }),
        function(req, res) {
            res.redirect('/');
    });
    app.get('/api', function(req, res){

    });
    app.engine('handlebars', exphbs({defaultLayout: 'main'}));
    app.set('view engine', 'handlebars');
    app.set('port', (process.env.PORT || 5000));

    app.get('/:account/:repo', function (req, res) {
        res.setHeader('Content-Type', 'application/json'); // Promise JSON
        channels.findOne({"_id": req.params.account + "/" + req.params.repo}, function(err, document){
            var ret = { account: req.params.account, repo: req.params.repo};
            if(document != null){
                ret.entryExists = true;
            }
            else{
                ret.entryExists = false;
                ret.data = [];
                res.end(JSON.stringify(ret, null, 3));
            }
        });
    });
    app.get('/user', ensureAuthenticated, function(req,res){
        res.setHeader('Content-Type', 'application/json'); // Promise JSON
        res.end(JSON.stringify(req.user, null, 3));
    });
    app.get('/', function(req, res){
       res.render("home", { user: req.user });
    });
    app.get('/logout', function(req, res){
        req.logout();
        res.redirect('/');
    });
    app.listen(app.get('port'), function () {
        console.log("Node app is running at localhost:" + app.get('port'))
    });
});
function ensureAuthenticated(req, res, next) {
    if (req.isAuthenticated())
        return next();
    else
        res.redirect("/");
}
<commit_msg>Removed unused Sync module<commit_after>var express = require('express'),
	exphbs = require('express-handlebars'),
    jf = require('jsonfile'),
    moment = require('moment'),
    request = require('request'),
    MongoClient = require('mongodb').MongoClient,
    passport = require('passport'),
    GitHubStrategy = require('passport-github').Strategy,
    session = require('express-session'),
    github = require('octonode');
var GITHUB_CLIENT_ID = "false";
var GITHUB_CLIENT_SECRET = "false";
console.log("Connecting...");
MongoClient.connect(process.env.MONGOLAB_URI, function(err, db) {
    if(err) throw err;
    channels = db.collection('channels');
    console.log("Loading channels...");
    // Passport session setup.
    //   To support persistent login sessions, Passport needs to be able to
    //   serialize users into and deserialize users out of the session.  Typically,
    //   this will be as simple as storing the user ID when serializing, and finding
    //   the user by ID when deserializing.  However, since this example does not
    //   have a database of user records, the complete GitHub profile is serialized
    //   and deserialized.
    passport.serializeUser(function(user, done) {
        done(null, user);
    });

    passport.deserializeUser(function(obj, done) {
        done(null, obj);
    });

    // Use the GitHubStrategy within Passport.
    //   Strategies in Passport require a `verify` function, which accept
    //   credentials (in this case, an accessToken, refreshToken, and GitHub
    //   profile), and invoke a callback with a user object.
    passport.use(new GitHubStrategy({
            clientID: GITHUB_CLIENT_ID,
            clientSecret: GITHUB_CLIENT_SECRET,
            callbackURL: "https://octoclap.herokuapp.com/auth/github/callback",
            scope: ["user", "repo", "read:org"]
        },
        function(accessToken, refreshToken, profile, done) {
            // asynchronous verification, for effect...
            process.nextTick(function () {

                // To keep the example simple, the user's GitHub profile is returned to
                // represent the logged-in user.  In a typical application, you would want
                // to associate the GitHub account with a user record in your database,
                // and return that user instead.
                profile.accessToken = accessToken;
                profile.refreshToken = refreshToken;
                profile.repos = [];
                var client = github.client(accessToken);
                var me = client.me();
                me.repos(1, 100, function(err, data){
                    profile.repos = profile.repos.concat(data);
                });
                me.orgs(1, 100, function(err, data){
                    client.org(data[0].login).repos(1, 100, function (err, orgRepos) {
                        profile.repos = profile.repos.concat(orgRepos);
                    });
                });
                return done(null, profile); //WARNING: Race condition!!!
            });
        }
    ));
    var app = express();
    app.use(session({
        secret: 'keyboard cat'
    }));
    app.use(passport.initialize());
    app.use(passport.session());
    app.get('/auth/github',
        passport.authenticate('github'),
        function(req, res){
            // The request will be redirected to GitHub for authentication, so this
            // function will not be called.
        });

    // GET /auth/github/callback
    //   Use passport.authenticate() as route middleware to authenticate the
    //   request.  If authentication fails, the user will be redirected back to the
    //   login page.  Otherwise, the primary route function function will be called,
    //   which, in this example, will redirect the user to the home page.
    app.get('/auth/github/callback',
        passport.authenticate('github', { failureRedirect: '/login' }),
        function(req, res) {
            res.redirect('/');
    });
    app.get('/api', function(req, res){

    });
    app.engine('handlebars', exphbs({defaultLayout: 'main'}));
    app.set('view engine', 'handlebars');
    app.set('port', (process.env.PORT || 5000));

    app.get('/:account/:repo', function (req, res) {
        res.setHeader('Content-Type', 'application/json'); // Promise JSON
        channels.findOne({"_id": req.params.account + "/" + req.params.repo}, function(err, document){
            var ret = { account: req.params.account, repo: req.params.repo};
            if(document != null){
                ret.entryExists = true;
            }
            else{
                ret.entryExists = false;
                ret.data = [];
                res.end(JSON.stringify(ret, null, 3));
            }
        });
    });
    app.get('/user', ensureAuthenticated, function(req,res){
        res.setHeader('Content-Type', 'application/json'); // Promise JSON
        res.end(JSON.stringify(req.user, null, 3));
    });
    app.get('/', function(req, res){
       res.render("home", { user: req.user });
    });
    app.get('/logout', function(req, res){
        req.logout();
        res.redirect('/');
    });
    app.listen(app.get('port'), function () {
        console.log("Node app is running at localhost:" + app.get('port'))
    });
});
function ensureAuthenticated(req, res, next) {
    if (req.isAuthenticated())
        return next();
    else
        res.redirect("/");
}
<|endoftext|>