<commit_before>/* globals define, exports, module */

(function(root, definition) {
	if (typeof define === 'function' && define.amd) {
		// AMD. Register as an anonymous module.
		define([], definition);
	} else if (typeof exports === 'object') {
		// Node. Does not work with strict CommonJS, but only CommonJS-like
		// environments that support module.exports, like Node.
		module.exports = definition();
	} else {
		// Browser globals (root is window)
		root.ViewEE = definition();
	}
}(window, function() {

var fontLoaded = false;

function stupidWebfontTrick(eagle) {
	if (!fontLoaded) {
		// see http://stackoverflow.com/a/8223543/27408
		var i = new Image()
		i.src = "../fonts/osifont.woff"
		i.onerror = function() {
			eagle.draw()
			setTimeout(function(){eagle.draw()}, 50)
			fontLoaded = true;
		};
	}

	updateCheckboxes()
	selectItem(null)
}

function loadWebFonts (cb) {
	if (typeof FontLoader === "undefined") {
		setTimeout (cb, 500);
		return;
	}

	var fontLoader = new FontLoader(["vector"], {
		"complete": function(error) {
			if (error !== null) {
				// Reached the timeout but not all fonts were loaded
				console.log(error.message);
				console.log(error.notLoadedFonts);
			} else {
				// All fonts were loaded
				// console.log("all fonts were loaded");
			}
			cb();
		}
	}, 500);

	fontLoader.loadFonts();
}

function MakeEl (name, attrs) {
	attrs = attrs || {};
	var el = attrs.xmlns ? document.createElementNS (attrs.xmlns, name) : document.createElement (name);
	for (var i in attrs) {
		if (i === 'xmlns') continue;
		el.setAttributeNS (null, i, attrs[i]);
		if (i.toLowerCase() == 'class') {
			el.className = attrs[i];  // for IE compatibility
		} else if (i.toLowerCase() == 'style') {
			el.style.cssText = attrs[i]; // for IE compatibility
		}
	}
	for (var i = 2; i<arguments.length; i++) {
		var val = arguments[i];
		if (typeof val == 'string')
			val = document.createTextNode( val );
		if (el && el.appendChild)
			el.appendChild (val);
	}
	return el;
}

window.MakeEl = MakeEl;

function getFormFields (formEl, formData) {
	formData = formData || {};
	for (var k in formData) {
		delete formData[k];
	}
	for (var i = 0; i < formEl.elements.length; i ++) {
		var formField = formEl.elements[i];
		var checkedType = formField.type.match (/^(?:radio|checkbox)$/);
		if ((checkedType && formField.checked) || !checkedType) {
			formData[formField.name] = formField.value;
		}
	}
	// console.log (formData);
	return formData;
}

var layers = [
	{id: 5, title: "Top Copper"},
	{id: 6, title: "Top silkscreen"},
	{id: 7, title: "Top documentation"},
	{id: 1, title: "Bottom copper"},
	{id: 2, title: "Bottom silkscreen"},
	{id: 3, title: "Bottom documentation"},
	{id: 9, title: "Outline"},
	{id: 8, title: "Vias"},
	{id: 4, title: "Dim backside"},
];

var EagleCanvas;

function ViewEE (options, EagleCanvasClass) {

	if (!options) options = {};

	if (!options.fromScratch && ViewEE.initialized)
		return ViewEE.initialized;

	EagleCanvas = EagleCanvas || EagleCanvasClass || window.EagleCanvas;

	this.node = options.node || document;

	this.canvasSelector = options.canvasSelector || '#canvas';
	this.scaleSelector  = options.scaleSelector  || '#outer';
	this.formSelector   = options.formSelector   || "form";
	this.hintsBoxSel    = options.hintsBoxSel    || '#hintsbox';
	this.hintsTitleSel  = options.hintsTitleSel  || '#hintstitle';
	this.hintsTextSel   = options.hintsTextSel   || '#hintstext';

	var form = this.node.querySelector (this.formSelector);
	var radios = [].slice.apply (form.querySelectorAll ('input[name=side]'));
	radios.forEach (function (radio) {
		radio.addEventListener ('click', function (e) {
			e = e || window.event;
			if (e) e.stopPropagation();
			var ff = getFormFields (form);
			this.canvas.setBoardFlipped (ff.side === 'back');
		}.bind (this));
	}, this);

	var layerList = form.querySelector ('div.dropdown ul.layers');
	layerList.innerHTML = '';

	for (var i = 0; i < layers.length; i++) {
		var layerNum = layers[i].id;
		var chk = MakeEl ('input', {
			type: "checkbox", checked: "true", id: "layer-"+layerNum, "data-layer": layerNum
		});
		var li = MakeEl (
			'li', {},
			chk,
			MakeEl ('label', {for: "layer-"+layerNum}, layers[i].title)
		);

		layerList.appendChild (li);

		chk.addEventListener ('click', this.toggleLayer.bind (this));
	}

	var zoomIn = form.querySelector ('.zoomIn');
	zoomIn.addEventListener ("click", this.zoomInHandler.bind (this), false);

	var zoomOut = form.querySelector ('.zoomOut');
	zoomOut.addEventListener ("click", this.zoomOutHandler.bind (this), false);

	var canvas = this.node.querySelector (this.canvasSelector);
	canvas.addEventListener ("click", this.canvasClick.bind (this), false);

	ViewEE.initialized = this;

	var resizeHandler = function () {
		this.canvas.scaleToFit ();
		this.canvas.draw ();
	}.bind (this);

	var resizeTimer;
	window.addEventListener ("resize", function() {
		clearTimeout (resizeTimer);
		resizeTimer = setTimeout (resizeHandler, 100);
	});

	loadWebFonts (function () {
		ViewEE.fontReady = true;
		if (this.loadUrl.delayed) {
			this.canvas.loadURL (this.loadUrl.delayed);
			delete this.loadUrl.delayed;
		} else if (this.loadText.delayed) {
			this.canvas.loadText (this.loadText.delayed);
			delete this.loadText.delayed;
		}
	}.bind (this));

}

ViewEE.init = function (url) {
	var viewee = new ViewEE ();
	viewee.loadUrl (url);
	return viewee;
}

ViewEE.deselect = function () {
	var viewee = new ViewEE ();
	viewee.selectItem (null);
}

ViewEE.prototype.loadUrl = function (url) {

	var defaultUrl; // = 'problems/no holes - lpc1114-valdez-mut-v.04.brd';

	var form = this.node.querySelector (this.formSelector);
	if (form) {
		var option = form.querySelector ("select.board option");
		defaultUrl = option.value;
	}

	this.canvas = new EagleCanvas (this.node.querySelector (this.canvasSelector));

	this.canvas.setScaleToFit (this.scaleSelector);
	if (!ViewEE.fontReady) {
		this.loadUrl.delayed = url || defaultUrl;
	} else {
		this.canvas.loadURL(url || defaultUrl, function () {});
	}

}

ViewEE.prototype.loadText = function (text) {

	this.canvas = new EagleCanvas (this.node.querySelector (this.canvasSelector));

	this.canvas.setScaleToFit (this.scaleSelector);

	if (!ViewEE.fontReady) {
		this.loadText.delayed = text;
	} else {
		this.canvas.loadText (text);
	}
}

ViewEE.prototype.zoomInHandler = function (e) {
	e = e || window.event;
	if (e) e.stopPropagation();
	this.canvas.setScale (this.canvas.getScale()*1.2);
}

ViewEE.prototype.zoomOutHandler = function (e) {
	e = e || window.event;
	if (e) e.stopPropagation();
	this.canvas.setScale (this.canvas.getScale()/1.2);
}

ViewEE.prototype.toggleLayer = function (e, layer) {
	e = e || window.event;
	if (e) e.stopPropagation();
	if (!layer) layer = parseInt (e.target.getAttribute ('data-layer'));
	var shown = this.canvas.isLayerVisible(layer);
	shown = !shown;
	this.canvas.setLayerVisible(layer,shown);
	this.updateCheckboxes();
}

ViewEE.prototype.updateCheckboxes = function () {
	for (var layerKey in EagleCanvas.LayerId) {
		var layerId = EagleCanvas.LayerId[layerKey];
		var form = this.node.querySelector (this.formSelector);
		var chk = form.querySelector ('input[data-layer="'+layerId+'"]');
		if (!chk) continue;
		chk.checked = (this.canvas.isLayerVisible(layerId)) ? "checked" : "";
	}
}

ViewEE.prototype.canvasClick = function (e) {
	e = e || window.event;
	if (!e) return;
	e.stopPropagation();
	var canvas = this.node.querySelector (this.canvasSelector);
	var x = e.clientX - canvas.getBoundingClientRect().left - canvas.clientLeft + canvas.scrollLeft;
	var y = e.clientY - canvas.getBoundingClientRect().top - canvas.clientTop + canvas.scrollTop;
	var hit = this.canvas.hitTest(x,y);
	this.selectItem(hit);
}

ViewEE.prototype.selectItem = function (hit) {
	this.canvas.setHighlightedItem (hit);
	var hintsbox = this.node.querySelector (this.hintsBoxSel);
	hintsbox.style.display = (hit) ? 'block' : 'none';

	if (!hit) return;

	var hintstitle = this.node.querySelector (this.hintsTitleSel);
	while (hintstitle.childNodes.length > 0)
		hintstitle.removeChild(hintstitle.firstChild);
	var title = "";
	if (hit.type=='element') title = "Element: "+hit.name;
	else if (hit.type=='signal') title = "Signal: "+hit.name;
	hintstitle.appendChild (document.createTextNode(title));

	var hintstext = this.node.querySelector (this.hintsTextSel);
	while (hintstext.childNodes.length > 0)
		hintstext.removeChild(hintstext.firstChild);
	var desc = "";
	if (hit.description) {
		desc = hit.description;
	} else if (typeof itemHints !== "undefined") {
		desc = itemHints[hit.type+": "+hit.name];
	}
	if (!desc) desc = "";
	hintstext.appendChild(document.createTextNode(desc));
}

return ViewEE;

}))
<commit_msg>canvas needed much earlier<commit_after>/* globals define, exports, module */

(function(root, definition) {
	if (typeof define === 'function' && define.amd) {
		// AMD. Register as an anonymous module.
		define([], definition);
	} else if (typeof exports === 'object') {
		// Node. Does not work with strict CommonJS, but only CommonJS-like
		// environments that support module.exports, like Node.
		module.exports = definition();
	} else {
		// Browser globals (root is window)
		root.ViewEE = definition();
	}
}(window, function() {

var fontLoaded = false;

function stupidWebfontTrick(eagle) {
	if (!fontLoaded) {
		// see http://stackoverflow.com/a/8223543/27408
		var i = new Image()
		i.src = "../fonts/osifont.woff"
		i.onerror = function() {
			eagle.draw()
			setTimeout(function(){eagle.draw()}, 50)
			fontLoaded = true;
		};
	}

	updateCheckboxes()
	selectItem(null)
}

function loadWebFonts (cb) {
	if (typeof FontLoader === "undefined") {
		setTimeout (cb, 500);
		return;
	}

	var fontLoader = new FontLoader(["vector"], {
		"complete": function(error) {
			if (error !== null) {
				// Reached the timeout but not all fonts were loaded
				console.log(error.message);
				console.log(error.notLoadedFonts);
			} else {
				// All fonts were loaded
				// console.log("all fonts were loaded");
			}
			cb();
		}
	}, 500);

	fontLoader.loadFonts();
}

function MakeEl (name, attrs) {
	attrs = attrs || {};
	var el = attrs.xmlns ? document.createElementNS (attrs.xmlns, name) : document.createElement (name);
	for (var i in attrs) {
		if (i === 'xmlns') continue;
		el.setAttributeNS (null, i, attrs[i]);
		if (i.toLowerCase() == 'class') {
			el.className = attrs[i];  // for IE compatibility
		} else if (i.toLowerCase() == 'style') {
			el.style.cssText = attrs[i]; // for IE compatibility
		}
	}
	for (var i = 2; i<arguments.length; i++) {
		var val = arguments[i];
		if (typeof val == 'string')
			val = document.createTextNode( val );
		if (el && el.appendChild)
			el.appendChild (val);
	}
	return el;
}

window.MakeEl = MakeEl;

function getFormFields (formEl, formData) {
	formData = formData || {};
	for (var k in formData) {
		delete formData[k];
	}
	for (var i = 0; i < formEl.elements.length; i ++) {
		var formField = formEl.elements[i];
		var checkedType = formField.type.match (/^(?:radio|checkbox)$/);
		if ((checkedType && formField.checked) || !checkedType) {
			formData[formField.name] = formField.value;
		}
	}
	// console.log (formData);
	return formData;
}

var layers = [
	{id: 5, title: "Top Copper"},
	{id: 6, title: "Top silkscreen"},
	{id: 7, title: "Top documentation"},
	{id: 1, title: "Bottom copper"},
	{id: 2, title: "Bottom silkscreen"},
	{id: 3, title: "Bottom documentation"},
	{id: 9, title: "Outline"},
	{id: 8, title: "Vias"},
	{id: 4, title: "Dim backside"},
];

var EagleCanvas;

function ViewEE (options, EagleCanvasClass) {

	if (!options) options = {};

	if (!options.fromScratch && ViewEE.initialized)
		return ViewEE.initialized;

	EagleCanvas = EagleCanvas || EagleCanvasClass || window.EagleCanvas;

	this.node = options.node || document;

	this.canvasSelector = options.canvasSelector || '#canvas';
	this.scaleSelector  = options.scaleSelector  || '#outer';
	this.formSelector   = options.formSelector   || "form";
	this.hintsBoxSel    = options.hintsBoxSel    || '#hintsbox';
	this.hintsTitleSel  = options.hintsTitleSel  || '#hintstitle';
	this.hintsTextSel   = options.hintsTextSel   || '#hintstext';

	this.canvas = new EagleCanvas (this.node.querySelector (this.canvasSelector));

	var form = this.node.querySelector (this.formSelector);
	var radios = [].slice.apply (form.querySelectorAll ('input[name=side]'));
	radios.forEach (function (radio) {
		radio.addEventListener ('click', function (e) {
			e = e || window.event;
			if (e) e.stopPropagation();
			var ff = getFormFields (form);
			this.canvas.setBoardFlipped (ff.side === 'back');
		}.bind (this));
	}, this);

	var layerList = form.querySelector ('div.dropdown ul.layers');
	layerList.innerHTML = '';

	for (var i = 0; i < layers.length; i++) {
		var layerNum = layers[i].id;
		var chk = MakeEl ('input', {
			type: "checkbox", checked: "true", id: "layer-"+layerNum, "data-layer": layerNum
		});
		var li = MakeEl (
			'li', {},
			chk,
			MakeEl ('label', {for: "layer-"+layerNum}, layers[i].title)
		);

		layerList.appendChild (li);

		chk.addEventListener ('click', this.toggleLayer.bind (this));
	}

	var zoomIn = form.querySelector ('.zoomIn');
	zoomIn.addEventListener ("click", this.zoomInHandler.bind (this), false);

	var zoomOut = form.querySelector ('.zoomOut');
	zoomOut.addEventListener ("click", this.zoomOutHandler.bind (this), false);

	var canvas = this.node.querySelector (this.canvasSelector);
	canvas.addEventListener ("click", this.canvasClick.bind (this), false);

	ViewEE.initialized = this;

	var resizeHandler = function () {
		this.canvas.scaleToFit ();
		this.canvas.draw ();
	}.bind (this);

	var resizeTimer;
	window.addEventListener ("resize", function() {
		clearTimeout (resizeTimer);
		resizeTimer = setTimeout (resizeHandler, 100);
	});

	loadWebFonts (function () {
		ViewEE.fontReady = true;
		if (this.loadUrl.delayed) {
			this.canvas.loadURL (this.loadUrl.delayed);
			delete this.loadUrl.delayed;
		} else if (this.loadText.delayed) {
			this.canvas.loadText (this.loadText.delayed);
			delete this.loadText.delayed;
		}
	}.bind (this));

}

ViewEE.init = function (url) {
	var viewee = new ViewEE ();
	viewee.loadUrl (url);
	return viewee;
}

ViewEE.deselect = function () {
	var viewee = new ViewEE ();
	viewee.selectItem (null);
}

ViewEE.prototype.loadUrl = function (url) {

	var defaultUrl; // = 'problems/no holes - lpc1114-valdez-mut-v.04.brd';

	var form = this.node.querySelector (this.formSelector);
	if (form) {
		var option = form.querySelector ("select.board option");
		defaultUrl = option.value;
	}

	this.canvas.setScaleToFit (this.scaleSelector);
	if (!ViewEE.fontReady) {
		this.loadUrl.delayed = url || defaultUrl;
	} else {
		this.canvas.loadURL(url || defaultUrl, function () {});
	}

}

ViewEE.prototype.loadText = function (text) {

	this.canvas = new EagleCanvas (this.node.querySelector (this.canvasSelector));

	this.canvas.setScaleToFit (this.scaleSelector);

	if (!ViewEE.fontReady) {
		this.loadText.delayed = text;
	} else {
		this.canvas.loadText (text);
	}
}

ViewEE.prototype.zoomInHandler = function (e) {
	e = e || window.event;
	if (e) e.stopPropagation();
	this.canvas.setScale (this.canvas.getScale()*1.2);
}

ViewEE.prototype.zoomOutHandler = function (e) {
	e = e || window.event;
	if (e) e.stopPropagation();
	this.canvas.setScale (this.canvas.getScale()/1.2);
}

ViewEE.prototype.toggleLayer = function (e, layer) {
	e = e || window.event;
	if (e) e.stopPropagation();
	if (!layer) layer = parseInt (e.target.getAttribute ('data-layer'));
	var shown = this.canvas.isLayerVisible(layer);
	shown = !shown;
	this.canvas.setLayerVisible(layer,shown);
	this.updateCheckboxes();
}

ViewEE.prototype.updateCheckboxes = function () {
	for (var layerKey in EagleCanvas.LayerId) {
		var layerId = EagleCanvas.LayerId[layerKey];
		var form = this.node.querySelector (this.formSelector);
		var chk = form.querySelector ('input[data-layer="'+layerId+'"]');
		if (!chk) continue;
		chk.checked = (this.canvas.isLayerVisible(layerId)) ? "checked" : "";
	}
}

ViewEE.prototype.canvasClick = function (e) {
	e = e || window.event;
	if (!e) return;
	e.stopPropagation();
	var canvas = this.node.querySelector (this.canvasSelector);
	var x = e.clientX - canvas.getBoundingClientRect().left - canvas.clientLeft + canvas.scrollLeft;
	var y = e.clientY - canvas.getBoundingClientRect().top - canvas.clientTop + canvas.scrollTop;
	var hit = this.canvas.hitTest(x,y);
	this.selectItem(hit);
}

ViewEE.prototype.selectItem = function (hit) {
	this.canvas.setHighlightedItem (hit);
	var hintsbox = this.node.querySelector (this.hintsBoxSel);
	hintsbox.style.display = (hit) ? 'block' : 'none';

	if (!hit) return;

	var hintstitle = this.node.querySelector (this.hintsTitleSel);
	while (hintstitle.childNodes.length > 0)
		hintstitle.removeChild(hintstitle.firstChild);
	var title = "";
	if (hit.type=='element') title = "Element: "+hit.name;
	else if (hit.type=='signal') title = "Signal: "+hit.name;
	hintstitle.appendChild (document.createTextNode(title));

	var hintstext = this.node.querySelector (this.hintsTextSel);
	while (hintstext.childNodes.length > 0)
		hintstext.removeChild(hintstext.firstChild);
	var desc = "";
	if (hit.description) {
		desc = hit.description;
	} else if (typeof itemHints !== "undefined") {
		desc = itemHints[hit.type+": "+hit.name];
	}
	if (!desc) desc = "";
	hintstext.appendChild(document.createTextNode(desc));
}

return ViewEE;

}))
<|endoftext|>


<commit_before>nextZoneId = function() {
  var zoneIds = 0;
  return function () {
    return zoneIds++;
  };
}();

extendZone = function(fields) {
  for(var key in fields) {
    Zone.prototype[key] = fields[key];
  }
};

// extendZone with our own functionality

extendZone({
  _fork: Zone.prototype.fork,

  onError: function (e) {
    this.erroredStack = new Stacktrace(e);
    Zone.Reporters.run(this);
  },

  fork: function (locals) {
    var zone = this._fork(locals);
    zone.currentStack = getStacktrace();
    zone.createdAt = Date.now();
    zone.id = nextZoneId();

    // when creating a new zone, it will use's parent zone as __proto__
    // that's why we can access ancesstor properties
    // but we are deleting eventMap just after zone ran
    // so, we need to create eventMap explicitely to stay it in the current zone
    zone.eventMap = zone.eventMap;

    // make sure owner doesn't get inherited
    zone.owner = undefined;
    return zone;
  },

  beforeTask: function() {
    this.runAt = Date.now();

    // create eventMap for the first time
    // eventMap will be deleted just after zone completed
    // but it will be available only in the errroed zone
    // so, in that zone, someone can access all the events happened on the
    // async call stack
    if(!this.eventMap) {
      this.eventMap = {};
    }

    // _events will only be available during the zone running time only
    // an event can be run multiple times. So we can't maintain the events
    // in this array forever.
    // best option is to add it to eventMap, which carries events to the
    // top of the stack
    this._events = [];
    this.eventMap[this.id] = this._events;

    // if there is _ownerArgs we need to add it as an event
    // after that we don't need to _ownerArgs
    if(this._ownerArgs) {
      this.addEvent({type: "owner-args", args: this._ownerArgs, at: Date.now()});
      delete this._ownerArgs;
    }
  },

  afterTask: function() {
    delete this._events;
    // we only keep eventMap in the errored zone only
    if(!this.erroredStack) {
      delete this.eventMap;
    }
  },

  addEvent: function(event) {
    // when zone completed _events will be removed
    // but actions may happen even after the zone completed
    // and we are not interested about those
    if(this._events) {
      this._events.push(event);
    }
  },

  // we can add it the zone direcly, because zone can be run many times
  // we can't add this as a event yet, since zone doesn't started yet
  // so we'll add this to a special fields and it's will added to the _events
  // when _events will be creating
  setOwnerArgs: function(args) {
    this._ownerArgs = args;
  },

  setOwner: function(ownerInfo) {
    this.owner = ownerInfo;
  },

  // validate and pick arguments
  // we don't need to capture event object as the argument
  // (then we can't to JSON stringify)
  // That's why we've this
  bind: function (func, skipEnqueue, ownerInfo, validateArgs) {
    validateArgs = validateArgs || function() {return []};
    skipEnqueue || this.enqueueTask(func);
    var zone = this.fork();

    if(ownerInfo) {
      zone.setOwner(ownerInfo);
      ownerInfo.zoneId = zone.id;
      this.addEvent(ownerInfo);
    }

    return function zoneBoundFn() {
      if(ownerInfo) {
        zone.setOwnerArgs(validateArgs(this, arguments));
      }
      return zone.run(func, this, arguments);
    };
  },

  bindOnce: function (func, ownerInfo, validateArgs) {
    var boundZone = this;
    return this.bind(function() {
      var result = func.apply(this, arguments);
      boundZone.dequeueTask(func);
      return result;
    }, false, ownerInfo, validateArgs);
  }
});

/**
 * Create a stack trace
 */

function getStacktrace () {
  var stack = getStacktraceWithUncaughtError();
  if (stack && stack._e.stack) {
    getStacktrace = getStacktraceWithUncaughtError;
    return stack;
  } else {
    getStacktrace = getStacktraceWithCaughtError;
    return getStacktrace();
  }
};

function getStacktraceWithUncaughtError () {
  return new Stacktrace(new Error());
}

function getStacktraceWithCaughtError () {
  try {
    throw new Error();
  } catch (e) {
    return new Stacktrace(e);
  }
}

/*
 * Wrapped stacktrace
 *
 * We need this because in some implementations, constructing a trace is slow
 * and so we want to defer accessing the trace for as long as possible
 */

function Stacktrace (e) {
  this._e = e;
}

Stacktrace.prototype.get = function() {
  return this._e.stack
    .split('\n')
    .filter(this.stackFramesFilter)
    .join('\n');
};

Stacktrace.prototype.stackFramesFilter = function(line) {
  var filterRegExp = /\/packages\/zones\/assets\/|^Error$/;
  return !line.match(filterRegExp);
};
<commit_msg>explictely check for the error and stack<commit_after>nextZoneId = function() {
  var zoneIds = 0;
  return function () {
    return zoneIds++;
  };
}();

extendZone = function(fields) {
  for(var key in fields) {
    Zone.prototype[key] = fields[key];
  }
};

// extendZone with our own functionality

extendZone({
  _fork: Zone.prototype.fork,

  onError: function (e) {
    this.erroredStack = new Stacktrace(e);
    Zone.Reporters.run(this);
  },

  fork: function (locals) {
    var zone = this._fork(locals);
    zone.currentStack = getStacktrace();
    zone.createdAt = Date.now();
    zone.id = nextZoneId();

    // when creating a new zone, it will use's parent zone as __proto__
    // that's why we can access ancesstor properties
    // but we are deleting eventMap just after zone ran
    // so, we need to create eventMap explicitely to stay it in the current zone
    zone.eventMap = zone.eventMap;

    // make sure owner doesn't get inherited
    zone.owner = undefined;
    return zone;
  },

  beforeTask: function() {
    this.runAt = Date.now();

    // create eventMap for the first time
    // eventMap will be deleted just after zone completed
    // but it will be available only in the errroed zone
    // so, in that zone, someone can access all the events happened on the
    // async call stack
    if(!this.eventMap) {
      this.eventMap = {};
    }

    // _events will only be available during the zone running time only
    // an event can be run multiple times. So we can't maintain the events
    // in this array forever.
    // best option is to add it to eventMap, which carries events to the
    // top of the stack
    this._events = [];
    this.eventMap[this.id] = this._events;

    // if there is _ownerArgs we need to add it as an event
    // after that we don't need to _ownerArgs
    if(this._ownerArgs) {
      this.addEvent({type: "owner-args", args: this._ownerArgs, at: Date.now()});
      delete this._ownerArgs;
    }
  },

  afterTask: function() {
    delete this._events;
    // we only keep eventMap in the errored zone only
    if(!this.erroredStack) {
      delete this.eventMap;
    }
  },

  addEvent: function(event) {
    // when zone completed _events will be removed
    // but actions may happen even after the zone completed
    // and we are not interested about those
    if(this._events) {
      this._events.push(event);
    }
  },

  // we can add it the zone direcly, because zone can be run many times
  // we can't add this as a event yet, since zone doesn't started yet
  // so we'll add this to a special fields and it's will added to the _events
  // when _events will be creating
  setOwnerArgs: function(args) {
    this._ownerArgs = args;
  },

  setOwner: function(ownerInfo) {
    this.owner = ownerInfo;
  },

  // validate and pick arguments
  // we don't need to capture event object as the argument
  // (then we can't to JSON stringify)
  // That's why we've this
  bind: function (func, skipEnqueue, ownerInfo, validateArgs) {
    validateArgs = validateArgs || function() {return []};
    skipEnqueue || this.enqueueTask(func);
    var zone = this.fork();

    if(ownerInfo) {
      zone.setOwner(ownerInfo);
      ownerInfo.zoneId = zone.id;
      this.addEvent(ownerInfo);
    }

    return function zoneBoundFn() {
      if(ownerInfo) {
        zone.setOwnerArgs(validateArgs(this, arguments));
      }
      return zone.run(func, this, arguments);
    };
  },

  bindOnce: function (func, ownerInfo, validateArgs) {
    var boundZone = this;
    return this.bind(function() {
      var result = func.apply(this, arguments);
      boundZone.dequeueTask(func);
      return result;
    }, false, ownerInfo, validateArgs);
  }
});

/**
 * Create a stack trace
 */

function getStacktrace () {
  var stack = getStacktraceWithUncaughtError();
  if (stack && stack._e.stack) {
    getStacktrace = getStacktraceWithUncaughtError;
    return stack;
  } else {
    getStacktrace = getStacktraceWithCaughtError;
    return getStacktrace();
  }
};

function getStacktraceWithUncaughtError () {
  return new Stacktrace(new Error());
}

function getStacktraceWithCaughtError () {
  try {
    throw new Error();
  } catch (e) {
    return new Stacktrace(e);
  }
}

/*
 * Wrapped stacktrace
 *
 * We need this because in some implementations, constructing a trace is slow
 * and so we want to defer accessing the trace for as long as possible
 */

function Stacktrace (e) {
  this._e = e;
}

Stacktrace.prototype.get = function() {
  if(this._e && typeof this._e.stack == 'string') {
    return this._e.stack
      .split('\n')
      .filter(this.stackFramesFilter)
      .join('\n');
  } else {
    return "";
  }
};

Stacktrace.prototype.stackFramesFilter = function(line) {
  var filterRegExp = /\/packages\/zones\/assets\/|^Error$/;
  return !line.match(filterRegExp);
};
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var browserify = require('browserify');
var babelify = require('babelify');
// var mocha = require('gulp-mocha');
var through2 = require('through2');

gulp.task('bundle', function () {
  // return bundler.bundle()
          // .pipe(gulp.dest('./client/public/scripts'));
  return gulp
    .src('./server/client/index.js')
    .pipe(through2.obj(function (file, enc, next) {
      browserify(file.path, {debug : true})
        .transform(babelify)
        .bundle(function (err, res) {
          if (err) {
            return next(err);
          }
          file.contents = res;
          next(null, file);
        });
    }))
    .pipe(gulp.dest('./server/client/public/scripts'));
});

gulp.task('test', function (){
  return gulp.src('./specs/serverspecs/*.spec.js')

});

// gulp.task('testClient', function () {
//   return gulp.src('./specs/clientspecs/*.spec.js')
//   .transform(babelify)

// });
<commit_msg>Add watch task to gulp<commit_after>'use strict';

var gulp = require('gulp');
var sourcemaps = require('gulp-sourcemaps');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var browserify = require('browserify');
var watchify = require('watchify');
var babelify = require('babelify');

var mocha = require('gulp-mocha');
var eslint = require('gulp-eslint');

function compile(watch) {
  var bundler = watchify(browserify('./server/client/index.js', { debug: true }).transform(babelify));

  function rebundle() {
    bundler.bundle()
      .on('error', function(err) { console.error(err); this.emit('end'); })
      .pipe(source('build.js'))
      .pipe(buffer())
      .pipe(sourcemaps.init({ loadMaps: true }))
      .pipe(sourcemaps.write('./'))
      .pipe(gulp.dest('./server/client/public/scripts'));
  }

  if (watch) {
    bundler.on('update', function() {
      console.log('-> bundling...');
      rebundle();
    });
  }

  rebundle();
}

function watch() {
  return compile(true);
};

gulp.task('bundle', function() { return compile(); });
gulp.task('watch', function() { return watch(); });

gulp.task('default', ['watch']);

gulp.task('mocha', function () {
  return gulp.src('./specs/serverspecs/**/*.spec.js')
    .pipe(mocha({reporter: 'spec'}))
    .once('end', function () {
      process.exit();
    });
});

gulp.task('lint', function () {
  return gulp.src(['server/**/*.js', '!server/client/public/scripts/index.js'])
      .pipe(eslint())
      .pipe(eslint.format())
      // .pipe(eslint.failOnError());
});

gulp.task('test', ['mocha', 'lint']);
<|endoftext|>


<commit_before>$( document ).ready(function(){

  $("input").attr("maxlength", 1);

  var matrix = undefined;
  var dimension = undefined;
  var letters = [];
  var words = [];
  var alphabet = 'abcdefghijklmnopqrstuvwxyz';
  var dict_en = {};

  // fetch English dictionary
  $.get('/dict_en', null, function(response){
    dict_en = response;
    $('#finder').removeAttr('disabled');
  });

  $("#ramdomizer").click(function(event){
    $('.results').hide();
    $.makeArray($('input')).forEach(function(el){
      var random = Math.ceil( (Math.random() * 25) );
      $(el).val( alphabet[random] );
    });
  });

  $("#finder").click(function(event){
    timer.start();

    // can't have it working properly :(
    // $('.loading').show();

    // build matrix of all letters
    letters = jQuery.makeArray($('input')).map(function(el){
      return $(el).val();
    });
    dimension = Math.sqrt( letters.length );
    matrix = new Array(dimension);
    for(var i=0; i < dimension; i++){
      matrix[i] = new Array(dimension);
      for(var j=0; j < dimension; j++){
        matrix[i][j] = letters[j*dimension + i];
      }
    }

    // find all possible letter combinations
    words = [];
    for(i = 0; i < dimension; i++){
      for(j = 0; j < dimension; j++){
        spread( new Word([[i, j]]) );
      }
    }

    // max of 5-letter words for now (otherwise too slow)
    for(i = 0; i < 3; i++){
      words.forEach(function(e){
        spread(e);
      });
    }

    // only keep words of a certain length
    words = words.filter(function(w){
      return w.longEnough();
    });

    // removes dupes
    var lot = [];
    words = words.filter(function(item) {
      item.letterize();
      if (lot.indexOf(item.letters) == -1){
        lot.push(item.letters);
        return true;
      }else{
        return false;
      }
    });

    // filter existing words
    words = words.filter(function(item) {
      return dict_en.indexOf(item.letters) != -1;
    });

    // sort words list
    words = words.sort(function(item1, item2){
      if ( item1.letters > item2.letters ){
        return 1;
      }else{
        return -1;
      }
    });

    $('.results').show();
    $('.results h2').html( 'Words found: ' + words.length );
    $('.words').empty();
    var list = $('.words');
    var count = words.length;
    words.forEach(function(word){
      list.append("" + word.letters + '');
      words.indexOf(word) == (count - 1) ? list.append('.') : list.append(', ');
    });
    timer.stop();
    $('.benchmark').html('Results found in: ' + timer.getTime() + ' ms');
  });

  $('.words').on('mouseenter', 'span', function(event){
    var el = $(event.target);
    el.addClass('highlight-word');
    var positions = el.data('positions').toString();
    var inputs = $('input');
    var length = positions.length;
    for(var i=0; i<length; i+=2){
      $(inputs[parseInt(positions[i], 10) + 5 * parseInt(positions[i+1], 10)]).addClass('highlight-letter');
    }
  });
  $('.words').on('mouseleave', 'span', function(event){
    var el = $(event.target);
    el.removeClass('highlight-word');
    var positions = el.data('positions').toString();
    var inputs = $('input');
    var length = positions.length;
    for(var i=0; i<length; i+=2){
      $(inputs[parseInt(positions[i], 10) + 5 * parseInt(positions[i+1], 10)]).removeClass('highlight-letter');
    }
  });

  function spread(word){
    var directions = ['up', 'up-right', 'right', 'right-down', 'down', 'down-left', 'left', 'left-up'];
    directions.forEach(function(d){
      var candidate = move( new Word(word.positions), d );
      if( candidate != undefined ){
        words.push( candidate );
      }
    });
  }

  function move(word, move){
    var current_position = word.positions[word.positions.length - 1];
    if (move === 'up'){
      new_position = [current_position[0], current_position[1] - 1];
      if(new_position[1] > -1 && !word.beenThere(new_position)){
        word.positions.push(new_position);
        return word;
      }
    }
    if (move === 'up-right'){
      new_position = [current_position[0] + 1, current_position[1] - 1];
      if(new_position[1] > -1 && new_position[0] < dimension && !word.beenThere(new_position)){
        word.positions.push(new_position);
        return word;
      }
    }
    if ( move === 'right' ){
      new_position = [current_position[0] + 1, current_position[1]];
      if(new_position[0] < dimension && !word.beenThere(new_position)){
        word.positions.push(new_position);
        return word;
      }
    }
    if ( move === 'right-down' ){
      new_position = [current_position[0] + 1, current_position[1] + 1];
      if(new_position[0] < dimension && new_position[1] < dimension && !word.beenThere(new_position)){
        word.positions.push(new_position);
        return word;
      }
    }
    if (move === 'down'){
      new_position = [current_position[0], current_position[1] + 1];
      if(new_position[1] < dimension && !word.beenThere(new_position)){
        word.positions.push(new_position);
        return word;
      }
    }
    if (move === 'down-left'){
      new_position = [current_position[0] - 1, current_position[1] + 1];
      if(new_position[1] < dimension && new_position[0] > -1 && !word.beenThere(new_position)){
        word.positions.push(new_position);
        return word;
      }
    }
    if ( move === 'left' ){
      new_position = [current_position[0] - 1, current_position[1]];
      if(new_position[0] > -1 && !word.beenThere(new_position)){
        word.positions.push(new_position);
        return word;
      }
    }
    if ( move === 'left-up' ){
      new_position = [current_position[0] - 1, current_position[1] - 1];
      if(new_position[0] > -1 && new_position[1] > -1 && !word.beenThere(new_position)){
        word.positions.push(new_position);
        return word;
      }
    }
    return undefined;
  }

  function Word(positions){
    this.positions = positions.slice(0);
    this.letters = '';
    this.addPosition = function(position){
      this.positions.push(position);
    };
    this.letterize = function(){
      var chars = this.positions.map(function(e){
        return matrix[e[0]][e[1]];
      });
      this.letters = chars.join('');
    };
    this.beenThere = function(position){
      var found = false;
      this.positions.forEach(function(e){
        if(e[0] == position[0] && e[1] == position[1]){
          found = true;
        }
      });
      return found;
    };
    this.longEnough = function(){
      return this.positions.length > 2;
    };
    return this;
  }

  var timer = {
    startedAt: null,
    stoppedAt: null,
    start: function () {
      this.stoppedAt = null;
      this.startedAt = new Date();
    },
    stop: function () {
      this.stoppedAt = new Date();
    },
    getTime: function () {
      if (!this.stoppedAt) { this.stop(); }
      return this.stoppedAt.getTime() - this.startedAt.getTime();
    }
  };

});
<commit_msg>sets a limit of 4 letters per word (otherwise too slow)<commit_after>$( document ).ready(function(){

  $("input").attr("maxlength", 1);

  var matrix = undefined;
  var dimension = undefined;
  var letters = [];
  var words = [];
  var alphabet = 'abcdefghijklmnopqrstuvwxyz';
  var dict_en = {};

  // fetch English dictionary
  $.get('/dict_en', null, function(response){
    dict_en = response;
    $('#finder').removeAttr('disabled');
  });

  $("#ramdomizer").click(function(event){
    $('.results').hide();
    $.makeArray($('input')).forEach(function(el){
      var random = Math.ceil( (Math.random() * 25) );
      $(el).val( alphabet[random] );
    });
  });

  $("#finder").click(function(event){
    timer.start();

    // can't have it working properly :(
    // $('.loading').show();

    // build matrix of all letters
    letters = jQuery.makeArray($('input')).map(function(el){
      return $(el).val();
    });
    dimension = Math.sqrt( letters.length );
    matrix = new Array(dimension);
    for(var i=0; i < dimension; i++){
      matrix[i] = new Array(dimension);
      for(var j=0; j < dimension; j++){
        matrix[i][j] = letters[j*dimension + i];
      }
    }

    // find all possible letter combinations
    words = [];
    for(i = 0; i < dimension; i++){
      for(j = 0; j < dimension; j++){
        spread( new Word([[i, j]]) );
      }
    }

    // max of 4-letter words for now (otherwise too slow)
    for(i = 0; i < 2; i++){
      words.forEach(function(e){
        spread(e);
      });
    }

    // only keep words of a certain length
    words = words.filter(function(w){
      return w.longEnough();
    });

    // removes dupes
    var lot = [];
    words = words.filter(function(item) {
      item.letterize();
      if (lot.indexOf(item.letters) == -1){
        lot.push(item.letters);
        return true;
      }else{
        return false;
      }
    });

    // filter existing words
    words = words.filter(function(item) {
      return dict_en.indexOf(item.letters) != -1;
    });

    // sort words list
    words = words.sort(function(item1, item2){
      if ( item1.letters > item2.letters ){
        return 1;
      }else{
        return -1;
      }
    });

    $('.results').show();
    $('.results h2').html( 'Words found: ' + words.length );
    $('.words').empty();
    var list = $('.words');
    var count = words.length;
    words.forEach(function(word){
      list.append("" + word.letters + '');
      words.indexOf(word) == (count - 1) ? list.append('.') : list.append(', ');
    });
    timer.stop();
    $('.benchmark').html('Results found in: ' + timer.getTime() + ' ms');
  });

  $('.words').on('mouseenter', 'span', function(event){
    var el = $(event.target);
    el.addClass('highlight-word');
    var positions = el.data('positions').toString();
    var inputs = $('input');
    var length = positions.length;
    for(var i=0; i<length; i+=2){
      $(inputs[parseInt(positions[i], 10) + 5 * parseInt(positions[i+1], 10)]).addClass('highlight-letter');
    }
  });
  $('.words').on('mouseleave', 'span', function(event){
    var el = $(event.target);
    el.removeClass('highlight-word');
    var positions = el.data('positions').toString();
    var inputs = $('input');
    var length = positions.length;
    for(var i=0; i<length; i+=2){
      $(inputs[parseInt(positions[i], 10) + 5 * parseInt(positions[i+1], 10)]).removeClass('highlight-letter');
    }
  });

  function spread(word){
    var directions = ['up', 'up-right', 'right', 'right-down', 'down', 'down-left', 'left', 'left-up'];
    directions.forEach(function(d){
      var candidate = move( new Word(word.positions), d );
      if( candidate != undefined ){
        words.push( candidate );
      }
    });
  }

  function move(word, move){
    var current_position = word.positions[word.positions.length - 1];
    if (move === 'up'){
      new_position = [current_position[0], current_position[1] - 1];
      if(new_position[1] > -1 && !word.beenThere(new_position)){
        word.positions.push(new_position);
        return word;
      }
    }
    if (move === 'up-right'){
      new_position = [current_position[0] + 1, current_position[1] - 1];
      if(new_position[1] > -1 && new_position[0] < dimension && !word.beenThere(new_position)){
        word.positions.push(new_position);
        return word;
      }
    }
    if ( move === 'right' ){
      new_position = [current_position[0] + 1, current_position[1]];
      if(new_position[0] < dimension && !word.beenThere(new_position)){
        word.positions.push(new_position);
        return word;
      }
    }
    if ( move === 'right-down' ){
      new_position = [current_position[0] + 1, current_position[1] + 1];
      if(new_position[0] < dimension && new_position[1] < dimension && !word.beenThere(new_position)){
        word.positions.push(new_position);
        return word;
      }
    }
    if (move === 'down'){
      new_position = [current_position[0], current_position[1] + 1];
      if(new_position[1] < dimension && !word.beenThere(new_position)){
        word.positions.push(new_position);
        return word;
      }
    }
    if (move === 'down-left'){
      new_position = [current_position[0] - 1, current_position[1] + 1];
      if(new_position[1] < dimension && new_position[0] > -1 && !word.beenThere(new_position)){
        word.positions.push(new_position);
        return word;
      }
    }
    if ( move === 'left' ){
      new_position = [current_position[0] - 1, current_position[1]];
      if(new_position[0] > -1 && !word.beenThere(new_position)){
        word.positions.push(new_position);
        return word;
      }
    }
    if ( move === 'left-up' ){
      new_position = [current_position[0] - 1, current_position[1] - 1];
      if(new_position[0] > -1 && new_position[1] > -1 && !word.beenThere(new_position)){
        word.positions.push(new_position);
        return word;
      }
    }
    return undefined;
  }

  function Word(positions){
    this.positions = positions.slice(0);
    this.letters = '';
    this.addPosition = function(position){
      this.positions.push(position);
    };
    this.letterize = function(){
      var chars = this.positions.map(function(e){
        return matrix[e[0]][e[1]];
      });
      this.letters = chars.join('');
    };
    this.beenThere = function(position){
      var found = false;
      this.positions.forEach(function(e){
        if(e[0] == position[0] && e[1] == position[1]){
          found = true;
        }
      });
      return found;
    };
    this.longEnough = function(){
      return this.positions.length > 2;
    };
    return this;
  }

  var timer = {
    startedAt: null,
    stoppedAt: null,
    start: function () {
      this.stoppedAt = null;
      this.startedAt = new Date();
    },
    stop: function () {
      this.stoppedAt = new Date();
    },
    getTime: function () {
      if (!this.stoppedAt) { this.stop(); }
      return this.stoppedAt.getTime() - this.startedAt.getTime();
    }
  };

});
<|endoftext|>


<commit_before>(function(global){"use strict";var _Base64=global.Base64;var version="2.3.2";var buffer;if(typeof module!=="undefined"&&module.exports){try{buffer=require("buffer").Buffer}catch(err){}}var b64chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";var b64tab=function(bin){var t={};for(var i=0,l=bin.length;i<l;i++)t[bin.charAt(i)]=i;return t}(b64chars);var fromCharCode=String.fromCharCode;var cb_utob=function(c){if(c.length<2){var cc=c.charCodeAt(0);return cc<128?c:cc<2048?fromCharCode(192|cc>>>6)+fromCharCode(128|cc&63):fromCharCode(224|cc>>>12&15)+fromCharCode(128|cc>>>6&63)+fromCharCode(128|cc&63)}else{var cc=65536+(c.charCodeAt(0)-55296)*1024+(c.charCodeAt(1)-56320);return fromCharCode(240|cc>>>18&7)+fromCharCode(128|cc>>>12&63)+fromCharCode(128|cc>>>6&63)+fromCharCode(128|cc&63)}};var re_utob=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g;var utob=function(u){return u.replace(re_utob,cb_utob)};var cb_encode=function(ccc){var padlen=[0,2,1][ccc.length%3],ord=ccc.charCodeAt(0)<<16|(ccc.length>1?ccc.charCodeAt(1):0)<<8|(ccc.length>2?ccc.charCodeAt(2):0),chars=[b64chars.charAt(ord>>>18),b64chars.charAt(ord>>>12&63),padlen>=2?"=":b64chars.charAt(ord>>>6&63),padlen>=1?"=":b64chars.charAt(ord&63)];return chars.join("")};var btoa=global.btoa?function(b){return global.btoa(b)}:function(b){return b.replace(/[\s\S]{1,3}/g,cb_encode)};var _encode=buffer?buffer.from&&buffer.from!==Uint8Array.from?function(u){return(u.constructor===buffer.constructor?u:buffer.from(u)).toString("base64")}:function(u){return(u.constructor===buffer.constructor?u:new buffer(u)).toString("base64")}:function(u){return btoa(utob(u))};var encode=function(u,urisafe){return!urisafe?_encode(String(u)):_encode(String(u)).replace(/[+\/]/g,function(m0){return m0=="+"?"-":"_"}).replace(/=/g,"")};var encodeURI=function(u){return encode(u,true)};var re_btou=new RegExp(["[À-ß][-¿]","[à-ï][-¿]{2}","[ð-÷][-¿]{3}"].join("|"),"g");var cb_btou=function(cccc){switch(cccc.length){case 4:var cp=(7&cccc.charCodeAt(0))<<18|(63&cccc.charCodeAt(1))<<12|(63&cccc.charCodeAt(2))<<6|63&cccc.charCodeAt(3),offset=cp-65536;return fromCharCode((offset>>>10)+55296)+fromCharCode((offset&1023)+56320);case 3:return fromCharCode((15&cccc.charCodeAt(0))<<12|(63&cccc.charCodeAt(1))<<6|63&cccc.charCodeAt(2));default:return fromCharCode((31&cccc.charCodeAt(0))<<6|63&cccc.charCodeAt(1))}};var btou=function(b){return b.replace(re_btou,cb_btou)};var cb_decode=function(cccc){var len=cccc.length,padlen=len%4,n=(len>0?b64tab[cccc.charAt(0)]<<18:0)|(len>1?b64tab[cccc.charAt(1)]<<12:0)|(len>2?b64tab[cccc.charAt(2)]<<6:0)|(len>3?b64tab[cccc.charAt(3)]:0),chars=[fromCharCode(n>>>16),fromCharCode(n>>>8&255),fromCharCode(n&255)];chars.length-=[0,0,2,1][padlen];return chars.join("")};var atob=global.atob?function(a){return global.atob(a)}:function(a){return a.replace(/[\s\S]{1,4}/g,cb_decode)};var _decode=buffer?buffer.from&&buffer.from!==Uint8Array.from?function(a){return(a.constructor===buffer.constructor?a:buffer.from(a,"base64")).toString()}:function(a){return(a.constructor===buffer.constructor?a:new buffer(a,"base64")).toString()}:function(a){return btou(atob(a))};var decode=function(a){return _decode(String(a).replace(/[-_]/g,function(m0){return m0=="-"?"+":"/"}).replace(/[^A-Za-z0-9\+\/]/g,""))};var noConflict=function(){var Base64=global.Base64;global.Base64=_Base64;return Base64};global.Base64={VERSION:version,atob:atob,btoa:btoa,fromBase64:decode,toBase64:encode,utob:utob,encode:encode,encodeURI:encodeURI,btou:btou,decode:decode,noConflict:noConflict};if(typeof Object.defineProperty==="function"){var noEnum=function(v){return{value:v,enumerable:false,writable:true,configurable:true}};global.Base64.extendString=function(){Object.defineProperty(String.prototype,"fromBase64",noEnum(function(){return decode(this)}));Object.defineProperty(String.prototype,"toBase64",noEnum(function(urisafe){return encode(this,urisafe)}));Object.defineProperty(String.prototype,"toBase64URI",noEnum(function(){return encode(this,true)}))}}if(global["Meteor"]){Base64=global.Base64}if(typeof module!=="undefined"&&module.exports){module.exports.Base64=global.Base64}else if(typeof define==="function"&&define.amd){define([],function(){return global.Base64})}})(typeof self!=="undefined"?self:typeof window!=="undefined"?window:typeof global!=="undefined"?global:this);<commit_msg>generate base64.min.js<commit_after>(function(global,factory){typeof exports==="object"&&typeof module!=="undefined"?module.exports=factory(global):typeof define==="function"&&define.amd?define(factory):global.moment=factory(global)}((typeof self!=="undefined"?self:typeof window!=="undefined"?window:typeof global!=="undefined"?global:this),function(global){var _Base64=global.Base64;var version="2.3.2";var buffer;if(typeof module!=="undefined"&&module.exports){try{buffer=require("buffer").Buffer}catch(err){}}var b64chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";var b64tab=function(bin){var t={};for(var i=0,l=bin.length;i<l;i++){t[bin.charAt(i)]=i}return t}(b64chars);var fromCharCode=String.fromCharCode;var cb_utob=function(c){if(c.length<2){var cc=c.charCodeAt(0);return cc<128?c:cc<2048?(fromCharCode(192|(cc>>>6))+fromCharCode(128|(cc&63))):(fromCharCode(224|((cc>>>12)&15))+fromCharCode(128|((cc>>>6)&63))+fromCharCode(128|(cc&63)))}else{var cc=65536+(c.charCodeAt(0)-55296)*1024+(c.charCodeAt(1)-56320);return(fromCharCode(240|((cc>>>18)&7))+fromCharCode(128|((cc>>>12)&63))+fromCharCode(128|((cc>>>6)&63))+fromCharCode(128|(cc&63)))}};var re_utob=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g;var utob=function(u){return u.replace(re_utob,cb_utob)};var cb_encode=function(ccc){var padlen=[0,2,1][ccc.length%3],ord=ccc.charCodeAt(0)<<16|((ccc.length>1?ccc.charCodeAt(1):0)<<8)|((ccc.length>2?ccc.charCodeAt(2):0)),chars=[b64chars.charAt(ord>>>18),b64chars.charAt((ord>>>12)&63),padlen>=2?"=":b64chars.charAt((ord>>>6)&63),padlen>=1?"=":b64chars.charAt(ord&63)];return chars.join("")};var btoa=global.btoa?function(b){return global.btoa(b)}:function(b){return b.replace(/[\s\S]{1,3}/g,cb_encode)};var _encode=buffer?buffer.from&&buffer.from!==Uint8Array.from?function(u){return(u.constructor===buffer.constructor?u:buffer.from(u)).toString("base64")}:function(u){return(u.constructor===buffer.constructor?u:new buffer(u)).toString("base64")}:function(u){return btoa(utob(u))};var encode=function(u,urisafe){return !urisafe?_encode(String(u)):_encode(String(u)).replace(/[+\/]/g,function(m0){return m0=="+"?"-":"_"}).replace(/=/g,"")};var encodeURI=function(u){return encode(u,true)};var re_btou=new RegExp(["[\xC0-\xDF][\x80-\xBF]","[\xE0-\xEF][\x80-\xBF]{2}","[\xF0-\xF7][\x80-\xBF]{3}"].join("|"),"g");var cb_btou=function(cccc){switch(cccc.length){case 4:var cp=((7&cccc.charCodeAt(0))<<18)|((63&cccc.charCodeAt(1))<<12)|((63&cccc.charCodeAt(2))<<6)|(63&cccc.charCodeAt(3)),offset=cp-65536;return(fromCharCode((offset>>>10)+55296)+fromCharCode((offset&1023)+56320));case 3:return fromCharCode(((15&cccc.charCodeAt(0))<<12)|((63&cccc.charCodeAt(1))<<6)|(63&cccc.charCodeAt(2)));default:return fromCharCode(((31&cccc.charCodeAt(0))<<6)|(63&cccc.charCodeAt(1)))}};var btou=function(b){return b.replace(re_btou,cb_btou)};var cb_decode=function(cccc){var len=cccc.length,padlen=len%4,n=(len>0?b64tab[cccc.charAt(0)]<<18:0)|(len>1?b64tab[cccc.charAt(1)]<<12:0)|(len>2?b64tab[cccc.charAt(2)]<<6:0)|(len>3?b64tab[cccc.charAt(3)]:0),chars=[fromCharCode(n>>>16),fromCharCode((n>>>8)&255),fromCharCode(n&255)];chars.length-=[0,0,2,1][padlen];return chars.join("")};var atob=global.atob?function(a){return global.atob(a)}:function(a){return a.replace(/[\s\S]{1,4}/g,cb_decode)};var _decode=buffer?buffer.from&&buffer.from!==Uint8Array.from?function(a){return(a.constructor===buffer.constructor?a:buffer.from(a,"base64")).toString()}:function(a){return(a.constructor===buffer.constructor?a:new buffer(a,"base64")).toString()}:function(a){return btou(atob(a))};var decode=function(a){return _decode(String(a).replace(/[-_]/g,function(m0){return m0=="-"?"+":"/"}).replace(/[^A-Za-z0-9\+\/]/g,""))};var noConflict=function(){var Base64=global.Base64;global.Base64=_Base64;return Base64};global.Base64={VERSION:version,atob:atob,btoa:btoa,fromBase64:decode,toBase64:encode,utob:utob,encode:encode,encodeURI:encodeURI,btou:btou,decode:decode,noConflict:noConflict};if(typeof Object.defineProperty==="function"){var noEnum=function(v){return{value:v,enumerable:false,writable:true,configurable:true}};global.Base64.extendString=function(){Object.defineProperty(String.prototype,"fromBase64",noEnum(function(){return decode(this)}));Object.defineProperty(String.prototype,"toBase64",noEnum(function(urisafe){return encode(this,urisafe)}));Object.defineProperty(String.prototype,"toBase64URI",noEnum(function(){return encode(this,true)}))}}if(global["Meteor"]){Base64=global.Base64}if(typeof module!=="undefined"&&module.exports){module.exports.Base64=global.Base64}else{if(typeof define==="function"&&define.amd){define([],function(){return global.Base64})}}return{Base64:global.Base64}}));<|endoftext|>


<commit_before>var facetsDef = [
    {
        name: 'type',
        label: 'Type de résultat',
        valueLabels: {
            dataset: 'Jeu de données',
            service: 'Service',
            map: 'Carte',
            other: 'Autre',
            none: 'Non renseigné'
        }
    },
    {
        name: 'representationType',
        label: 'Type de donnée',
        valueLabels: {
            vector: 'Vecteur',
            grid: 'Imagerie / Raster',
            other: 'Autre',
            none: 'Non renseigné'
        }
    },
    {
        name: 'opendata',
        label: 'Donnée ouverte',
        valueLabels: {
            yes: 'Oui',
            'not-determined': 'Indéterminé'
        }
    },
    {
        name: 'availability',
        label: 'Disponibilité',
        valueLabels: {
            yes: 'Oui',
            'not-determined': 'Indéterminé'
        }
    },
    {
        name: 'organization',
        label: 'Organismes'
    },
    {
        name: 'keyword',
        label: 'Mot-clés'
    },
    {
        name: 'distributionFormat',
        label: 'Format de distribution',
        valueLabels: {
            'wfs-featureType': 'WFS',
            'file-package': 'Package fichier'
        }
    }
];

angular.module('mainApp').controller('ServiceRecords', function ($scope, $http, $location, $stateParams) {
    function buildQueryString() {
        if (!$scope.datasets) {
            return _.pick($stateParams, 'organization', 'keyword', 'type', 'representationType', 'opendata', 'availability', 'distributionFormat', 'q', 'offset');
        } else {
            var qs = {};
            $scope.activeFacets.forEach(function (activeFacet) {
                if (!qs[activeFacet.name]) qs[activeFacet.name] = [];
                qs[activeFacet.name].push(activeFacet.value);
            });

            qs.q = $scope.q;
            qs.offset = $scope.offset;

            return qs;
        }
    }

    $scope.fetchDatasets = function() {
        $http
            .get('/api/geogw/services/' + $scope.currentService._id + '/datasets', { params: buildQueryString() })
            .success(function(data) {
                $scope.datasets = data.results;
                $scope.count = data.count;
                $scope.offset = data.query.offset;
                $scope.firstResultPos = data.query.offset + 1;
                $scope.lastResultPos = data.query.offset + data.results.length;
                $scope.activeFacets = data.query.facets;
                $scope.computeFacets(data.facets);
            });
    };

    $scope.computeFacets = function (facets) {
        $scope.facets = _.map(facetsDef, function(def) {
            return { name: def.name, label: def.label, values: facets[def.name], valueLabels: def.valueLabels };
        });
    };

    $scope.updateResults = function (paginate) {
        if (!paginate) $scope.offset = null;
        $location.search(buildQueryString());
        $scope.fetchDatasets();
    };

    $scope.hasPreviousResults = function() {
        return $scope.datasets && ($scope.offset > 0);
    };

    $scope.hasNextResults = function() {
        return $scope.datasets && ($scope.offset + $scope.datasets.length < $scope.count);
    };

    $scope.paginatePrevious = function() {
        $scope.offset = $scope.offset - 20;
        $scope.updateResults(true);
    };

    $scope.paginateNext = function() {
        $scope.offset = $scope.offset + 20;
        $scope.updateResults(true);
    };

    $scope.toggleFacet = function (facet) {
        if (!$scope.facetIsActive(facet)) {
            $scope.activeFacets.push(facet);
        } else {
            _.remove($scope.activeFacets, facet);
        }
        $scope.updateResults();
    };

    $scope.facetIsActive = function (facet) {
        return _.find($scope.activeFacets, facet);
    };

    $scope.applyFacet = function (facet) {
        $scope.activeFacets = [facet];
        $scope.updateResults();
    };

    $scope.encodeURIComponent = encodeURIComponent;

    $scope.$watch('q', $scope.updateResults, true);
    $scope.fetchDatasets();
});
<commit_msg>Update search API usage<commit_after>var facetsDef = [
    {
        name: 'type',
        label: 'Type de résultat',
        valueLabels: {
            dataset: 'Jeu de données',
            service: 'Service',
            map: 'Carte',
            other: 'Autre',
            none: 'Non renseigné'
        }
    },
    {
        name: 'representationType',
        label: 'Type de donnée',
        valueLabels: {
            vector: 'Vecteur',
            grid: 'Imagerie / Raster',
            other: 'Autre',
            none: 'Non renseigné'
        }
    },
    {
        name: 'opendata',
        label: 'Donnée ouverte',
        valueLabels: {
            yes: 'Oui',
            'not-determined': 'Indéterminé'
        }
    },
    {
        name: 'availability',
        label: 'Disponibilité',
        valueLabels: {
            yes: 'Oui',
            'not-determined': 'Indéterminé'
        }
    },
    {
        name: 'organization',
        label: 'Organismes'
    },
    {
        name: 'keyword',
        label: 'Mot-clés'
    },
    {
        name: 'catalog',
        label: 'Catalogue'
    },
    {
        name: 'distributionFormat',
        label: 'Format de distribution',
        valueLabels: {
            'wfs-featureType': 'WFS',
            'file-package': 'Package fichier'
        }
    }
];

angular.module('mainApp').controller('ServiceRecords', function ($scope, $http, $location, $stateParams) {
    function buildQueryString() {
        if (!$scope.datasets) {
            return _.pick($stateParams, 'organization', 'keyword', 'type', 'representationType', 'opendata', 'availability', 'distributionFormat', 'q', 'offset');
        } else {
            var qs = {};
            $scope.activeFacets.forEach(function (activeFacet) {
                if (!qs[activeFacet.name]) qs[activeFacet.name] = [];
                qs[activeFacet.name].push(activeFacet.value);
            });

            qs.q = $scope.q;
            qs.offset = $scope.offset;

            return qs;
        }
    }

    $scope.fetchDatasets = function() {
        $http
            .get('/api/geogw/services/' + $scope.currentService._id + '/records', { params: buildQueryString() })
            .success(function(data) {
                $scope.datasets = data.results;
                $scope.count = data.count;
                $scope.offset = data.query.offset;
                $scope.firstResultPos = data.query.offset + 1;
                $scope.lastResultPos = data.query.offset + data.results.length;
                $scope.activeFacets = data.query.facets;
                $scope.computeFacets(data.facets);
            });
    };

    $scope.computeFacets = function (facets) {
        $scope.facets = _.map(facetsDef, function(def) {
            return { name: def.name, label: def.label, values: facets[def.name], valueLabels: def.valueLabels };
        });
    };

    $scope.updateResults = function (paginate) {
        if (!paginate) $scope.offset = null;
        $location.search(buildQueryString());
        $scope.fetchDatasets();
    };

    $scope.hasPreviousResults = function() {
        return $scope.datasets && ($scope.offset > 0);
    };

    $scope.hasNextResults = function() {
        return $scope.datasets && ($scope.offset + $scope.datasets.length < $scope.count);
    };

    $scope.paginatePrevious = function() {
        $scope.offset = $scope.offset - 20;
        $scope.updateResults(true);
    };

    $scope.paginateNext = function() {
        $scope.offset = $scope.offset + 20;
        $scope.updateResults(true);
    };

    $scope.toggleFacet = function (facet) {
        if (!$scope.facetIsActive(facet)) {
            $scope.activeFacets.push(facet);
        } else {
            _.remove($scope.activeFacets, facet);
        }
        $scope.updateResults();
    };

    $scope.facetIsActive = function (facet) {
        return _.find($scope.activeFacets, facet);
    };

    $scope.applyFacet = function (facet) {
        $scope.activeFacets = [facet];
        $scope.updateResults();
    };

    $scope.encodeURIComponent = encodeURIComponent;

    $scope.$watch('q', $scope.updateResults, true);
    $scope.fetchDatasets();
});
<|endoftext|>


<commit_before>
// Success handler
var successHandler = function(status){
    if (window.console != undefined) {
        console.log("Purchase completed successfully: ", status);
    }
    window.location = $('input#google-wallet-id').data('success-url');
};

// Failure handler
var failureHandler = function(status){
    if (window.console != undefined) {
        console.log("Purchase failed ", status);
    }
    window.location = $('input#google-wallet-id').data('failure-url');
};

function purchase() {
    var generated_jwt = $('input#google-wallet-id').data('jwt');

    google.payments.inapp.buy({
      'jwt'     : generated_jwt,
      'success' : successHandler,
      'failure' : failureHandler
    });
    return false
}

jQuery(document).ready(function() {
    purchase();
});
<commit_msg>Make widget independent from jquery<commit_after>(function() {

    // Success handler
    var successHandler = function(status){
        if (window.console != undefined) {
            console.log("Purchase completed successfully: ", status);
        }
        window.location = document.getElementById('google-wallet-id').getAttribute('data-success-url');
    };

    // Failure handler
    var failureHandler = function(status){
        if (window.console != undefined) {
            console.log("Purchase failed ", status);
        }
        window.location = document.getElementById('google-wallet-id').getAttribute('data-failure-url');
    };

    function purchase() {
        var generated_jwt = document.getElementById('google-wallet-id').getAttribute('data-jwt');

        google.payments.inapp.buy({
            'jwt'     : generated_jwt,
            'success' : successHandler,
            'failure' : failureHandler
        });
        return false
    }

    $ = this.jQuery || this.Zepto || this.ender || this.$;

    if($) {
        $(purchase)
    } else {
        window.onload = purchase
    }
})()
<|endoftext|>


<commit_before>// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview using private properties isn't a Closure violation in tests.
 * @suppress {accessControls}
 */

Host.InspectorFrontendHost.isolatedFileSystem = function(name) {
  return BindingsTestRunner.TestFileSystem._instances[name];
};

BindingsTestRunner.TestFileSystem = function(fileSystemPath) {
  this.root = new BindingsTestRunner.TestFileSystem.Entry(this, '', true, null);
  this.fileSystemPath = fileSystemPath;
};

BindingsTestRunner.TestFileSystem._instances = {};

BindingsTestRunner.TestFileSystem.prototype = {
  dumpAsText: function() {
    const result = [];
    dfs(this.root, '');
    result[0] = this.fileSystemPath;
    return result.join('\n');

    function dfs(node, indent) {
      result.push(indent + node.name);
      const newIndent = indent + '    ';

      for (const child of node._children) {
        dfs(child, newIndent);
      }
    }
  },

  reportCreatedPromise: function(type) {
    return new Promise(fulfill => this.reportCreated(fulfill, type));
  },

  reportCreated: function(callback, type) {
    const fileSystemPath = this.fileSystemPath;
    BindingsTestRunner.TestFileSystem._instances[this.fileSystemPath] = this;

    Host.InspectorFrontendHost.events.dispatchEventToListeners(
        Host.InspectorFrontendHostAPI.Events.FileSystemAdded,
        {fileSystem: {fileSystemPath: this.fileSystemPath, fileSystemName: this.fileSystemPath, type}});

    self.Persistence.isolatedFileSystemManager.addEventListener(
        Persistence.IsolatedFileSystemManager.Events.FileSystemAdded, created);

    function created(event) {
      const fileSystem = event.data;

      if (fileSystem.path() !== fileSystemPath) {
        return;
      }

      self.Persistence.isolatedFileSystemManager.removeEventListener(
          Persistence.IsolatedFileSystemManager.Events.FileSystemAdded, created);
      callback(fileSystem);
    }
  },

  reportRemoved: function() {
    delete BindingsTestRunner.TestFileSystem._instances[this.fileSystemPath];
    Host.InspectorFrontendHost.events.dispatchEventToListeners(
        Host.InspectorFrontendHostAPI.Events.FileSystemRemoved, this.fileSystemPath);
  },

  addFile: function(path, content, lastModified) {
    const pathTokens = path.split('/');
    let node = this.root;
    const folders = pathTokens.slice(0, pathTokens.length - 1);
    const fileName = pathTokens.peekLast();

    for (const folder of folders) {
      let dir = node._childrenMap[folder];

      if (!dir) {
        dir = node.mkdir(folder);
      }

      node = dir;
    }

    const file = node.addFile(fileName, content);

    if (lastModified) {
      file._timestamp = lastModified;
    }

    return file;
  }
};

BindingsTestRunner.TestFileSystem.Entry = function(fileSystem, name, isDirectory, parent) {
  this._fileSystem = fileSystem;
  this.name = name;
  this._children = [];
  this._childrenMap = {};
  this.isDirectory = isDirectory;
  this._timestamp = 1000000;
  this._parent = parent;
};

BindingsTestRunner.TestFileSystem.Entry.prototype = {
  get fullPath() {
    return (this.parent ? this.parent.fullPath + '/' + this.name : '');
  },

  remove: function(success, failure) {
    this._parent._removeChild(this, success, failure);
  },

  _removeChild: function(child, success, failure) {
    const index = this._children.indexOf(child);

    if (index === -1) {
      failure('Failed to remove file: file not found.');
      return;
    }

    const fullPath = this._fileSystem.fileSystemPath + child.fullPath;
    this._children.splice(index, 1);
    delete this._childrenMap[child.name];
    child.parent = null;

    Host.InspectorFrontendHost.events.dispatchEventToListeners(
        Host.InspectorFrontendHostAPI.Events.FileSystemFilesChangedAddedRemoved,
        {changed: [], added: [], removed: [fullPath]});

    success();
  },

  mkdir: function(name) {
    const child = new BindingsTestRunner.TestFileSystem.Entry(this._fileSystem, name, true, this);
    this._childrenMap[name] = child;
    this._children.push(child);
    child.parent = this;
    return child;
  },

  addFile: function(name, content) {
    const child = new BindingsTestRunner.TestFileSystem.Entry(this._fileSystem, name, false, this);
    this._childrenMap[name] = child;
    this._children.push(child);
    child.parent = this;

    child.content = new Blob([content], {type: 'text/plain'});

    const fullPath = this._fileSystem.fileSystemPath + child.fullPath;

    Host.InspectorFrontendHost.events.dispatchEventToListeners(
        Host.InspectorFrontendHostAPI.Events.FileSystemFilesChangedAddedRemoved,
        {changed: [], added: [fullPath], removed: []});

    return child;
  },

  setContent: function(content) {
    this.content = new Blob([content], {type: 'text/plain'});

    this._timestamp += 1000;
    const fullPath = this._fileSystem.fileSystemPath + this.fullPath;

    Host.InspectorFrontendHost.events.dispatchEventToListeners(
        Host.InspectorFrontendHostAPI.Events.FileSystemFilesChangedAddedRemoved,
        {changed: [fullPath], added: [], removed: []});
  },

  createReader: function() {
    return new BindingsTestRunner.TestFileSystem.Reader(this._children);
  },

  createWriter: function(success, failure) {
    success(new BindingsTestRunner.TestFileSystem.Writer(this));
  },

  file: function(callback) {
    callback(this.content);
  },

  getDirectory: function(path, noop, callback, errorCallback) {
    this.getEntry(path, noop, callback, errorCallback);
  },

  getFile: function(path, noop, callback, errorCallback) {
    this.getEntry(path, noop, callback, errorCallback);
  },

  _createEntry: function(path, options, callback, errorCallback) {
    const tokens = path.split('/');
    const name = tokens.pop();
    let parentEntry = this;

    for (const token of tokens) {
      parentEntry = parentEntry._childrenMap[token];
    }

    let entry = parentEntry._childrenMap[name];

    if (entry && options.exclusive) {
      errorCallback(new DOMException('File exists: ' + path, 'InvalidModificationError'));
      return;
    }

    if (!entry) {
      entry = parentEntry.addFile(name, '');
    }

    callback(entry);
  },

  getEntry: function(path, options, callback, errorCallback) {
    if (path.startsWith('/')) {
      path = path.substring(1);
    }

    if (options && options.create) {
      this._createEntry(path, options, callback, errorCallback);
      return;
    }

    if (!path) {
      callback(this);
      return;
    }

    let entry = this;

    for (const token of path.split('/')) {
      entry = entry._childrenMap[token];
      if (!entry) {
        break;
      }
    }

    (entry ? callback(entry) : errorCallback(new DOMException('Path not found: ' + path, 'NotFoundError')));
  },

  getMetadata: function(success, failure) {
    success({modificationTime: new Date(this._timestamp), size: (this.isDirectory ? 0 : this.content.size)});
  },

  moveTo: function(parent, newName, callback, errorCallback) {
    this._parent._children.remove(this);
    delete this._parent._childrenMap[this.name];
    this._parent = parent;
    this._parent._children.push(this);
    this.name = newName;
    this._parent._childrenMap[this.name] = this;
    callback(this);
  },

  getParent: function(callback, errorCallback) {
    callback(this._parent);
  }
};

BindingsTestRunner.TestFileSystem.Reader = function(children) {
  this._children = children;
};

BindingsTestRunner.TestFileSystem.Reader.prototype = {
  readEntries: function(callback) {
    const children = this._children;
    this._children = [];
    callback(children);
  }
};

BindingsTestRunner.TestFileSystem.Writer = function(entry) {
  this._entry = entry;
  this._modificationTimesDelta = 500;
};

BindingsTestRunner.TestFileSystem.Writer.prototype = {
  write: function(blob) {
    this._entry._timestamp += this._modificationTimesDelta;
    this._entry.content = blob;

    if (this.onwriteend) {
      this.onwriteend();
    }
  },

  truncate: function(num) {
    this._entry._timestamp += this._modificationTimesDelta;
    this._entry.content = this._entry.content.slice(0, num);

    if (this.onwriteend) {
      this.onwriteend();
    }
  }
};
<commit_msg>[utilities] Use Map instead of Array in TestFileSystem.Entry<commit_after>// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview using private properties isn't a Closure violation in tests.
 * @suppress {accessControls}
 */

Host.InspectorFrontendHost.isolatedFileSystem = function(name) {
  return BindingsTestRunner.TestFileSystem._instances[name];
};

BindingsTestRunner.TestFileSystem = function(fileSystemPath) {
  this.root = new BindingsTestRunner.TestFileSystem.Entry(this, '', true, null);
  this.fileSystemPath = fileSystemPath;
};

BindingsTestRunner.TestFileSystem._instances = {};

BindingsTestRunner.TestFileSystem.prototype = {
  dumpAsText: function() {
    const result = [];
    dfs(this.root, '');
    result[0] = this.fileSystemPath;
    return result.join('\n');

    function dfs(node, indent) {
      result.push(indent + node.name);
      const newIndent = indent + '    ';

      for (const child of node._children.values()) {
        dfs(child, newIndent);
      }
    }
  },

  reportCreatedPromise: function(type) {
    return new Promise(fulfill => this.reportCreated(fulfill, type));
  },

  reportCreated: function(callback, type) {
    const fileSystemPath = this.fileSystemPath;
    BindingsTestRunner.TestFileSystem._instances[this.fileSystemPath] = this;

    Host.InspectorFrontendHost.events.dispatchEventToListeners(
        Host.InspectorFrontendHostAPI.Events.FileSystemAdded,
        {fileSystem: {fileSystemPath: this.fileSystemPath, fileSystemName: this.fileSystemPath, type}});

    self.Persistence.isolatedFileSystemManager.addEventListener(
        Persistence.IsolatedFileSystemManager.Events.FileSystemAdded, created);

    function created(event) {
      const fileSystem = event.data;

      if (fileSystem.path() !== fileSystemPath) {
        return;
      }

      self.Persistence.isolatedFileSystemManager.removeEventListener(
          Persistence.IsolatedFileSystemManager.Events.FileSystemAdded, created);
      callback(fileSystem);
    }
  },

  reportRemoved: function() {
    delete BindingsTestRunner.TestFileSystem._instances[this.fileSystemPath];
    Host.InspectorFrontendHost.events.dispatchEventToListeners(
        Host.InspectorFrontendHostAPI.Events.FileSystemRemoved, this.fileSystemPath);
  },

  addFile: function(path, content, lastModified) {
    const pathTokens = path.split('/');
    let node = this.root;
    const folders = pathTokens.slice(0, pathTokens.length - 1);
    const fileName = pathTokens.peekLast();

    for (const folder of folders) {
      let dir = node._children.get(folder);

      if (!dir) {
        dir = node.mkdir(folder);
      }

      node = dir;
    }

    const file = node.addFile(fileName, content);

    if (lastModified) {
      file._timestamp = lastModified;
    }

    return file;
  }
};

BindingsTestRunner.TestFileSystem.Entry = function(fileSystem, name, isDirectory, parent) {
  this._fileSystem = fileSystem;
  this.name = name;
  this._children = new Map();
  this.isDirectory = isDirectory;
  this._timestamp = 1000000;
  this._parent = parent;
};

BindingsTestRunner.TestFileSystem.Entry.prototype = {
  get fullPath() {
    return (this._parent ? this._parent.fullPath + '/' + this.name : '');
  },

  remove: function(success, failure) {
    this._parent._removeChild(this, success, failure);
  },

  _removeChild: function(child, success, failure) {
    if (!this._children.has(child.name)) {
      failure('Failed to remove file: file not found.');
      return;
    }

    const fullPath = this._fileSystem.fileSystemPath + child.fullPath;
    this._children.delete(child.name);
    child._parent = null;

    Host.InspectorFrontendHost.events.dispatchEventToListeners(
        Host.InspectorFrontendHostAPI.Events.FileSystemFilesChangedAddedRemoved,
        {changed: [], added: [], removed: [fullPath]});

    success();
  },

  mkdir: function(name) {
    const child = new BindingsTestRunner.TestFileSystem.Entry(this._fileSystem, name, true, this);
    this._children.set(name, child);
    return child;
  },

  addFile: function(name, content) {
    const child = new BindingsTestRunner.TestFileSystem.Entry(this._fileSystem, name, false, this);
    this._children.set(name, child);

    child.content = new Blob([content], {type: 'text/plain'});

    const fullPath = this._fileSystem.fileSystemPath + child.fullPath;

    Host.InspectorFrontendHost.events.dispatchEventToListeners(
        Host.InspectorFrontendHostAPI.Events.FileSystemFilesChangedAddedRemoved,
        {changed: [], added: [fullPath], removed: []});

    return child;
  },

  setContent: function(content) {
    this.content = new Blob([content], {type: 'text/plain'});

    this._timestamp += 1000;
    const fullPath = this._fileSystem.fileSystemPath + this.fullPath;

    Host.InspectorFrontendHost.events.dispatchEventToListeners(
        Host.InspectorFrontendHostAPI.Events.FileSystemFilesChangedAddedRemoved,
        {changed: [fullPath], added: [], removed: []});
  },

  createReader: function() {
    return new BindingsTestRunner.TestFileSystem.Reader([...this._children.values()]);
  },

  createWriter: function(success, failure) {
    success(new BindingsTestRunner.TestFileSystem.Writer(this));
  },

  file: function(callback) {
    callback(this.content);
  },

  getDirectory: function(path, noop, callback, errorCallback) {
    this.getEntry(path, noop, callback, errorCallback);
  },

  getFile: function(path, noop, callback, errorCallback) {
    this.getEntry(path, noop, callback, errorCallback);
  },

  _createEntry: function(path, options, callback, errorCallback) {
    const tokens = path.split('/');
    const name = tokens.pop();
    let parentEntry = this;

    for (const token of tokens) {
      parentEntry = parentEntry._children.get(token);
    }

    let entry = parentEntry._children.get(name);

    if (entry && options.exclusive) {
      errorCallback(new DOMException('File exists: ' + path, 'InvalidModificationError'));
      return;
    }

    if (!entry) {
      entry = parentEntry.addFile(name, '');
    }

    callback(entry);
  },

  getEntry: function(path, options, callback, errorCallback) {
    if (path.startsWith('/')) {
      path = path.substring(1);
    }

    if (options && options.create) {
      this._createEntry(path, options, callback, errorCallback);
      return;
    }

    if (!path) {
      callback(this);
      return;
    }

    let entry = this;

    for (const token of path.split('/')) {
      entry = entry._children.get(token);
      if (!entry) {
        break;
      }
    }

    (entry ? callback(entry) : errorCallback(new DOMException('Path not found: ' + path, 'NotFoundError')));
  },

  getMetadata: function(success, failure) {
    success({modificationTime: new Date(this._timestamp), size: (this.isDirectory ? 0 : this.content.size)});
  },

  moveTo: function(parent, newName, callback, errorCallback) {
    this._parent._children.delete(this.name);
    this._parent = parent;
    this.name = newName;
    this._parent._children.set(this.name, this);
    callback(this);
  },

  getParent: function(callback, errorCallback) {
    callback(this._parent);
  }
};

BindingsTestRunner.TestFileSystem.Reader = function(children) {
  this._children = children;
};

BindingsTestRunner.TestFileSystem.Reader.prototype = {
  readEntries: function(callback) {
    const children = this._children;
    this._children = [];
    callback(children);
  }
};

BindingsTestRunner.TestFileSystem.Writer = function(entry) {
  this._entry = entry;
  this._modificationTimesDelta = 500;
};

BindingsTestRunner.TestFileSystem.Writer.prototype = {
  write: function(blob) {
    this._entry._timestamp += this._modificationTimesDelta;
    this._entry.content = blob;

    if (this.onwriteend) {
      this.onwriteend();
    }
  },

  truncate: function(num) {
    this._entry._timestamp += this._modificationTimesDelta;
    this._entry.content = this._entry.content.slice(0, num);

    if (this.onwriteend) {
      this.onwriteend();
    }
  }
};
<|endoftext|>


<commit_before>L.Control.EasyPrint = L.Control.extend({
	options: {
		title: 'Print map',
		position: 'topleft'
	},

	onAdd: function () {
		var container = L.DomUtil.create('div', 'leaflet-control-easyPrint leaflet-bar leaflet-control');

		this.link = L.DomUtil.create('a', 'leaflet-control-easyPrint-button leaflet-bar-part', container);
		this.link.id = "leafletEasyPrint";
		this.link.title = this.options.title;

		L.DomEvent.addListener(this.link, 'click', printPage, this.options);
		L.DomEvent.disableClickPropagation(container);

		return container;
	}

});

L.easyPrint = function(options) {
	return new L.Control.EasyPrint(options);
};

function printPage(){

	if (this.elementsToHide){
		var htmlElementsToHide = document.querySelectorAll(this.elementsToHide);

		for (var i = 0; i < htmlElementsToHide.length; i++) {
			htmlElementsToHide[i].className = htmlElementsToHide[i].className + ' _epHidden';
		}
	}
	this.map.fire("beforePrint");
	window.print();
	this.map.fire("afterPrint");
	if (this.elementsToHide){
		var htmlElementsToHide = document.querySelectorAll(this.elementsToHide);

		for (var i = 0; i < htmlElementsToHide.length; i++) {
			htmlElementsToHide[i].className = htmlElementsToHide[i].className.replace(' _epHidden','');
		}
	}

}<commit_msg>Fix for event handling<commit_after>L.Control.EasyPrint = L.Control.extend({
	options: {
		title: 'Print map',
		position: 'topleft'
	},

	onAdd: function () {
		var container = L.DomUtil.create('div', 'leaflet-control-easyPrint leaflet-bar leaflet-control');

		this.link = L.DomUtil.create('a', 'leaflet-control-easyPrint-button leaflet-bar-part', container);
		this.link.id = "leafletEasyPrint";
		this.link.title = this.options.title;

		L.DomEvent.addListener(this.link, 'click', printPage, this);
		L.DomEvent.disableClickPropagation(container);

		return container;
	}

});

L.easyPrint = function(options) {
	return new L.Control.EasyPrint(options);
};

function printPage(){

	if (this.options.elementsToHide){
		var htmlElementsToHide = document.querySelectorAll(this.options.elementsToHide);

		for (var i = 0; i < htmlElementsToHide.length; i++) {
			htmlElementsToHide[i].className = htmlElementsToHide[i].className + ' _epHidden';
		}
	}
	this._map.fire("beforePrint");
	window.print();
	this._map.fire("afterPrint");
	if (this.options.elementsToHide){
		var htmlElementsToHide = document.querySelectorAll(this.options.elementsToHide);

		for (var i = 0; i < htmlElementsToHide.length; i++) {
			htmlElementsToHide[i].className = htmlElementsToHide[i].className.replace(' _epHidden','');
		}
	}

}<|endoftext|>


<commit_before>// Routes for oauth
// /oauth
var express = require('express');
var router = express.Router();

var errors = require('@holmwell/errors');
var ensure = require('circle-blvd/auth-ensure');

var guard = errors.guard;
var handle = require('circle-blvd/handle');

var request = require('request');

module.exports = function (db) {

	var settings = require('circle-blvd/settings')(db);

	router.get('/oauth/slack', ensure.auth, function (req, res) {
		var payload = req.query;

		if (payload.state && payload.code) {
			// Verify that we have access to the circle
			// specified in state
			var memberships = req.user.memberships;
			for (var index in memberships) {
				if (memberships[index].circle === payload.state) {
					settings.get(guard(res, processSettings));
					return;
				}
			}
		}

		function processSettings(settings) {
			// Get Slack access, save the tokens
			var oauthUrl = [
				'https://slack.com/api/oauth.access',
				'?client_id=',
				settings['slack-client-id'].value,
				'&client_secret=',
				settings['slack-client-secret'].value,
				'&code=',
				payload.code
			].join('');

			request.get(oauthUrl, handleOauthReply);
		}

		function handleOauthReply(err, httpResponse, body) {
			var access = JSON.parse(body);
			if (access && access.ok) {
				var circleId = payload.state;
				db.circles.get(circleId, guard(res, updateCircle));
			}
			else {
				// Didn't work out
				console.log(err);
				res.redirect('/#/');
			}
		}

		function updateCircle(circle) {
			circle.access = circle.access || {};
			circle.access.slack = access;

			circle.webhooks = circle.webhooks || {};
			circle.webhooks.slack = circle.webhooks.slack || {};
			circle.webhooks.slack.url = access.incoming_webhook.url;

			db.circles.update(circle, guard(res, function () {
				res.redirect('/#/');
			}));
		}

		// fallback / invalid request
		res.redirect('/#/');
	});

	return {
		router: router
	};
};<commit_msg>Fix oauth/slack route<commit_after>// Routes for oauth
// /oauth
var express = require('express');
var router = express.Router();

var errors = require('@holmwell/errors');
var ensure = require('circle-blvd/auth-ensure');

var guard = errors.guard;
var handle = require('circle-blvd/handle');

var request = require('request');

module.exports = function (db) {

	var settings = require('circle-blvd/settings')(db);

	router.get('/slack', ensure.auth, function (req, res) {
		var payload = req.query;

		if (payload.state && payload.code) {
			// Verify that we have access to the circle
			// specified in state
			var memberships = req.user.memberships;
			for (var index in memberships) {
				if (memberships[index].circle === payload.state) {
					settings.get(guard(res, processSettings));
					return;
				}
			}
		}

		function processSettings(settings) {
			// Get Slack access, save the tokens
			var oauthUrl = [
				'https://slack.com/api/oauth.access',
				'?client_id=',
				settings['slack-client-id'].value,
				'&client_secret=',
				settings['slack-client-secret'].value,
				'&code=',
				payload.code
			].join('');

			request.get(oauthUrl, handleOauthReply);
		}

		function handleOauthReply(err, httpResponse, body) {
			var access = JSON.parse(body);
			if (access && access.ok) {
				var circleId = payload.state;
				db.circles.get(circleId, guard(res, updateCircle));
			}
			else {
				// Didn't work out
				console.log(err);
				res.redirect('/#/');
			}
		}

		function updateCircle(circle) {
			circle.access = circle.access || {};
			circle.access.slack = access;

			circle.webhooks = circle.webhooks || {};
			circle.webhooks.slack = circle.webhooks.slack || {};
			circle.webhooks.slack.url = access.incoming_webhook.url;

			db.circles.update(circle, guard(res, function () {
				res.redirect('/#/');
			}));
		}

		// fallback / invalid request
		res.redirect('/#/');
	});

	return {
		router: router
	};
};<|endoftext|>


<commit_before>var common  = require("../common");
var SQL     = require("../../lib/SQL");

var should  = require("should");

var Dialect = common.fakeDialect;

describe("SQL.CREATE_TABLE", function () {
	it("should return a CREATE TABLE", function (done) {
		SQL.CREATE_TABLE({
			name    : "fake_table",
			columns : [ "first_fake_column", "second_fake_column" ],
			primary : [ "my_primary_key" ]
		}, Dialect).should.equal("CREATE TABLE $$fake_table$$ (first_fake_column, second_fake_column, " +
		                         "PRIMARY KEY ($$my_primary_key$$))");

		return done();
	});
});

describe("SQL.CREATE_TABLE", function () {
	it("should return a CREATE TABLE", function (done) {
		SQL.CREATE_TABLE({
			name    : "fake_table",
			columns : [ "first_fake_column", "second_fake_column" ]
		}, Dialect).should.equal("CREATE TABLE $$fake_table$$ (first_fake_column, second_fake_column)");

		return done();
	});
});

describe("SQL.ALTER_TABLE_ADD_COLUMN", function () {
	it("should return an ALTER TABLE", function (done) {
		SQL.ALTER_TABLE_ADD_COLUMN({
			name    : "fake_table",
			column  : "my_fake_column"
		}, Dialect).should.equal("ALTER TABLE $$fake_table$$ ADD my_fake_column");

		return done();
	});
});

describe("SQL.ALTER_TABLE_ADD_COLUMN", function () {
	it("should return an ALTER TABLE", function (done) {
		SQL.ALTER_TABLE_ADD_COLUMN({
			name    : "fake_table",
			column  : "my_fake_column",
			first   : true
		}, Dialect).should.equal("ALTER TABLE $$fake_table$$ ADD my_fake_column FIRST");

		return done();
	});
});

describe("SQL.ALTER_TABLE_ADD_COLUMN", function () {
	it("should return an ALTER TABLE", function (done) {
		SQL.ALTER_TABLE_ADD_COLUMN({
			name    : "fake_table",
			column  : "my_fake_column",
			after   : "other_column"
		}, Dialect).should.equal("ALTER TABLE $$fake_table$$ ADD my_fake_column AFTER $$other_column$$");

		return done();
	});
});

describe("SQL.ALTER_TABLE_MODIFY_COLUMN", function () {
	it("should return an ALTER TABLE", function (done) {
		SQL.ALTER_TABLE_MODIFY_COLUMN({
			name    : "fake_table",
			column  : "my_fake_column"
		}, Dialect).should.equal("ALTER TABLE $$fake_table$$ MODIFY my_fake_column");

		return done();
	});
});

describe("SQL.ALTER_TABLE_DROP_COLUMN", function () {
	it("should return an ALTER TABLE", function (done) {
		SQL.ALTER_TABLE_DROP_COLUMN({
			name    : "fake_table",
			column  : "my_fake_column"
		}, Dialect).should.equal("ALTER TABLE $$fake_table$$ DROP $$my_fake_column$$");

		return done();
	});
});
<commit_msg>Adds SQL.addIndex and SQL.dropIndex simple tests<commit_after>var common  = require("../common");
var SQL     = require("../../lib/SQL");

var should  = require("should");

var Dialect = common.fakeDialect;

describe("SQL.CREATE_TABLE", function () {
	it("should return a CREATE TABLE", function (done) {
		SQL.CREATE_TABLE({
			name    : "fake_table",
			columns : [ "first_fake_column", "second_fake_column" ],
			primary : [ "my_primary_key" ]
		}, Dialect).should.equal("CREATE TABLE $$fake_table$$ (first_fake_column, second_fake_column, " +
		                         "PRIMARY KEY ($$my_primary_key$$))");

		return done();
	});
});

describe("SQL.CREATE_TABLE", function () {
	it("should return a CREATE TABLE", function (done) {
		SQL.CREATE_TABLE({
			name    : "fake_table",
			columns : [ "first_fake_column", "second_fake_column" ]
		}, Dialect).should.equal("CREATE TABLE $$fake_table$$ (first_fake_column, second_fake_column)");

		return done();
	});
});

describe("SQL.ALTER_TABLE_ADD_COLUMN", function () {
	it("should return an ALTER TABLE", function (done) {
		SQL.ALTER_TABLE_ADD_COLUMN({
			name    : "fake_table",
			column  : "my_fake_column"
		}, Dialect).should.equal("ALTER TABLE $$fake_table$$ ADD my_fake_column");

		return done();
	});
});

describe("SQL.ALTER_TABLE_ADD_COLUMN", function () {
	it("should return an ALTER TABLE", function (done) {
		SQL.ALTER_TABLE_ADD_COLUMN({
			name    : "fake_table",
			column  : "my_fake_column",
			first   : true
		}, Dialect).should.equal("ALTER TABLE $$fake_table$$ ADD my_fake_column FIRST");

		return done();
	});
});

describe("SQL.ALTER_TABLE_ADD_COLUMN", function () {
	it("should return an ALTER TABLE", function (done) {
		SQL.ALTER_TABLE_ADD_COLUMN({
			name    : "fake_table",
			column  : "my_fake_column",
			after   : "other_column"
		}, Dialect).should.equal("ALTER TABLE $$fake_table$$ ADD my_fake_column AFTER $$other_column$$");

		return done();
	});
});

describe("SQL.ALTER_TABLE_MODIFY_COLUMN", function () {
	it("should return an ALTER TABLE", function (done) {
		SQL.ALTER_TABLE_MODIFY_COLUMN({
			name    : "fake_table",
			column  : "my_fake_column"
		}, Dialect).should.equal("ALTER TABLE $$fake_table$$ MODIFY my_fake_column");

		return done();
	});
});

describe("SQL.ALTER_TABLE_DROP_COLUMN", function () {
	it("should return an ALTER TABLE", function (done) {
		SQL.ALTER_TABLE_DROP_COLUMN({
			name    : "fake_table",
			column  : "my_fake_column"
		}, Dialect).should.equal("ALTER TABLE $$fake_table$$ DROP $$my_fake_column$$");

		return done();
	});
});

describe("SQL.CREATE_INDEX", function () {
	it("should return an CREATE INDEX", function (done) {
		SQL.CREATE_INDEX({
			name       : "fake_index",
			collection : "fake_table",
			columns    : [ "my_fake_column" ]
		}, Dialect).should.equal("CREATE INDEX $$fake_index$$ ON $$fake_table$$ ($$my_fake_column$$)");

		return done();
	});

	it("should return an CREATE UNIQUE INDEX if unique passed", function (done) {
		SQL.CREATE_INDEX({
			name       : "fake_index",
			collection : "fake_table",
			unique     : true,
			columns    : [ "my_fake_column" ]
		}, Dialect).should.equal("CREATE UNIQUE INDEX $$fake_index$$ ON $$fake_table$$ ($$my_fake_column$$)");

		return done();
	});
});

describe("SQL.DROP_INDEX", function () {
	it("should return an DROP INDEX", function (done) {
		SQL.DROP_INDEX({
			name       : "fake_index",
			collection : "fake_table"
		}, Dialect).should.equal("DROP INDEX $$fake_index$$ ON $$fake_table$$");

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