<commit_before>define(["Tone/core/Tone", "Tone/core/Emitter", "Tone/core/Timeline"], function (Tone) {

	/**
	 *  shim
	 *  @private
	 */
	if (!window.hasOwnProperty("AudioContext") && window.hasOwnProperty("webkitAudioContext")){
		window.AudioContext = window.webkitAudioContext;
	}

	/**
	 *  @class Wrapper around the native AudioContext.
	 *  @extends {Tone.Emitter}
	 *  @param {AudioContext=} context optionally pass in a context
	 */
	Tone.Context = function(context){

		Tone.Emitter.call(this);

		if (!context){
			context = new window.AudioContext();
		}
		this._context = context;
		// extend all of the methods
		for (var prop in this._context){
			this._defineProperty(this._context, prop);
		}

		/**
		 *  The default latency hint
		 *  @type  {String}
		 *  @private
		 */
		this._latencyHint = "interactive";

		/**
		 *  An object containing all of the constants AudioBufferSourceNodes
		 *  @type  {Object}
		 *  @private
		 */
		this._constants = {};

		///////////////////////////////////////////////////////////////////////
		// WORKER
		///////////////////////////////////////////////////////////////////////

		/**
		 *  The amount of time events are scheduled
		 *  into the future
		 *  @type  {Number}
		 *  @private
		 */
		this._lookAhead = 0.1;

		/**
		 *  How often the update look runs
		 *  @type  {Number}
		 *  @private
		 */
		this._updateInterval = this._lookAhead/3;

		/**
		 *  A reference to the actual computed update interval
		 *  @type  {Number}
		 *  @private
		 */
		this._computedUpdateInterval = 0;

		/**
		 *  The web worker which is used to update Tone.Clock
		 *  @private
		 *  @type  {WebWorker}
		 */
		this._worker = this._createWorker();

		///////////////////////////////////////////////////////////////////////
		// TIMEOUTS
		///////////////////////////////////////////////////////////////////////

		/**
		 *  All of the setTimeout events.
		 *  @type  {Tone.Timeline}
		 *  @private
		 */
		this._timeouts = new Tone.Timeline();

		/**
		 *  The timeout id counter
		 *  @private
		 *  @type {Number}
		 */
		this._timeoutIds = 0;

		this.on("tick", this._timeoutLoop.bind(this));

	};

	Tone.extend(Tone.Context, Tone.Emitter);
	Tone.Emitter.mixin(Tone.Context);

	/**
	 *  Define a property on this Tone.Context.
	 *  This is used to extend the native AudioContext
	 *  @param  {AudioContext}  context
	 *  @param  {String}  prop
	 *  @private
	 */
	Tone.Context.prototype._defineProperty = function(context, prop){
		if (Tone.isUndef(this[prop])){
			Object.defineProperty(this, prop, {
				get : function(){
					if (typeof context[prop] === "function"){
						return context[prop].bind(context);
					} else {
						return context[prop];
					}
				},
				set : function(val){
					context[prop] = val;
				}
			});
		}
	};

	/**
	 *  The current audio context time
	 *  @return  {Number}
	 */
	Tone.Context.prototype.now = function(){
		return this._context.currentTime;
	};

	/**
	 *  Generate a web worker
	 *  @return  {WebWorker}
	 *  @private
	 */
	Tone.Context.prototype._createWorker = function(){

		//URL Shim
		window.URL = window.URL || window.webkitURL;

		var blob = new Blob([
			//the initial timeout time
			"var timeoutTime = "+(this._updateInterval * 1000).toFixed(1)+";" +
			//onmessage callback
			"self.onmessage = function(msg){" +
			"	timeoutTime = parseInt(msg.data);" +
			"};" +
			//the tick function which posts a message
			//and schedules a new tick
			"function tick(){" +
			"	setTimeout(tick, timeoutTime);" +
			"	self.postMessage('tick');" +
			"}" +
			//call tick initially
			"tick();"
		]);
		var blobUrl = URL.createObjectURL(blob);
		var worker = new Worker(blobUrl);

		worker.addEventListener("message", function(){
			// tick the clock
			this.emit("tick");
		}.bind(this));

		//lag compensation
		worker.addEventListener("message", function(){
			var now = this.now();
			if (Tone.isNumber(this._lastUpdate)){
				var diff = now - this._lastUpdate;
				this._computedUpdateInterval = Math.max(diff, this._computedUpdateInterval * 0.97);
			}
			this._lastUpdate = now;
		}.bind(this));

		return worker;
	};

	/**
	 *  Generate a looped buffer at some constant value.
	 *  @param  {Number}  val
	 *  @return  {BufferSourceNode}
	 */
	Tone.Context.prototype.getConstant = function(val){
		if (this._constants[val]){
			return this._constants[val];
		} else {
			var buffer = this._context.createBuffer(1, 128, this._context.sampleRate);
			var arr = buffer.getChannelData(0);
			for (var i = 0; i < arr.length; i++){
				arr[i] = val;
			}
			var constant = this._context.createBufferSource();
			constant.channelCount = 1;
			constant.channelCountMode = "explicit";
			constant.buffer = buffer;
			constant.loop = true;
			constant.start(0);
			this._constants[val] = constant;
			return constant;
		}
	};

	/**
	 *  The private loop which keeps track of the context scheduled timeouts
	 *  Is invoked from the clock source
	 *  @private
	 */
	Tone.Context.prototype._timeoutLoop = function(){
		var now = this.now();
		while(this._timeouts && this._timeouts.length && this._timeouts.peek().time <= now){
			this._timeouts.shift().callback();
		}
	};

	/**
	 *  A setTimeout which is gaurenteed by the clock source.
	 *  Also runs in the offline context.
	 *  @param  {Function}  fn       The callback to invoke
	 *  @param  {Seconds}    timeout  The timeout in seconds
	 *  @returns {Number} ID to use when invoking Tone.Context.clearTimeout
	 */
	Tone.Context.prototype.setTimeout = function(fn, timeout){
		this._timeoutIds++;
		var now = this.now();
		this._timeouts.add({
			callback : fn,
			time : now + timeout,
			id : this._timeoutIds
		});
		return this._timeoutIds;
	};

	/**
	 *  Clears a previously scheduled timeout with Tone.context.setTimeout
	 *  @param  {Number}  id  The ID returned from setTimeout
	 *  @return  {Tone.Context}  this
	 */
	Tone.Context.prototype.clearTimeout = function(id){
		this._timeouts.forEach(function(event){
			if (event.id === id){
				this.remove(event);
			}
		});
		return this;
	};

	/**
	 *  This is the time that the clock is falling behind
	 *  the scheduled update interval. The Context automatically
	 *  adjusts for the lag and schedules further in advance.
	 *  @type {Number}
	 *  @memberOf Tone.Context
	 *  @name lag
	 *  @static
	 *  @readOnly
	 */
	Object.defineProperty(Tone.Context.prototype, "lag", {
		get : function(){
			var diff = this._computedUpdateInterval - this._updateInterval;
			diff = Math.max(diff, 0);
			return diff;
		}
	});

	/**
	 *  The amount of time in advance that events are scheduled.
	 *  The lookAhead will adjust slightly in response to the
	 *  measured update time to try to avoid clicks.
	 *  @type {Number}
	 *  @memberOf Tone.Context
	 *  @name lookAhead
	 *  @static
	 */
	Object.defineProperty(Tone.Context.prototype, "lookAhead", {
		get : function(){
			return this._lookAhead;
		},
		set : function(lA){
			this._lookAhead = lA;
		}
	});

	/**
	 *  How often the Web Worker callback is invoked.
	 *  This number corresponds to how responsive the scheduling
	 *  can be. Context.updateInterval + Context.lookAhead gives you the
	 *  total latency between scheduling an event and hearing it.
	 *  @type {Number}
	 *  @memberOf Tone.Context
	 *  @name updateInterval
	 *  @static
	 */
	Object.defineProperty(Tone.Context.prototype, "updateInterval", {
		get : function(){
			return this._updateInterval;
		},
		set : function(interval){
			this._updateInterval = Math.max(interval, Tone.prototype.blockTime);
			this._worker.postMessage(Math.max(interval * 1000, 1));
		}
	});

	/**
	 *  The type of playback, which affects tradeoffs between audio
	 *  output latency and responsiveness.
	 *
	 *  In addition to setting the value in seconds, the latencyHint also
	 *  accepts the strings "interactive" (prioritizes low latency),
	 *  "playback" (prioritizes sustained playback), "balanced" (balances
	 *  latency and performance), and "fastest" (lowest latency, might glitch more often).
	 *  @type {String|Seconds}
	 *  @memberOf Tone.Context#
	 *  @name latencyHint
	 *  @static
	 *  @example
	 * //set the lookAhead to 0.3 seconds
	 * Tone.context.latencyHint = 0.3;
	 */
	Object.defineProperty(Tone.Context.prototype, "latencyHint", {
		get : function(){
			return this._latencyHint;
		},
		set : function(hint){
			var lookAhead = hint;
			this._latencyHint = hint;
			if (Tone.isString(hint)){
				switch(hint){
					case "interactive" :
						lookAhead = 0.1;
						this._context.latencyHint = hint;
						break;
					case "playback" :
						lookAhead = 0.8;
						this._context.latencyHint = hint;
						break;
					case "balanced" :
						lookAhead = 0.25;
						this._context.latencyHint = hint;
						break;
					case "fastest" :
						this._context.latencyHint = "interactive";
						lookAhead = 0.01;
						break;
				}
			}
			this.lookAhead = lookAhead;
			this.updateInterval = lookAhead/3;
		}
	});

	/**
	 *  Clean up
	 *  @returns {Tone.Context} this
	 */
	Tone.Context.prototype.dispose = function(){
		Tone.Emitter.prototype.dispose.call(this);
		this._worker = null;
		this._timeouts.dispose();
		this._timeouts = null;
		for(var con in this._constants){
			this._constants[con].disconnect();
		}
		this._constants = null;
		this.close();
		return this;
	};

	/**
	 *  Shim all connect/disconnect and some deprecated methods which are still in
	 *  some older implementations.
	 *  @private
	 */
	function shimConnect(){

		var nativeConnect = AudioNode.prototype.connect;
		var nativeDisconnect = AudioNode.prototype.disconnect;

		//replace the old connect method
		function toneConnect(B, outNum, inNum){
			if (B.input){
				inNum = Tone.defaultArg(inNum, 0);
				if (Tone.isArray(B.input)){
					this.connect(B.input[inNum]);
				} else {
					this.connect(B.input, outNum, inNum);
				}
			} else {
				try {
					if (B instanceof AudioNode){
						nativeConnect.call(this, B, outNum, inNum);
					} else {
						nativeConnect.call(this, B, outNum);
					}
				} catch (e) {
					throw new Error("error connecting to node: "+B+"\n"+e);
				}
			}
		}

		//replace the old disconnect method
		function toneDisconnect(B, outNum, inNum){
			if (B && B.input && Tone.isArray(B.input)){
				inNum = Tone.defaultArg(inNum, 0);
				this.disconnect(B.input[inNum], outNum, 0);
			} else if (B && B.input){
				this.disconnect(B.input, outNum, inNum);
			} else {
				try {
					nativeDisconnect.apply(this, arguments);
				} catch (e) {
					throw new Error("error disconnecting node: "+B+"\n"+e);
				}
			}
		}

		if (AudioNode.prototype.connect !== toneConnect){
			AudioNode.prototype.connect = toneConnect;
			AudioNode.prototype.disconnect = toneDisconnect;
		}
	}

	// set the audio context initially
	if (Tone.supported){
		shimConnect();
		Tone.context = new Tone.Context();
	} else {
		console.warn("This browser does not support Tone.js");
	}

	return Tone.Context;
});<commit_msg>lookAhead applied to all scheduled events<commit_after>define(["Tone/core/Tone", "Tone/core/Emitter", "Tone/core/Timeline"], function (Tone) {

	/**
	 *  shim
	 *  @private
	 */
	if (!window.hasOwnProperty("AudioContext") && window.hasOwnProperty("webkitAudioContext")){
		window.AudioContext = window.webkitAudioContext;
	}

	/**
	 *  @class Wrapper around the native AudioContext.
	 *  @extends {Tone.Emitter}
	 *  @param {AudioContext=} context optionally pass in a context
	 */
	Tone.Context = function(context){

		Tone.Emitter.call(this);

		if (!context){
			context = new window.AudioContext();
		}
		this._context = context;
		// extend all of the methods
		for (var prop in this._context){
			this._defineProperty(this._context, prop);
		}

		/**
		 *  The default latency hint
		 *  @type  {String}
		 *  @private
		 */
		this._latencyHint = "interactive";

		/**
		 *  An object containing all of the constants AudioBufferSourceNodes
		 *  @type  {Object}
		 *  @private
		 */
		this._constants = {};

		///////////////////////////////////////////////////////////////////////
		// WORKER
		///////////////////////////////////////////////////////////////////////

		/**
		 *  The amount of time events are scheduled
		 *  into the future
		 *  @type  {Number}
		 *  @private
		 */
		this.lookAhead = 0.1;

		/**
		 *  How often the update look runs
		 *  @type  {Number}
		 *  @private
		 */
		this._updateInterval = this.lookAhead/3;

		/**
		 *  A reference to the actual computed update interval
		 *  @type  {Number}
		 *  @private
		 */
		this._computedUpdateInterval = 0;

		/**
		 *  The web worker which is used to update Tone.Clock
		 *  @private
		 *  @type  {WebWorker}
		 */
		this._worker = this._createWorker();

		///////////////////////////////////////////////////////////////////////
		// TIMEOUTS
		///////////////////////////////////////////////////////////////////////

		/**
		 *  All of the setTimeout events.
		 *  @type  {Tone.Timeline}
		 *  @private
		 */
		this._timeouts = new Tone.Timeline();

		/**
		 *  The timeout id counter
		 *  @private
		 *  @type {Number}
		 */
		this._timeoutIds = 0;

		this.on("tick", this._timeoutLoop.bind(this));

	};

	Tone.extend(Tone.Context, Tone.Emitter);
	Tone.Emitter.mixin(Tone.Context);

	/**
	 *  Define a property on this Tone.Context.
	 *  This is used to extend the native AudioContext
	 *  @param  {AudioContext}  context
	 *  @param  {String}  prop
	 *  @private
	 */
	Tone.Context.prototype._defineProperty = function(context, prop){
		if (Tone.isUndef(this[prop])){
			Object.defineProperty(this, prop, {
				get : function(){
					if (typeof context[prop] === "function"){
						return context[prop].bind(context);
					} else {
						return context[prop];
					}
				},
				set : function(val){
					context[prop] = val;
				}
			});
		}
	};

	/**
	 *  The current audio context time
	 *  @return  {Number}
	 */
	Tone.Context.prototype.now = function(){
		return this._context.currentTime + this.lookAhead;
	};

	/**
	 *  Generate a web worker
	 *  @return  {WebWorker}
	 *  @private
	 */
	Tone.Context.prototype._createWorker = function(){

		//URL Shim
		window.URL = window.URL || window.webkitURL;

		var blob = new Blob([
			//the initial timeout time
			"var timeoutTime = "+(this._updateInterval * 1000).toFixed(1)+";" +
			//onmessage callback
			"self.onmessage = function(msg){" +
			"	timeoutTime = parseInt(msg.data);" +
			"};" +
			//the tick function which posts a message
			//and schedules a new tick
			"function tick(){" +
			"	setTimeout(tick, timeoutTime);" +
			"	self.postMessage('tick');" +
			"}" +
			//call tick initially
			"tick();"
		]);
		var blobUrl = URL.createObjectURL(blob);
		var worker = new Worker(blobUrl);

		worker.addEventListener("message", function(){
			// tick the clock
			this.emit("tick");
		}.bind(this));

		//lag compensation
		worker.addEventListener("message", function(){
			var now = this.now();
			if (Tone.isNumber(this._lastUpdate)){
				var diff = now - this._lastUpdate;
				this._computedUpdateInterval = Math.max(diff, this._computedUpdateInterval * 0.97);
			}
			this._lastUpdate = now;
		}.bind(this));

		return worker;
	};

	/**
	 *  Generate a looped buffer at some constant value.
	 *  @param  {Number}  val
	 *  @return  {BufferSourceNode}
	 */
	Tone.Context.prototype.getConstant = function(val){
		if (this._constants[val]){
			return this._constants[val];
		} else {
			var buffer = this._context.createBuffer(1, 128, this._context.sampleRate);
			var arr = buffer.getChannelData(0);
			for (var i = 0; i < arr.length; i++){
				arr[i] = val;
			}
			var constant = this._context.createBufferSource();
			constant.channelCount = 1;
			constant.channelCountMode = "explicit";
			constant.buffer = buffer;
			constant.loop = true;
			constant.start(0);
			this._constants[val] = constant;
			return constant;
		}
	};

	/**
	 *  The private loop which keeps track of the context scheduled timeouts
	 *  Is invoked from the clock source
	 *  @private
	 */
	Tone.Context.prototype._timeoutLoop = function(){
		var now = this.now();
		while(this._timeouts && this._timeouts.length && this._timeouts.peek().time <= now){
			this._timeouts.shift().callback();
		}
	};

	/**
	 *  A setTimeout which is gaurenteed by the clock source.
	 *  Also runs in the offline context.
	 *  @param  {Function}  fn       The callback to invoke
	 *  @param  {Seconds}    timeout  The timeout in seconds
	 *  @returns {Number} ID to use when invoking Tone.Context.clearTimeout
	 */
	Tone.Context.prototype.setTimeout = function(fn, timeout){
		this._timeoutIds++;
		var now = this.now();
		this._timeouts.add({
			callback : fn,
			time : now + timeout,
			id : this._timeoutIds
		});
		return this._timeoutIds;
	};

	/**
	 *  Clears a previously scheduled timeout with Tone.context.setTimeout
	 *  @param  {Number}  id  The ID returned from setTimeout
	 *  @return  {Tone.Context}  this
	 */
	Tone.Context.prototype.clearTimeout = function(id){
		this._timeouts.forEach(function(event){
			if (event.id === id){
				this.remove(event);
			}
		});
		return this;
	};

	/**
	 *  This is the time that the clock is falling behind
	 *  the scheduled update interval. The Context automatically
	 *  adjusts for the lag and schedules further in advance.
	 *  @type {Number}
	 *  @memberOf Tone.Context
	 *  @name lag
	 *  @static
	 *  @readOnly
	 */
	Object.defineProperty(Tone.Context.prototype, "lag", {
		get : function(){
			var diff = this._computedUpdateInterval - this._updateInterval;
			diff = Math.max(diff, 0);
			return diff;
		}
	});

	/**
	 *  How often the Web Worker callback is invoked.
	 *  This number corresponds to how responsive the scheduling
	 *  can be. Context.updateInterval + Context.lookAhead gives you the
	 *  total latency between scheduling an event and hearing it.
	 *  @type {Number}
	 *  @memberOf Tone.Context
	 *  @name updateInterval
	 *  @static
	 */
	Object.defineProperty(Tone.Context.prototype, "updateInterval", {
		get : function(){
			return this._updateInterval;
		},
		set : function(interval){
			this._updateInterval = Math.max(interval, Tone.prototype.blockTime);
			this._worker.postMessage(Math.max(interval * 1000, 1));
		}
	});

	/**
	 *  The type of playback, which affects tradeoffs between audio
	 *  output latency and responsiveness.
	 *
	 *  In addition to setting the value in seconds, the latencyHint also
	 *  accepts the strings "interactive" (prioritizes low latency),
	 *  "playback" (prioritizes sustained playback), "balanced" (balances
	 *  latency and performance), and "fastest" (lowest latency, might glitch more often).
	 *  @type {String|Seconds}
	 *  @memberOf Tone.Context#
	 *  @name latencyHint
	 *  @static
	 *  @example
	 * //set the lookAhead to 0.3 seconds
	 * Tone.context.latencyHint = 0.3;
	 */
	Object.defineProperty(Tone.Context.prototype, "latencyHint", {
		get : function(){
			return this._latencyHint;
		},
		set : function(hint){
			var lookAhead = hint;
			this._latencyHint = hint;
			if (Tone.isString(hint)){
				switch(hint){
					case "interactive" :
						lookAhead = 0.1;
						this._context.latencyHint = hint;
						break;
					case "playback" :
						lookAhead = 0.8;
						this._context.latencyHint = hint;
						break;
					case "balanced" :
						lookAhead = 0.25;
						this._context.latencyHint = hint;
						break;
					case "fastest" :
						this._context.latencyHint = "interactive";
						lookAhead = 0.01;
						break;
				}
			}
			this.lookAhead = lookAhead;
			this.updateInterval = lookAhead/3;
		}
	});

	/**
	 *  Clean up
	 *  @returns {Tone.Context} this
	 */
	Tone.Context.prototype.dispose = function(){
		Tone.Emitter.prototype.dispose.call(this);
		this._worker = null;
		this._timeouts.dispose();
		this._timeouts = null;
		for(var con in this._constants){
			this._constants[con].disconnect();
		}
		this._constants = null;
		this.close();
		return this;
	};

	/**
	 *  Shim all connect/disconnect and some deprecated methods which are still in
	 *  some older implementations.
	 *  @private
	 */
	function shimConnect(){

		var nativeConnect = AudioNode.prototype.connect;
		var nativeDisconnect = AudioNode.prototype.disconnect;

		//replace the old connect method
		function toneConnect(B, outNum, inNum){
			if (B.input){
				inNum = Tone.defaultArg(inNum, 0);
				if (Tone.isArray(B.input)){
					this.connect(B.input[inNum]);
				} else {
					this.connect(B.input, outNum, inNum);
				}
			} else {
				try {
					if (B instanceof AudioNode){
						nativeConnect.call(this, B, outNum, inNum);
					} else {
						nativeConnect.call(this, B, outNum);
					}
				} catch (e) {
					throw new Error("error connecting to node: "+B+"\n"+e);
				}
			}
		}

		//replace the old disconnect method
		function toneDisconnect(B, outNum, inNum){
			if (B && B.input && Tone.isArray(B.input)){
				inNum = Tone.defaultArg(inNum, 0);
				this.disconnect(B.input[inNum], outNum, 0);
			} else if (B && B.input){
				this.disconnect(B.input, outNum, inNum);
			} else {
				try {
					nativeDisconnect.apply(this, arguments);
				} catch (e) {
					throw new Error("error disconnecting node: "+B+"\n"+e);
				}
			}
		}

		if (AudioNode.prototype.connect !== toneConnect){
			AudioNode.prototype.connect = toneConnect;
			AudioNode.prototype.disconnect = toneDisconnect;
		}
	}

	// set the audio context initially
	if (Tone.supported){
		shimConnect();
		Tone.context = new Tone.Context();
	} else {
		console.warn("This browser does not support Tone.js");
	}

	return Tone.Context;
});<|endoftext|>


<commit_before>//var map = L.map('map');

//ピンの画像を設定
var ccIcon = L.icon({
    iconUrl: 'img/gohan.png',
    iconRetinaUrl: 'img/gohan.png',
    iconSize: [50, 50],
    iconAnchor: [12, 25],
    popupAnchor: [0, 0],
});

//ピンを追加 childrencafeteria:cc
var cc1 = L.marker([34.392487, 132.475126], { icon: ccIcon }).bindPopup('青い鳥'),
    cc2 = L.marker([34.361050, 132.463745], { icon: ccIcon }).bindPopup('くるり食堂');

var childrencafeteria = L.layerGroup([
    cc1, cc2
]);

var pale = L.tileLayer('http://cyberjapandata.gsi.go.jp/xyz/pale/{z}/{x}/{y}.png',
{id: 'palemap', attribution: "国土地理院"}),
    blank = L.tileLayer('http://cyberjapandata.gsi.go.jp/xyz/blank/{z}/{x}/{y}.png',
{id: 'blankmap', attribution: "国土地理院"}),
    osm = L.tileLayer('http://tile.openstreetmap.jp/{z}/{x}/{y}.png',
{ id: 'osmmap', attribution: '© OpenStreetMap contributors' });

var map = L.map('map', {
    layers: [osm, childrencafeteria]
});

var baseMaps = {
    "淡色地図" : pale,
    "白地図"   : blank,
    "OSM japan"  : osm
};

var overlayMaps = {
    "こども食堂" : childrencafeteria
};

L.control.layers(baseMaps, overlayMaps).addTo(map);

map.setView([34.395247, 132.457659], 15);<commit_msg>経路検索のURLを追加してみる<commit_after>//var map = L.map('map');

//ピンの画像を設定
var ccIcon = L.icon({
    iconUrl: 'img/gohan.png',
    iconRetinaUrl: 'img/gohan.png',
    iconSize: [50, 50],
    iconAnchor: [12, 25],
    popupAnchor: [0, 0],
});

//ピンを追加 childrencafeteria:cc
var cc1 = L.marker([34.392487, 132.475126], { icon: ccIcon }).bindPopup('青い鳥
ここまでの経路'),
    cc2 = L.marker([34.361050, 132.463745], { icon: ccIcon }).bindPopup('くるり食堂');

var childrencafeteria = L.layerGroup([
    cc1, cc2
]);

var pale = L.tileLayer('http://cyberjapandata.gsi.go.jp/xyz/pale/{z}/{x}/{y}.png',
{id: 'palemap', attribution: "国土地理院"}),
    blank = L.tileLayer('http://cyberjapandata.gsi.go.jp/xyz/blank/{z}/{x}/{y}.png',
{id: 'blankmap', attribution: "国土地理院"}),
    osm = L.tileLayer('http://tile.openstreetmap.jp/{z}/{x}/{y}.png',
{ id: 'osmmap', attribution: '© OpenStreetMap contributors' });

var map = L.map('map', {
    layers: [osm, childrencafeteria]
});

var baseMaps = {
    "淡色地図" : pale,
    "白地図"   : blank,
    "OSM japan"  : osm
};

var overlayMaps = {
    "こども食堂" : childrencafeteria
};

L.control.layers(baseMaps, overlayMaps).addTo(map);

map.setView([34.395247, 132.457659], 15);<|endoftext|>


<commit_before>// ==========================================================================
//                          DG.InspectorView
//
//  An inspector that reconfigures based on selected tile
//
//  Author:   William Finzer
//
//  Copyright (c) 2015 by The Concord Consortium, Inc. All rights reserved.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// ==========================================================================

sc_require('views/draggable_view');
/** @class

    InspectorView floats above tiles, pinned to the right edge. I reconfigures based on
 currently selected tile.

 @extends DG.DraggableView
 */
DG.InspectorView = DG.DraggableView.extend(
    /** @scope DG.InspectorView.prototype */
    (function () {
      var kAnimationTime = 0.2,
          kCollapsedWidth = 0,
          kExpandedWidth = 50,
          kCellHeight = 50,
          kDefaultIconSize = 32,
          kPadding = (kCellHeight - kDefaultIconSize) / 2;
      return {
        classNames: ['dg-inspector-palette', 'dg-inspector-view'],
        transitionIn: SC.View,
        isResizable: false,
        isClosable: false,

        componentContainer: null,
        targetComponent: null,

        init: function () {
          sc_super();
          this.set('layout', { height: kCellHeight, width: kCollapsedWidth});
          this.selectedComponentDidChange();
        },

        targetComponentDidChange: function () {

          var removeChildren = function () {
                var tChildren = this.get('childViews'),
                    tChild;
                // We call removeChild for each member of the array. This has the side effect of modifying the array
                                                  // eslint-disable-next-line no-cond-assign
                while (tChild = tChildren[0]) {   // jshint ignore:line
                  this.removeChild(tChild);
                }
              }.bind(this),

              adjustLayout = function () {
                var tChildren = this.get('childViews'),
                    tCurrTop = kPadding;
                tChildren.forEach(function (iChild, iIndex) {
                  if( iChild.get('isVisible')) {
                    iChild.adjust({top: tCurrTop, left: (kCellHeight - iChild.iconExtent.width) / 2});
                    tCurrTop += iChild.iconExtent.height + 2 * kPadding;
                  }
                });
                this.animate('height', Math.max(kCellHeight, tCurrTop - kPadding), kAnimationTime,
                              finishUp);
              }.bind(this),

              finishUp = function() {
                this.invokeLater( this.scrollToVisible);
              }.bind( this);

          var tTarget = this.get('targetComponent');
          if (tTarget) {
            tTarget.addObserver('layout', this, 'targetLayoutDidChange');
          }
          this.targetLayoutDidChange();
          this.get('childViews').forEach( function( iChild) {
            iChild.removeObserver( 'isVisible', this, adjustLayout);
          });
          removeChildren();
          var tWidth,
              tButtons = this.getPath('targetComponent.inspectorButtons');
          if (tButtons && tButtons.length > 0) {
            tButtons.forEach(function (iButton) {
              this.appendChild(iButton);
              iButton.addObserver( 'isVisible', this, adjustLayout);
            }.bind(this));
            tWidth = kExpandedWidth;
          }
          else {
            tWidth = kCollapsedWidth;
          }
          this.animate('width', tWidth, kAnimationTime, adjustLayout);
        }.observes('targetComponent'),

        selectedComponentDidChange: function () {
          var tTarget = this.get('targetComponent');
          if (tTarget) {
            tTarget.removeObserver('layout', this, 'targetLayoutDidChange');
          }
          this.set('targetComponent', this.getPath('componentContainer.selectedChildView'));
        }.observes('*componentContainer.selectedChildView'),

        targetLayoutDidChange: function () {
          var tTargetFrame = this.getPath('targetComponent.frame');
          if (tTargetFrame) {
            this.adjust('top', tTargetFrame.y);
              this.adjust('left', tTargetFrame.x + tTargetFrame.width);
          }
        },

        /**
         * Called during drag
         * @param iEvent
         * @param iInfo {pageX: mouse starting X
                         pageY: pageY, mouse starting Y
                         left: original layout.left
                         top: original layout.top,
                         height: original layout.height,
                         width: original layout.width }
         */
        dragAdjust: function (iEvent, iInfo) {
          var tTargetFrame = this.getPath('targetComponent.frame'),
              tMouseMovedY = iEvent.pageY - iInfo.pageY,
              tNewTop = iInfo.top + tMouseMovedY;
          tNewTop = Math.max(tTargetFrame.y, tNewTop);
          tNewTop = Math.min(tNewTop, tTargetFrame.y + tTargetFrame.height);
          this.adjust('top', tNewTop);
        }

      };  // object returned closure
    }()) // function closure
);

<commit_msg>Fix case card palette<commit_after>// ==========================================================================
//                          DG.InspectorView
//
//  An inspector that reconfigures based on selected tile
//
//  Author:   William Finzer
//
//  Copyright (c) 2015 by The Concord Consortium, Inc. All rights reserved.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// ==========================================================================

sc_require('views/draggable_view');
/** @class

    InspectorView floats above tiles, pinned to the right edge. I reconfigures based on
 currently selected tile.

 @extends DG.DraggableView
 */
DG.InspectorView = DG.DraggableView.extend(
    /** @scope DG.InspectorView.prototype */
    (function () {
      var kAnimationTime = 0.2,
          kCollapsedWidth = 0,
          kExpandedWidth = 50,
          kCellHeight = 50,
          kDefaultIconSize = 32,
          kPadding = (kCellHeight - kDefaultIconSize) / 2;
      return {
        classNames: ['dg-inspector-palette', 'dg-inspector-view'],
        transitionIn: SC.View,
        isResizable: false,
        isClosable: false,

        componentContainer: null,
        targetComponent: null,

        init: function () {
          sc_super();
          this.set('layout', { height: kCellHeight, width: kCollapsedWidth});
          this.selectedComponentDidChange();
        },

        adjustLayout: function () {
          var tChildren = this.get('childViews'),
              tCurrTop = kPadding;
          tChildren.forEach(function (iChild, iIndex) {
            if (iChild.get('isVisible')) {
              iChild.adjust({top: tCurrTop, left: (kCellHeight - iChild.iconExtent.width) / 2});
              tCurrTop += iChild.iconExtent.height + 2 * kPadding;
            }
          });
          this.animate('height', Math.max(kCellHeight, tCurrTop - kPadding), kAnimationTime,
                        function() { this.invokeLater(this.scrollToVisible); }.bind(this));
        },

        targetComponentDidChange: function () {

          var removeChildren = function () {
                var tChildren = this.get('childViews'),
                    tChild;
                // We call removeChild for each member of the array. This has the side effect of modifying the array
                                                  // eslint-disable-next-line no-cond-assign
                while (tChild = tChildren[0]) {   // jshint ignore:line
                  this.removeChild(tChild);
                }
              }.bind(this);

          var tTarget = this.get('targetComponent');
          if (tTarget) {
            tTarget.addObserver('layout', this, 'targetLayoutDidChange');
          }
          this.targetLayoutDidChange();
          this.get('childViews').forEach( function( iChild) {
            iChild.removeObserver( 'isVisible', this, 'adjustLayout');
          }.bind(this));
          removeChildren();
          this.inspectorButtonsDidChange();
        }.observes('targetComponent'),

        selectedComponentDidChange: function () {
          var tTarget = this.get('targetComponent');
          if (tTarget) {
            tTarget.removeObserver('layout', this, 'targetLayoutDidChange');
          }
          this.set('targetComponent', this.getPath('componentContainer.selectedChildView'));
        }.observes('*componentContainer.selectedChildView'),

        targetLayoutDidChange: function () {
          var tTargetFrame = this.getPath('targetComponent.frame');
          if (tTargetFrame) {
            this.adjust('top', tTargetFrame.y);
            this.adjust('left', tTargetFrame.x + tTargetFrame.width);
          }
        },

        inspectorButtonsDidChange: function () {
          var tWidth,
              tButtons = this.getPath('targetComponent.inspectorButtons');
          if (tButtons && tButtons.length > 0) {
            tButtons.forEach(function (iButton) {
              this.appendChild(iButton);
              iButton.addObserver('isVisible', this, 'adjustLayout');
            }.bind(this));
            tWidth = kExpandedWidth;
          }
          else {
            tWidth = kCollapsedWidth;
          }
          this.animate('width', tWidth, kAnimationTime, this, 'adjustLayout');
        }.observes('*targetComponent.inspectorButtons'),

        /**
         * Called during drag
         * @param iEvent
         * @param iInfo {pageX: mouse starting X
                         pageY: pageY, mouse starting Y
                         left: original layout.left
                         top: original layout.top,
                         height: original layout.height,
                         width: original layout.width }
         */
        dragAdjust: function (iEvent, iInfo) {
          var tTargetFrame = this.getPath('targetComponent.frame'),
              tMouseMovedY = iEvent.pageY - iInfo.pageY,
              tNewTop = iInfo.top + tMouseMovedY;
          tNewTop = Math.max(tTargetFrame.y, tNewTop);
          tNewTop = Math.min(tNewTop, tTargetFrame.y + tTargetFrame.height);
          this.adjust('top', tNewTop);
        }

      };  // object returned closure
    }()) // function closure
);

<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 *  WSO2 Inc. licenses this file to you under the Apache License,
 *  Version 2.0 (the "License"); you may not use this file except
 *  in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations
 *  under the License.
 *
 */
var pageDecorators = {};
(function(pageDecorators) {
    var log = new Log();
    var isActivatedAsset = function(assetType, tenantId) {
        var app = require('rxt').app;
        var activatedAssets = app.getUIActivatedAssets(tenantId); //ctx.tenantConfigs.assets;
        //return true;
        if (!activatedAssets) {
            throw 'Unable to load all activated assets for current tenant: ' + tenatId + '.Make sure that the assets property is present in the tenant config';
        }
        for (var index in activatedAssets) {
            if (activatedAssets[index] == assetType) {
                return true;
            }
        }
        return false;
    };
    pageDecorators.navigationBar = function(ctx, page, utils) {
        var permissionAPI = require('rxt').permissions;
        var ribbon = page.ribbon = {};
        var DEFAULT_ICON = 'icon-cog';
        var assetTypes = [];
        var assetType;
        var assetList = ctx.rxtManager.listRxtTypeDetails();
        for (var index in assetList) {
            assetType = assetList[index];
            //Only populate the link if the asset type is activated and the logged in user has permission to that asset
            if ((isActivatedAsset(assetType.shortName, ctx.tenantId)) && (permissionAPI.hasAssetPermission(permissionAPI.ASSET_LIST, assetType.shortName, ctx.session))) {
                assetTypes.push({
                    url: utils.buildAssetPageUrl(assetType.shortName, '/list'),
                    assetIcon: assetType.ui.icon || DEFAULT_ICON,
                    assetTitle: assetType.pluralLabel
                });
            }
        }
        ribbon.currentType = page.rxt.singularLabel;
        ribbon.currentTitle = page.rxt.singularLabel;
        ribbon.currentUrl = utils.buildAssetPageUrl(assetType.shortName, '/list'); //page.meta.currentPage;
        ribbon.shortName = page.rxt.singularLabel;
        ribbon.query = 'Query';
        ribbon.breadcrumb = assetTypes;
        return page;
    };
    pageDecorators.assetCategoryDetails = function(ctx, page, utils) {
        if (page.meta.pageName != 'list') {
            return;
        }
        page.assetCategoryDetails = {};
        page.assetCategoryDetails.hasCategories = false;
        page.assetCategoryDetails.values = [];
        var categoryField = ctx.rxtManager.getCategoryField(ctx.assetType);
        var categoryValues = [];
        var field = ctx.rxtManager.getRxtField(ctx.assetType, categoryField);
        var q = request.getParameter("q");
        if (q) {
            var options = parse("{" + q + "}");
            if (options.category) {
                page.assetCategoryDetails.selectedCategory = options.category;
            }
        }
        if (!field) {
            return;
        }
        var values = field.values[0].value;
        if (!values) {
            return;
        }
        for (var index = 0; index < values.length; index++) {
            categoryValues.push(values[index].value);
        }
        page.assetCategoryDetails.hasCategories = true;
        page.assetCategoryDetails.values = categoryValues;
    };
    pageDecorators.populateGroupingFeatureDetails = function(ctx, page) {
        page.groupingFeature = {};
        page.groupingFeature.isEnabled = ctx.rxtManager.isGroupingEnabled(ctx.assetType);
    };
    pageDecorators.populateAttachedLifecycles = function(ctx, page, utils) {
        var am = assetManager(ctx);
        //Check if an asset exists
        if ((page.assets) && (page.assets.id)) {
            var lifecycles; // = am.listAllAttachedLifecycles(page.assets.id);
            //TODO:Temp fix since the listAllAttachedLifecycles method does not
            //return all attached lifecycles
            var resource = am.am.registry.get(page.assets.path);
            if (!resource) {
                log.error('Unable to retrieve the attached lifecycle details');
                return;
            }
            lifecycles = resource.aspects();
            var lifecycle;
            var modifiedLifecycles = [];
            var entry;
            for (var index = 0; index < lifecycles.length; index++) {
                lifecycle = lifecycles[index];
                entry = {};
                entry.active = false;
                entry.name = lifecycle;
                if (page.assets.lifecycle === lifecycle) {
                    entry.active = true;
                }
                modifiedLifecycles.push(entry);
            }
            page.assets.availableLifecycles = modifiedLifecycles;
            page.assets.hasMultipleLifecycles = (lifecycles.length > 1) ? true : false;
        }
    };
    pageDecorators.populateAssetVersionDetails = function(ctx, page, utils) {
        if ((page.assets) && (page.assets.id)) {
            var am = assetManager(ctx);
            var info = page.assets;
            info.versions = [];
            var versions;
            var asset;
            var assetInstance = am.get(page.assets.id);
            var entry;
            versions = am.getAssetGroup(assetInstance || {});
            versions.sort(function(a1, a2) {
                return am.compareVersions(a1, a2);
            });
            info.isDefault = am.isDefaultAsset(page.assets);
            info.version = assetInstance.version;
            for (var index = 0; index < versions.length; index++) {
                asset = versions[index];
                entry = {};
                entry.id = asset.id;
                entry.name = asset.name;
                entry.version = asset.version;
                entry.isDefault = am.isDefaultAsset(asset);
                if (asset.id == page.assets.id) {
                    entry.selected = true;
                    info.version = asset.version;
                } else {
                    entry.selected = false;
                }
                entry.assetURL = utils.buildAssetPageUrl(ctx.assetType, '/details/' + entry.id);
                info.versions.push(entry);
            }
            info.hasMultipleVersions = (info.versions.length > 0) ? true : false;
        }
    };
    pageDecorators.populateTagDetails = function(ctx,page,utils){
        var am = assetManager(ctx);
        if(log.isDebugEnabled()){
            log.debug('Fetching tags for asset : ' + page.assets.name);
        }
        page.assetTags = am.getTags(page.assets.id);
        if(log.isDebugEnabled()){
            log.debug(page.assetTags);
        }
    };
    pageDecorators.sorting = function (ctx, page, fields) {
        var queryString = request.getQueryString();
        var sortable = fields || [
            {field:"overview_name",label:"Name"},
            {field:"overview_version",label:"Version"},
            {field:"overview_provider",label:"Provider"},
            {field:"createdDate",label:"Date/Time"}];
        var sortingList = [];
        var sortingListSelected = {};
        var sortBy = "createdDate";
        var sort = "-";
        if(queryString){
            var sortCombined = "";
            var parts = queryString.split('&');
            for(var i=0;i<parts.length;i++){
                if(parts[i].indexOf("=") != -1 ){
                    var params = parts[i].split("=");
                    if(params[0] == "sort"){
                        sortCombined = params[1];
                    }
                }
            }
            //sortCombined is a string in the format -overview_createdtime
            if(new RegExp("^[+]").test(sortCombined)){
                sort = "+";
                sortBy = sortCombined.substring(1);
            }else if(new RegExp("^[-]").test(sortCombined)){
                sort = "-";
                sortBy = sortCombined.substring(1);
            }
        }
        for(i=0;i<sortable.length;i++){
            var sortObj = {};
            sortObj.sortBy = sortable[i];
            sortObj.sort = "-";
            sortObj.active = false;
            sortObj.sortNext = "+";
            sortObj.sortIcon = "sorting_asc";
            if(sortable[i].field == sortBy) {
                if(sort == "+") {
                    sortingListSelected.helpIcon = "fw-sort-up margin-bottom-align";
                    sortObj.sortNext = "-";
                    sortObj.sortIcon = "sorting_asc";
                } else if(sort == "-") {
                    sortingListSelected.helpIcon = "fw-sort-down margin-top-align";
                    sortObj.sortNext = "+";
                    sortObj.sortIcon = "sorting_desc";
                }
                sortingListSelected.help = sortable[i].label;
                sortObj.active = true;
            }
            sortingList.push(sortObj);
        }
        page.sorting = {selected:sortingListSelected,list:sortingList};
        return page;
    };
    pageDecorators.hideEmptyTables = function(ctx,page,type){
        var table;
        var tables = page.assets.tables||[];
        for(var tableIndex=0; tableIndex < tables.length; tableIndex++){
            table = tables[tableIndex];
            table.renderingMetaData = {};
            if(isEmptyTable(table)){
                table.renderingMetaData.emptyTable = true;
            }
        }
    };
    pageDecorators.populateAssetPageBreadcrumb = function(ctx,page,utils){
        var Breadcrumb = require('rxt').app.Breadcrumb;
        var breadcrumb = new Breadcrumb(page.breadcrumb);

        if(!page.rxt) {
            return;
        }
        breadcrumb.crumb(page.rxt.pluralLabel.toUpperCase(),utils.buildUrl('list'));
        if(!page.assets.name) {
            page.breadcrumb  = breadcrumb.build();
            return;
        }
        breadcrumb.crumb(page.assets.name.toUpperCase(),utils.buildUrl('details')+'/'+page.assets.id);
        page.breadcrumb = breadcrumb.build();
    };
    var isEmptyTable = function(table){
        var field;
        var fields = table.fields;
        for(var fieldKey in fields){
            field = fields[fieldKey];
            if(field.hasOwnProperty('value')){
                return false;
            }
        }
        return true;
    };
    var assetManager = function(ctx) {
        var rxt = require('rxt');
        var type = ctx.assetType;
        var am = rxt.asset.createUserAssetManager(ctx.session, type);
        return am;
    };
}(pageDecorators));<commit_msg>Fix for STORE-1321: Check for pageName for list page, and get sortable field names through rxtManager for used in sort menu<commit_after>/*
 *  Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 *  WSO2 Inc. licenses this file to you under the Apache License,
 *  Version 2.0 (the "License"); you may not use this file except
 *  in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations
 *  under the License.
 *
 */
var pageDecorators = {};
(function(pageDecorators) {
    var log = new Log();
    var isActivatedAsset = function(assetType, tenantId) {
        var app = require('rxt').app;
        var activatedAssets = app.getUIActivatedAssets(tenantId); //ctx.tenantConfigs.assets;
        //return true;
        if (!activatedAssets) {
            throw 'Unable to load all activated assets for current tenant: ' + tenatId + '.Make sure that the assets property is present in the tenant config';
        }
        for (var index in activatedAssets) {
            if (activatedAssets[index] == assetType) {
                return true;
            }
        }
        return false;
    };
    pageDecorators.navigationBar = function(ctx, page, utils) {
        var permissionAPI = require('rxt').permissions;
        var ribbon = page.ribbon = {};
        var DEFAULT_ICON = 'icon-cog';
        var assetTypes = [];
        var assetType;
        var assetList = ctx.rxtManager.listRxtTypeDetails();
        for (var index in assetList) {
            assetType = assetList[index];
            //Only populate the link if the asset type is activated and the logged in user has permission to that asset
            if ((isActivatedAsset(assetType.shortName, ctx.tenantId)) && (permissionAPI.hasAssetPermission(permissionAPI.ASSET_LIST, assetType.shortName, ctx.session))) {
                assetTypes.push({
                    url: utils.buildAssetPageUrl(assetType.shortName, '/list'),
                    assetIcon: assetType.ui.icon || DEFAULT_ICON,
                    assetTitle: assetType.pluralLabel
                });
            }
        }
        ribbon.currentType = page.rxt.singularLabel;
        ribbon.currentTitle = page.rxt.singularLabel;
        ribbon.currentUrl = utils.buildAssetPageUrl(assetType.shortName, '/list'); //page.meta.currentPage;
        ribbon.shortName = page.rxt.singularLabel;
        ribbon.query = 'Query';
        ribbon.breadcrumb = assetTypes;
        return page;
    };
    pageDecorators.assetCategoryDetails = function(ctx, page, utils) {
        if (page.meta.pageName != 'list') {
            return;
        }
        page.assetCategoryDetails = {};
        page.assetCategoryDetails.hasCategories = false;
        page.assetCategoryDetails.values = [];
        var categoryField = ctx.rxtManager.getCategoryField(ctx.assetType);
        var categoryValues = [];
        var field = ctx.rxtManager.getRxtField(ctx.assetType, categoryField);
        var q = request.getParameter("q");
        if (q) {
            var options = parse("{" + q + "}");
            if (options.category) {
                page.assetCategoryDetails.selectedCategory = options.category;
            }
        }
        if (!field) {
            return;
        }
        var values = field.values[0].value;
        if (!values) {
            return;
        }
        for (var index = 0; index < values.length; index++) {
            categoryValues.push(values[index].value);
        }
        page.assetCategoryDetails.hasCategories = true;
        page.assetCategoryDetails.values = categoryValues;
    };
    pageDecorators.populateGroupingFeatureDetails = function(ctx, page) {
        page.groupingFeature = {};
        page.groupingFeature.isEnabled = ctx.rxtManager.isGroupingEnabled(ctx.assetType);
    };
    pageDecorators.populateAttachedLifecycles = function(ctx, page, utils) {
        var am = assetManager(ctx);
        //Check if an asset exists
        if ((page.assets) && (page.assets.id)) {
            var lifecycles; // = am.listAllAttachedLifecycles(page.assets.id);
            //TODO:Temp fix since the listAllAttachedLifecycles method does not
            //return all attached lifecycles
            var resource = am.am.registry.get(page.assets.path);
            if (!resource) {
                log.error('Unable to retrieve the attached lifecycle details');
                return;
            }
            lifecycles = resource.aspects();
            var lifecycle;
            var modifiedLifecycles = [];
            var entry;
            for (var index = 0; index < lifecycles.length; index++) {
                lifecycle = lifecycles[index];
                entry = {};
                entry.active = false;
                entry.name = lifecycle;
                if (page.assets.lifecycle === lifecycle) {
                    entry.active = true;
                }
                modifiedLifecycles.push(entry);
            }
            page.assets.availableLifecycles = modifiedLifecycles;
            page.assets.hasMultipleLifecycles = (lifecycles.length > 1) ? true : false;
        }
    };
    pageDecorators.populateAssetVersionDetails = function(ctx, page, utils) {
        if ((page.assets) && (page.assets.id)) {
            var am = assetManager(ctx);
            var info = page.assets;
            info.versions = [];
            var versions;
            var asset;
            var assetInstance = am.get(page.assets.id);
            var entry;
            versions = am.getAssetGroup(assetInstance || {});
            versions.sort(function(a1, a2) {
                return am.compareVersions(a1, a2);
            });
            info.isDefault = am.isDefaultAsset(page.assets);
            info.version = assetInstance.version;
            for (var index = 0; index < versions.length; index++) {
                asset = versions[index];
                entry = {};
                entry.id = asset.id;
                entry.name = asset.name;
                entry.version = asset.version;
                entry.isDefault = am.isDefaultAsset(asset);
                if (asset.id == page.assets.id) {
                    entry.selected = true;
                    info.version = asset.version;
                } else {
                    entry.selected = false;
                }
                entry.assetURL = utils.buildAssetPageUrl(ctx.assetType, '/details/' + entry.id);
                info.versions.push(entry);
            }
            info.hasMultipleVersions = (info.versions.length > 0) ? true : false;
        }
    };
    pageDecorators.populateTagDetails = function(ctx,page,utils){
        var am = assetManager(ctx);
        if(log.isDebugEnabled()){
            log.debug('Fetching tags for asset : ' + page.assets.name);
        }
        page.assetTags = am.getTags(page.assets.id);
        if(log.isDebugEnabled()){
            log.debug(page.assetTags);
        }
    };
    pageDecorators.sorting = function (ctx, page, fields) {
        if(page.meta.pageName !== 'list'){
            return;
        }
        var names = ctx.rxtManager.getSortingNames(ctx.assetType);
        var queryString = request.getQueryString();
        var sortable = fields || names;
        var sortingList = [];
        var sortingListSelected = {};
        var sortBy = "createdDate";
        var sort = "-";
        if(queryString){
            var sortCombined = "";
            var parts = queryString.split('&');
            for(var i=0;i<parts.length;i++){
                if(parts[i].indexOf("=") != -1 ){
                    var params = parts[i].split("=");
                    if(params[0] == "sort"){
                        sortCombined = params[1];
                    }
                }
            }
            //sortCombined is a string in the format -overview_createdtime
            if(new RegExp("^[+]").test(sortCombined)){
                sort = "+";
                sortBy = sortCombined.substring(1);
            }else if(new RegExp("^[-]").test(sortCombined)){
                sort = "-";
                sortBy = sortCombined.substring(1);
            }
        }
        for(i=0;i<sortable.length;i++){
            var sortObj = {};
            sortObj.sortBy = sortable[i];
            sortObj.sort = "-";
            sortObj.active = false;
            sortObj.sortNext = "+";
            sortObj.sortIcon = "sorting_asc";
            if(sortable[i].field == sortBy) {
                if(sort == "+") {
                    sortingListSelected.helpIcon = "fw-sort-up margin-bottom-align";
                    sortObj.sortNext = "-";
                    sortObj.sortIcon = "sorting_asc";
                } else if(sort == "-") {
                    sortingListSelected.helpIcon = "fw-sort-down margin-top-align";
                    sortObj.sortNext = "+";
                    sortObj.sortIcon = "sorting_desc";
                }
                sortingListSelected.help = sortable[i].label;
                sortObj.active = true;
            }
            sortingList.push(sortObj);
        }
        page.sorting = {selected:sortingListSelected,list:sortingList};
        return page;
    };
    pageDecorators.hideEmptyTables = function(ctx,page,type){
        var table;
        var tables = page.assets.tables||[];
        for(var tableIndex=0; tableIndex < tables.length; tableIndex++){
            table = tables[tableIndex];
            table.renderingMetaData = {};
            if(isEmptyTable(table)){
                table.renderingMetaData.emptyTable = true;
            }
        }
    };
    pageDecorators.populateAssetPageBreadcrumb = function(ctx,page,utils){
        var Breadcrumb = require('rxt').app.Breadcrumb;
        var breadcrumb = new Breadcrumb(page.breadcrumb);

        if(!page.rxt) {
            return;
        }
        breadcrumb.crumb(page.rxt.pluralLabel.toUpperCase(),utils.buildUrl('list'));
        if(!page.assets.name) {
            page.breadcrumb  = breadcrumb.build();
            return;
        }
        breadcrumb.crumb(page.assets.name.toUpperCase(),utils.buildUrl('details')+'/'+page.assets.id);
        page.breadcrumb = breadcrumb.build();
    };
    var isEmptyTable = function(table){
        var field;
        var fields = table.fields;
        for(var fieldKey in fields){
            field = fields[fieldKey];
            if(field.hasOwnProperty('value')){
                return false;
            }
        }
        return true;
    };
    var assetManager = function(ctx) {
        var rxt = require('rxt');
        var type = ctx.assetType;
        var am = rxt.asset.createUserAssetManager(ctx.session, type);
        return am;
    };
}(pageDecorators));<|endoftext|>


<commit_before>'use strict';

import Esa from '../src/js/esa';
jest.unmock('../src/js/esa.js');

import Promise from 'promise';
import $ from 'jquery';

let config = { teamName: 'test', token: 'token' };
const esa = new Esa(config);

describe('Esa', () => {
  describe('search', () => {
    beforeAll(() => {
      $.ajax = jest.fn(() => {
        return new Promise(() => {});
      });
    });

    it('should request Esa search API by ajax', async () => {
      let q = 'search query';

      esa.search(q, () => {}, () => {});
      expect($.ajax).toBeCalledWith({
        data: {
          access_token: config.token,
          q: q,
        },
        type: 'GET',
        url: `https://api.esa.io/v1/teams/${config.teamName}/posts`,
      });
    });

    describe('when ajax succeeded', () => {
      beforeAll(() => {
        $.ajax = jest.fn(() => {
          return new Promise((resolve, _) => {
            resolve({
              posts: [{ number: 123, name: 'name', body_md: '- body' }],
            });
          });
        });
      });

      it('should call callback for success', async () => {
        let callback = jest.fn((data) => {
          expect(data.posts).toEqual([
            { number: 123, name: 'name', body_md: '- body' },
          ]);
        });

        await esa.search('search query', callback, () => {});
      });
    });

    describe('when ajax failed', () => {
      beforeAll(() => {
        $.ajax = jest.fn(() => {
          return new Promise((_, reject) => {
            reject({
              posts: [{ number: 123, name: 'name', body_md: '- body' }],
            });
          });
        });
      });

      it('should call callback for error', async () => {
        let errCallback = jest.fn((data) => {
          expect(data.posts).toEqual([
            { number: 123, name: 'name', body_md: '- body' },
          ]);
        });

        await esa.search('search query', () => {}, errCallback);
      });
    });
  });

  describe('save', () => {
    beforeAll(() => {
      $.ajax = jest.fn(() => {
        return new Promise(() => {});
      });
    });

    describe('when post has no id', () => {
      it('should POST request Esa post API by ajax', async () => {
        let post = { name: 'name', body_md: '- body' };

        esa.save(post, () => {}, () => {});
        expect($.ajax).toBeCalledWith({
          data: {
            access_token: config.token,
            post: post,
          },
          type: 'POST',
          url: `https://api.esa.io/v1/teams/${config.teamName}/posts`,
        });
      });
    });

    describe('when post has id', () => {
      it('should PATCH request Esa post API by ajax', async () => {
        let post = { id: 123, name: 'name', body_md: '- body' };

        esa.save(post, () => {}, () => {});
        expect($.ajax).toBeCalledWith({
          data: {
            access_token: config.token,
            post: post,
          },
          type: 'PATCH',
          url: `https://api.esa.io/v1/teams/${config.teamName}/posts/${
            post.id
          }`,
        });
      });
    });

    describe('callbacks', () => {
      let post = { name: 'name', body_md: '- body' };

      describe('when ajax succeeded', () => {
        beforeAll(() => {
          $.ajax = jest.fn(() => {
            return new Promise((resolve, _) => {
              resolve({
                posts: [{ number: 123, name: 'name', body_md: '- body' }],
              });
            });
          });
        });

        it('should call callback for success', async () => {
          let callback = jest.fn((data) => {
            expect(data.posts).toEqual([
              { number: 123, name: 'name', body_md: '- body' },
            ]);
          });

          await esa.save(post, callback, () => {});
        });
      });

      describe('when ajax failed', () => {
        beforeAll(() => {
          $.ajax = jest.fn(() => {
            return new Promise((_, reject) => {
              reject({
                posts: [{ number: 123, name: 'name', body_md: '- body' }],
              });
            });
          });
        });

        it('should call callback for error', async () => {
          let errCallback = jest.fn((data) => {
            expect(data.posts).toEqual([
              { number: 123, name: 'name', body_md: '- body' },
            ]);
          });

          await esa.save(post, () => {}, errCallback);
        });
      });
    });
  });
});
<commit_msg>spec: Add "#" for prototype method name in each describe<commit_after>'use strict';

import Esa from '../src/js/esa';
jest.unmock('../src/js/esa.js');

import Promise from 'promise';
import $ from 'jquery';

let config = { teamName: 'test', token: 'token' };
const esa = new Esa(config);

describe('Esa', () => {
  describe('#search', () => {
    beforeAll(() => {
      $.ajax = jest.fn(() => {
        return new Promise(() => {});
      });
    });

    it('should request Esa search API by ajax', async () => {
      let q = 'search query';

      esa.search(q, () => {}, () => {});
      expect($.ajax).toBeCalledWith({
        data: {
          access_token: config.token,
          q: q,
        },
        type: 'GET',
        url: `https://api.esa.io/v1/teams/${config.teamName}/posts`,
      });
    });

    describe('when ajax succeeded', () => {
      beforeAll(() => {
        $.ajax = jest.fn(() => {
          return new Promise((resolve, _) => {
            resolve({
              posts: [{ number: 123, name: 'name', body_md: '- body' }],
            });
          });
        });
      });

      it('should call callback for success', async () => {
        let callback = jest.fn((data) => {
          expect(data.posts).toEqual([
            { number: 123, name: 'name', body_md: '- body' },
          ]);
        });

        await esa.search('search query', callback, () => {});
      });
    });

    describe('when ajax failed', () => {
      beforeAll(() => {
        $.ajax = jest.fn(() => {
          return new Promise((_, reject) => {
            reject({
              posts: [{ number: 123, name: 'name', body_md: '- body' }],
            });
          });
        });
      });

      it('should call callback for error', async () => {
        let errCallback = jest.fn((data) => {
          expect(data.posts).toEqual([
            { number: 123, name: 'name', body_md: '- body' },
          ]);
        });

        await esa.search('search query', () => {}, errCallback);
      });
    });
  });

  describe('#save', () => {
    beforeAll(() => {
      $.ajax = jest.fn(() => {
        return new Promise(() => {});
      });
    });

    describe('when post has no id', () => {
      it('should POST request Esa post API by ajax', async () => {
        let post = { name: 'name', body_md: '- body' };

        esa.save(post, () => {}, () => {});
        expect($.ajax).toBeCalledWith({
          data: {
            access_token: config.token,
            post: post,
          },
          type: 'POST',
          url: `https://api.esa.io/v1/teams/${config.teamName}/posts`,
        });
      });
    });

    describe('when post has id', () => {
      it('should PATCH request Esa post API by ajax', async () => {
        let post = { id: 123, name: 'name', body_md: '- body' };

        esa.save(post, () => {}, () => {});
        expect($.ajax).toBeCalledWith({
          data: {
            access_token: config.token,
            post: post,
          },
          type: 'PATCH',
          url: `https://api.esa.io/v1/teams/${config.teamName}/posts/${
            post.id
          }`,
        });
      });
    });

    describe('callbacks', () => {
      let post = { name: 'name', body_md: '- body' };

      describe('when ajax succeeded', () => {
        beforeAll(() => {
          $.ajax = jest.fn(() => {
            return new Promise((resolve, _) => {
              resolve({
                posts: [{ number: 123, name: 'name', body_md: '- body' }],
              });
            });
          });
        });

        it('should call callback for success', async () => {
          let callback = jest.fn((data) => {
            expect(data.posts).toEqual([
              { number: 123, name: 'name', body_md: '- body' },
            ]);
          });

          await esa.save(post, callback, () => {});
        });
      });

      describe('when ajax failed', () => {
        beforeAll(() => {
          $.ajax = jest.fn(() => {
            return new Promise((_, reject) => {
              reject({
                posts: [{ number: 123, name: 'name', body_md: '- body' }],
              });
            });
          });
        });

        it('should call callback for error', async () => {
          let errCallback = jest.fn((data) => {
            expect(data.posts).toEqual([
              { number: 123, name: 'name', body_md: '- body' },
            ]);
          });

          await esa.save(post, () => {}, errCallback);
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>var ticket_data = null;

function short_hash(data, type, row, meta)
{
    var short_hash = data.substring(0,7);
    return ''+short_hash+'';
}

function get_ticket_by_selected()
{
    if(ticket_data.selected == -1)
    {
        return ticket_data.current;
    }
    return ticket_data.history[ticket_data.selected];
}

function show_ticket_from_data(data)
{
    var read_only = true;
    if(data.selected == -1)
    {
        ticket = data.current;
        $('#right_arrow').hide();
        if(data.history !== undefined && data.history.length > 0)
        {
            $('#left_arrow').show();
        }
        else
        {
            $('#left_arrow').hide();
        }
        read_only = false;
        $('#saveticket').removeAttr('disabled');
    }
    else
    {
        ticket = data.history[data.selected];
        if(data.selected == (data.history.length - 1))
        {
            $('#left_arrow').hide();
        }
        else
        {
            $('#left_arrow').show();
        }
        $('#right_arrow').show();
        $('#saveticket').attr('disabled', 'true');
    }
    $('#hash').val(ticket.hash);
    $('#year').val(ticket.year);
    $('#firstName').val(ticket.firstName);
    $('#lastName').val(ticket.lastName);
    $('#email').val(ticket.email);
    $('#request_id').val(ticket.request_id);
    $('#type').val(ticket.type);
    $('#guardian_first').val(ticket.guardian_first);
    $('#guardian_last').val(ticket.guardian_last);
    if(ticket.sold == 1)
    {
        $('#sold').prop('checked', true);
    }
    else
    {
        $('#sold').prop('checked', false);
    }
    if(ticket.used == 1)
    {
        $('#used').prop('checked', true);
    }
    else
    {
        $('#used').prop('checked', false);
    }
    if(ticket.void == 1)
    {
        $('#void').prop('checked', true);
    }
    else
    {
        $('#void').prop('checked', false);
    }
    $('#comments').val(ticket.comments);
    if(read_only)
    {
        $('#firstName').prop('disabled', true);
        $('#lastName').prop('disabled', true);
        $('#email').prop('disabled', true);
        $('#request_id').prop('disabled', true);
        $('#type').prop('disabled', true);
        $('#guardian_first').prop('disabled', true);
        $('#guardian_last').prop('disabled', true);
        $('#sold').prop('disabled', true);
        $('#used').prop('disabled', true);
        $('#void').prop('disabled', true);
        $('#comments').prop('disabled', true);
    }
    else
    {
        $('#firstName').prop('disabled', false);
        $('#lastName').prop('disabled', false);
        $('#email').prop('disabled', false);
        $('#request_id').prop('disabled', false);
        $('#type').prop('disabled', false);
        $('#guardian_first').prop('disabled', false);
        $('#guardian_last').prop('disabled', false);
        $('#sold').prop('disabled', false);
        $('#used').prop('disabled', false);
        $('#void').prop('disabled', false);
        $('#comments').prop('disabled', false);
    }
    $('#ticket_modal').modal('show');
    console.log(data);
}

function ticket_data_done(data)
{
    var ticket = null;
    if(data.selected === undefined)
    {
        alert('Unable to retrieve ticket history data');
        console.log(data);
        return;
    }
    ticket_data = data;
    show_ticket_from_data(data);
}

function view_ticket(hash)
{
    $.ajax({
        url: '../api/v1/tickets/'+hash+'?with_history=1',
        type: 'get',
        dataType: 'json',
        success: ticket_data_done});
}

function prev_ticket()
{
    ticket_data.selected++;
    show_ticket_from_data(ticket_data);
}

function next_ticket()
{
    ticket_data.selected--;
    show_ticket_from_data(ticket_data);
}

function set_if_value_different(ticket, obj, inputname, fieldname)
{
    if(fieldname === undefined)
    {
        fieldname = inputname;
    }
    var input = $('#'+inputname);
    if(input.attr('type') === 'checkbox')
    {
         if(input.is(':checked'))
         {
             if(ticket[fieldname] == 0)
             {
                 obj[fieldname] = 1;
             }
         }
         else if(ticket[fieldname] == 1)
         {
             obj[fieldname] = 0;
         }
    }
    else
    {
        var val = $('#'+inputname).val();
        if(val != ticket[fieldname])
        {
            obj[fieldname] = val;
        }
    }
}

function save_ticket_done(jqXHR)
{
    if(jqXHR.status != 200)
    {
        alert("Unable to save ticket!");
    }
    else
    {
        console.log(jqXHR);
    }
}

function save_ticket()
{
    var ticket = get_ticket_by_selected();
    var obj = {};
    set_if_value_different(ticket, obj, 'email');
    set_if_value_different(ticket, obj, 'firstName');
    set_if_value_different(ticket, obj, 'lastName');
    set_if_value_different(ticket, obj, 'request_id');
    set_if_value_different(ticket, obj, 'type');
    set_if_value_different(ticket, obj, 'guardian_first');
    set_if_value_different(ticket, obj, 'guardian_last');
    set_if_value_different(ticket, obj, 'sold');
    set_if_value_different(ticket, obj, 'used');
    set_if_value_different(ticket, obj, 'void');
    if(Object.keys(obj).length > 0)
    {
        $.ajax({
            url: '/tickets/api/v1/ticket/'+ticket.hash,
            contentType: 'application/json',
            data: JSON.stringify(obj),
            type: 'patch',
            dataType: 'json',
            complete: save_ticket_done});
    }
    else
    {
        $('#ticket_modal').modal('hide');
    }
}

function backend_search_done(data)
{
    var tickets = data;
    var history = false;
    if(data.old_tickets !== undefined)
    {
        tickets = data.old_tickets;
        history = true;
    }
    $.ajax({
        url: '/tickets/ajax/tickets.php',
        data: 'hash='+tickets[0].hash+'&with_history=1',
        type: 'get',
        dataType: 'json',
        success: ticket_data_done});
}

function table_searched()
{
    var dt_api = $('#tickets').DataTable();
    if(dt_api.rows({'search':'applied'})[0].length == 0)
    {
        $.ajax({
            url: '../api/v1/tickets/search/'+dt_api.search(),
            type: 'get',
            dataType: 'json',
            success: backend_search_done
        });
    }
}

function yearChanged(e)
{
    $('#tickets').DataTable().ajax.url('../api/v1/tickets?filter=year eq '+e.currentTarget.value+'&fmt=data-table').load();
}

function gotTicketYears(jqXHR)
{
    if(jqXHR.status !== 200)
    {
        alert('Unable to obtain valid ticket years!');
        console.log(jqXHR);
        return;
    }
    jqXHR.responseJSON.sort().reverse();
    for(var i = 0; i < jqXHR.responseJSON.length; i++)
    {
        $('#ticket_year').append($('<option/>').attr('value', jqXHR.responseJSON[i]).text(jqXHR.responseJSON[i]));
    }
    $('#ticket_year').on('change', yearChanged);
    var e = {};
    e.currentTarget = {};
    e.currentTarget.value = $('#ticket_year').val();
    yearChanged(e);
}

function init_page()
{
    $('#tickets').dataTable({
        columns: [
            {'data': 'hash', 'render':short_hash},
            {'data': 'firstName'},
            {'data': 'lastName'},
            {'data': 'email'},
            {'data': 'type'}
        ]
    });
    $.ajax({
        url: '../api/v1/globals/years',
        type: 'get',
        dataType: 'json',
        complete: gotTicketYears});

    $('#tickets').on('search.dt', table_searched);
}

$(init_page)
<commit_msg>Remove deprecated API call from tickets admin page<commit_after>var ticket_data = null;

function short_hash(data, type, row, meta)
{
    var short_hash = data.substring(0,7);
    return ''+short_hash+'';
}

function get_ticket_by_selected()
{
    if(ticket_data.selected == -1)
    {
        return ticket_data.current;
    }
    return ticket_data.history[ticket_data.selected];
}

function show_ticket_from_data(data)
{
    var read_only = true;
    if(data.selected == -1)
    {
        ticket = data.current;
        $('#right_arrow').hide();
        if(data.history !== undefined && data.history.length > 0)
        {
            $('#left_arrow').show();
        }
        else
        {
            $('#left_arrow').hide();
        }
        read_only = false;
        $('#saveticket').removeAttr('disabled');
    }
    else
    {
        ticket = data.history[data.selected];
        if(data.selected == (data.history.length - 1))
        {
            $('#left_arrow').hide();
        }
        else
        {
            $('#left_arrow').show();
        }
        $('#right_arrow').show();
        $('#saveticket').attr('disabled', 'true');
    }
    $('#hash').val(ticket.hash);
    $('#year').val(ticket.year);
    $('#firstName').val(ticket.firstName);
    $('#lastName').val(ticket.lastName);
    $('#email').val(ticket.email);
    $('#request_id').val(ticket.request_id);
    $('#type').val(ticket.type);
    $('#guardian_first').val(ticket.guardian_first);
    $('#guardian_last').val(ticket.guardian_last);
    if(ticket.sold == 1)
    {
        $('#sold').prop('checked', true);
    }
    else
    {
        $('#sold').prop('checked', false);
    }
    if(ticket.used == 1)
    {
        $('#used').prop('checked', true);
    }
    else
    {
        $('#used').prop('checked', false);
    }
    if(ticket.void == 1)
    {
        $('#void').prop('checked', true);
    }
    else
    {
        $('#void').prop('checked', false);
    }
    $('#comments').val(ticket.comments);
    if(read_only)
    {
        $('#firstName').prop('disabled', true);
        $('#lastName').prop('disabled', true);
        $('#email').prop('disabled', true);
        $('#request_id').prop('disabled', true);
        $('#type').prop('disabled', true);
        $('#guardian_first').prop('disabled', true);
        $('#guardian_last').prop('disabled', true);
        $('#sold').prop('disabled', true);
        $('#used').prop('disabled', true);
        $('#void').prop('disabled', true);
        $('#comments').prop('disabled', true);
    }
    else
    {
        $('#firstName').prop('disabled', false);
        $('#lastName').prop('disabled', false);
        $('#email').prop('disabled', false);
        $('#request_id').prop('disabled', false);
        $('#type').prop('disabled', false);
        $('#guardian_first').prop('disabled', false);
        $('#guardian_last').prop('disabled', false);
        $('#sold').prop('disabled', false);
        $('#used').prop('disabled', false);
        $('#void').prop('disabled', false);
        $('#comments').prop('disabled', false);
    }
    $('#ticket_modal').modal('show');
    console.log(data);
}

function ticket_data_done(data)
{
    var ticket = null;
    if(data.selected === undefined)
    {
        alert('Unable to retrieve ticket history data');
        console.log(data);
        return;
    }
    ticket_data = data;
    show_ticket_from_data(data);
}

function view_ticket(hash)
{
    $.ajax({
        url: '../api/v1/tickets/'+hash+'?with_history=1',
        type: 'get',
        dataType: 'json',
        success: ticket_data_done});
}

function prev_ticket()
{
    ticket_data.selected++;
    show_ticket_from_data(ticket_data);
}

function next_ticket()
{
    ticket_data.selected--;
    show_ticket_from_data(ticket_data);
}

function set_if_value_different(ticket, obj, inputname, fieldname)
{
    if(fieldname === undefined)
    {
        fieldname = inputname;
    }
    var input = $('#'+inputname);
    if(input.attr('type') === 'checkbox')
    {
         if(input.is(':checked'))
         {
             if(ticket[fieldname] == 0)
             {
                 obj[fieldname] = 1;
             }
         }
         else if(ticket[fieldname] == 1)
         {
             obj[fieldname] = 0;
         }
    }
    else
    {
        var val = $('#'+inputname).val();
        if(val != ticket[fieldname])
        {
            obj[fieldname] = val;
        }
    }
}

function save_ticket_done(jqXHR)
{
    if(jqXHR.status != 200)
    {
        alert("Unable to save ticket!");
    }
    else
    {
        console.log(jqXHR);
    }
}

function save_ticket()
{
    var ticket = get_ticket_by_selected();
    var obj = {};
    set_if_value_different(ticket, obj, 'email');
    set_if_value_different(ticket, obj, 'firstName');
    set_if_value_different(ticket, obj, 'lastName');
    set_if_value_different(ticket, obj, 'request_id');
    set_if_value_different(ticket, obj, 'type');
    set_if_value_different(ticket, obj, 'guardian_first');
    set_if_value_different(ticket, obj, 'guardian_last');
    set_if_value_different(ticket, obj, 'sold');
    set_if_value_different(ticket, obj, 'used');
    set_if_value_different(ticket, obj, 'void');
    if(Object.keys(obj).length > 0)
    {
        $.ajax({
            url: '../api/v1/tickets/'+ticket.hash,
            contentType: 'application/json',
            data: JSON.stringify(obj),
            type: 'patch',
            dataType: 'json',
            complete: save_ticket_done});
    }
    else
    {
        $('#ticket_modal').modal('hide');
    }
}

function backend_search_done(data)
{
    var tickets = data;
    var history = false;
    if(data.old_tickets !== undefined)
    {
        tickets = data.old_tickets;
        history = true;
    }
    view_ticket(tickets[0].hash);
}

function table_searched()
{
    var dt_api = $('#tickets').DataTable();
    if(dt_api.rows({'search':'applied'})[0].length == 0)
    {
        $.ajax({
            url: '../api/v1/tickets/search/'+dt_api.search(),
            type: 'get',
            dataType: 'json',
            success: backend_search_done
        });
    }
}

function yearChanged(e)
{
    $('#tickets').DataTable().ajax.url('../api/v1/tickets?filter=year eq '+e.currentTarget.value+'&fmt=data-table').load();
}

function gotTicketYears(jqXHR)
{
    if(jqXHR.status !== 200)
    {
        alert('Unable to obtain valid ticket years!');
        console.log(jqXHR);
        return;
    }
    jqXHR.responseJSON.sort().reverse();
    for(var i = 0; i < jqXHR.responseJSON.length; i++)
    {
        $('#ticket_year').append($('<option/>').attr('value', jqXHR.responseJSON[i]).text(jqXHR.responseJSON[i]));
    }
    $('#ticket_year').on('change', yearChanged);
    var e = {};
    e.currentTarget = {};
    e.currentTarget.value = $('#ticket_year').val();
    yearChanged(e);
}

function init_page()
{
    $('#tickets').dataTable({
        columns: [
            {'data': 'hash', 'render':short_hash},
            {'data': 'firstName'},
            {'data': 'lastName'},
            {'data': 'email'},
            {'data': 'type'}
        ]
    });
    $.ajax({
        url: '../api/v1/globals/years',
        type: 'get',
        dataType: 'json',
        complete: gotTicketYears});

    $('#tickets').on('search.dt', table_searched);
}

$(init_page)
<|endoftext|>


<commit_before>import {map} from 'rxjs/operators'
import {of} from 'rxjs'
import {sepalMap} from './map'
import _ from 'lodash'
import ee from 'earthengine-api'
import guid from 'guid'

export default class EarthEngineLayer {
    constructor({layerIndex, bounds, mapId$, props, onProgress}) {
        this.layerIndex = layerIndex
        this.bounds = bounds
        this.mapId$ = mapId$
        this.props = props
        this.onProgress = onProgress
    }

    equals(o) {
        return _.isEqual(o && o.props, this.props)
    }

    addToMap(googleMap) {
        const layer = new ee.layers.ImageOverlay(
            new ee.layers.EarthEngineTileSource(
                toMapId(this.mapId, this.token)
            )
        )

        // [HACK] When fitting bounds with no change to bounds, after Google Maps v3.33,
        // tiles were loaded then removed. GEE used same id for tiles at the same position.
        // This caused freshly loaded tiles to be immediately removed.
        // This workaround uses unique tile ids. Hopefully this doesn't lead to any memory leaks.
        layer.getUniqueTileId_ = () => guid()

        googleMap.overlayMapTypes.setAt(this.layerIndex, layer)

        const notifyOnProgress = () => {
            // Manually calculate stats, since GEE returns stats from multiple zoom-levels
            const tileStatuses = layer.tilesById.getValues()
                .filter(tile => tile.zoom === googleMap.getZoom())
                .map(tile => tile.getStatus())
            const Status = ee.layers.AbstractTile.Status

            const loading = tileStatuses.filter(status => status === Status.LOADING).length
                + tileStatuses.filter(status => status === Status.NEW).length
                + tileStatuses.filter(status => status === Status.THROTTLED).length
            const loaded = tileStatuses.filter(status => status === Status.LOADED).length
            const failed = tileStatuses.filter(status => status === Status.FAILED).length
                + tileStatuses.filter(status => status === Status.ABORTED).length

            const tileStats = {
                count: loading + loaded + failed,
                loading,
                failed,
                loaded
            }
            tileStats.complete = tileStats.count === tileStats.loaded + tileStats.failed

            if (this.onProgress && tileStats.count > 0)
                this.onProgress(tileStats)
            else
                setTimeout(notifyOnProgress, 100)
        }
        this.boundsChangedListener = sepalMap.onBoundsChanged(notifyOnProgress)
        notifyOnProgress()
        layer.addEventListener('tile-load', notifyOnProgress)
        layer.addEventListener('tile-fail', notifyOnProgress)
    }

    removeFromMap(googleMap) {
        sepalMap.removeListener(this.boundsChangedListener)
        // [HACK] Prevent flashing of removed layers, which happens when just setting layer to null
        googleMap.overlayMapTypes.insertAt(this.layerIndex, null)
        googleMap.overlayMapTypes.removeAt(this.layerIndex + 1)
    }

    hide(googleMap, hidden) {
        const layer = googleMap.overlayMapTypes.getAt(this.layerIndex)
        layer && layer.setOpacity(hidden ? 0 : 1)
    }

    initialize$() {
        if (this.token)
            return of(this)
        return this.mapId$.pipe(
            map(({response: {token, mapId}}) => {
                this.token = token
                this.mapId = mapId
                return this
            })
        )
    }
}

const toMapId = (mapid, token) => {
    const path = `https://earthengine.googleapis.com/map/${mapid}`
    const suffix = `?token=${token}`
    // Builds a URL of the form {tileBaseUrl}{path}/{z}/{x}/{y}{suffix}
    const formatTileUrl = (x, y, z) => {
        const width = Math.pow(2, z)
        x = x % width
        if (x < 0) {
            x += width
        }
        const tileUrl = [path, z, x, y].join('/') + suffix
        return tileUrl
    }
    return {mapid, token, formatTileUrl}
}
<commit_msg>Cleanup.<commit_after>import {map} from 'rxjs/operators'
import {of} from 'rxjs'
import {sepalMap} from './map'
import _ from 'lodash'
import ee from 'earthengine-api'
import guid from 'guid'

export default class EarthEngineLayer {
    constructor({layerIndex, bounds, mapId$, props, onProgress}) {
        this.layerIndex = layerIndex
        this.bounds = bounds
        this.mapId$ = mapId$
        this.props = props
        this.onProgress = onProgress
    }

    equals(o) {
        return _.isEqual(o && o.props, this.props)
    }

    addToMap(googleMap) {
        const layer = new ee.layers.ImageOverlay(
            new ee.layers.EarthEngineTileSource(
                toMapId(this.mapId, this.token)
            )
        )

        // [HACK] When fitting bounds with no change to bounds, after Google Maps v3.33,
        // tiles were loaded then removed. GEE used same id for tiles at the same position.
        // This caused freshly loaded tiles to be immediately removed.
        // This workaround uses unique tile ids. Hopefully this doesn't lead to any memory leaks.
        layer.getUniqueTileId_ = () => guid()

        googleMap.overlayMapTypes.setAt(this.layerIndex, layer)

        const notifyOnProgress = () => {
            // Manually calculate stats, since GEE returns stats from multiple zoom-levels
            const tileStatuses = layer.tilesById.getValues()
                .filter(tile => tile.zoom === googleMap.getZoom())
                .map(tile => tile.getStatus())
            const Status = ee.layers.AbstractTile.Status

            const loading = tileStatuses.filter(status => status === Status.LOADING).length
                + tileStatuses.filter(status => status === Status.NEW).length
                + tileStatuses.filter(status => status === Status.THROTTLED).length
            const loaded = tileStatuses.filter(status => status === Status.LOADED).length
            const failed = tileStatuses.filter(status => status === Status.FAILED).length
                + tileStatuses.filter(status => status === Status.ABORTED).length

            const tileStats = {
                count: loading + loaded + failed,
                loading,
                failed,
                loaded
            }
            tileStats.complete = tileStats.count === tileStats.loaded + tileStats.failed

            if (this.onProgress && tileStats.count > 0)
                this.onProgress(tileStats)
            else
                setTimeout(notifyOnProgress, 100)
        }
        this.boundsChangedListener = sepalMap.onBoundsChanged(notifyOnProgress)
        notifyOnProgress()
        layer.addEventListener('tile-load', notifyOnProgress)
        layer.addEventListener('tile-fail', notifyOnProgress)
    }

    removeFromMap(googleMap) {
        sepalMap.removeListener(this.boundsChangedListener)
        // [HACK] Prevent flashing of removed layers, which happens when just setting layer to null
        googleMap.overlayMapTypes.insertAt(this.layerIndex, null)
        googleMap.overlayMapTypes.removeAt(this.layerIndex + 1)
    }

    hide(googleMap, hidden) {
        const layer = googleMap.overlayMapTypes.getAt(this.layerIndex)
        layer && layer.setOpacity(hidden ? 0 : 1)
    }

    initialize$() {
        if (this.token)
            return of(this)
        return this.mapId$.pipe(
            map(({response: {token, mapId}}) => {
                this.token = token
                this.mapId = mapId
                return this
            })
        )
    }
}

// Creates a ee.data.RawMapId.
// https://github.com/google/earthengine-api/blob/1a3121aa7574ecf2d5432c047621081aed8e1b28/javascript/src/data.js#L2198
const toMapId = (mapid, token) => {
    const path = `https://earthengine.googleapis.com/map/${mapid}`
    const suffix = `?token=${token}`
    // Builds a URL of the form {tileBaseUrl}{path}/{z}/{x}/{y}{suffix}
    const formatTileUrl = (x, y, z) => {
        const width = Math.pow(2, z)
        x = x % width
        if (x < 0) {
            x += width
        }
        return [path, z, x, y].join('/') + suffix
    }
    return {mapid, token, formatTileUrl}
}
<|endoftext|>


<commit_before>'use babel';

import manager from './atom-ternjs-manager';
import packageConfig from './atom-ternjs-package-config';
import {
  setMarkerCheckpoint,
  openFileAndGoTo
} from './atom-ternjs-helper';

export default class Client {

  constructor(projectDir) {

    this.projectDir = projectDir;
  }

  completions(file, end) {

    return this.post('query', {

      query: {

        type: 'completions',
        file: file,
        end: end,
        types: true,
        includeKeywords: true,
        sort: packageConfig.options.sort,
        guess: packageConfig.options.guess,
        docs: packageConfig.options.documentation,
        urls: packageConfig.options.urls,
        origins: packageConfig.options.origins,
        lineCharPositions: true,
        caseInsensitive: packageConfig.options.caseInsensitive
      }
    });
  }

  documentation(file, end) {

    return this.post('query', {

      query: {

        type: 'documentation',
        file: file,
        end: end
      }
    });
  }

  refs(file, end) {

    return this.post('query', {

      query: {

        type: 'refs',
        file: file,
        end: end
      }
    });
  }

  updateFull(editor, editorMeta) {

    if (editorMeta) {

      editorMeta.diffs = [];
    }

    return this.post('query', { files: [{

      type: 'full',
      name: atom.project.relativizePath(editor.getURI())[1],
      text: editor.getText()
    }]});
  }

  updatePart(editor, editorMeta, start, text) {

    if (editorMeta) {

      editorMeta.diffs = [];
    }

    return this.post('query', [{

      type: 'full',
      name: atom.project.relativizePath(editor.getURI())[1],
      offset: {

        line: start,
        ch: 0
      },
      text: editor.getText()
    }]);
  }

  update(editor) {

    const editorMeta = manager.getEditor(editor);
    const file = atom.project.relativizePath(editor.getURI())[1].replace(/\\/g, '/');

    // check if this file is excluded via dontLoad
    if (
      manager.server &&
      manager.server.dontLoad(file)
    ) {

      return Promise.resolve({});
    }

    // check if the file is registered, else return
    return this.files().then((data) => {

      if (data.files) {

        for (let i = 0; i < data.files.length; i++) {

          data.files[i] = data.files[i].replace(/\\/g, '/');
        }
      }

      const registered = data.files && data.files.indexOf(file) > -1;

      if (
        editorMeta &&
        editorMeta.diffs.length === 0 &&
        registered
      ) {

        return Promise.resolve({});
      }

      if (registered) {

        // const buffer = editor.getBuffer();
        // if buffer.getMaxCharacterIndex() > 5000
        //   start = 0
        //   end = 0
        //   text = ''
        //   for diff in editorMeta.diffs
        //     start = Math.max(0, diff.oldRange.start.row - 50)
        //     end = Math.min(buffer.getLineCount(), diff.oldRange.end.row + 5)
        //     text = buffer.getTextInRange([[start, 0], [end, buffer.lineLengthForRow(end)]])
        //   promise = this.updatePart(editor, editorMeta, start, text)
        // else
        return this.updateFull(editor, editorMeta);

      } else {

        return Promise.resolve({});
      }
    }).catch((err) => {

      console.error(err);
    });
  }

  rename(file, end, newName) {

    return this.post('query', {

      query: {

        type: 'rename',
        file: file,
        end: end,
        newName: newName
      }
    });
  }

  type(editor, position) {

    const file = atom.project.relativizePath(editor.getURI())[1];
    const end = {

      line: position.row,
      ch: position.column
    };

    return this.post('query', {

      query: {

        type: 'type',
        file: file,
        end: end,
        preferFunction: true
      }
    });
  }

  definition() {

    const editor = atom.workspace.getActiveTextEditor();
    const cursor = editor.getLastCursor();
    const position = cursor.getBufferPosition();
    const file = atom.project.relativizePath(editor.getURI())[1];
    const end = {

      line: position.row,
      ch: position.column
    };

    return this.post('query', {

      query: {

        type: 'definition',
        file: file,
        end: end
      }

    }).then((data) => {

      if (data && data.start) {

        setMarkerCheckpoint();
        openFileAndGoTo(data.start, data.file);
      }
    }).catch((err) => {

      console.error(err);
    });
  }

  files() {

    return this.post('query', {

      query: {

        type: 'files'
      }

    }).then((data) => {

      return data;
    });
  }

  post(type, data) {

    const promise = manager.server.request(type, data);

    return promise;
  }
}
<commit_msg>Jump to file in the same project, not the first project every time.<commit_after>'use babel';

import manager from './atom-ternjs-manager';
import packageConfig from './atom-ternjs-package-config';
import {
  setMarkerCheckpoint,
  openFileAndGoTo
} from './atom-ternjs-helper';

export default class Client {

  constructor(projectDir) {

    this.projectDir = projectDir;
  }

  completions(file, end) {

    return this.post('query', {

      query: {

        type: 'completions',
        file: file,
        end: end,
        types: true,
        includeKeywords: true,
        sort: packageConfig.options.sort,
        guess: packageConfig.options.guess,
        docs: packageConfig.options.documentation,
        urls: packageConfig.options.urls,
        origins: packageConfig.options.origins,
        lineCharPositions: true,
        caseInsensitive: packageConfig.options.caseInsensitive
      }
    });
  }

  documentation(file, end) {

    return this.post('query', {

      query: {

        type: 'documentation',
        file: file,
        end: end
      }
    });
  }

  refs(file, end) {

    return this.post('query', {

      query: {

        type: 'refs',
        file: file,
        end: end
      }
    });
  }

  updateFull(editor, editorMeta) {

    if (editorMeta) {

      editorMeta.diffs = [];
    }

    return this.post('query', { files: [{

      type: 'full',
      name: atom.project.relativizePath(editor.getURI())[1],
      text: editor.getText()
    }]});
  }

  updatePart(editor, editorMeta, start, text) {

    if (editorMeta) {

      editorMeta.diffs = [];
    }

    return this.post('query', [{

      type: 'full',
      name: atom.project.relativizePath(editor.getURI())[1],
      offset: {

        line: start,
        ch: 0
      },
      text: editor.getText()
    }]);
  }

  update(editor) {

    const editorMeta = manager.getEditor(editor);
    const file = atom.project.relativizePath(editor.getURI())[1].replace(/\\/g, '/');

    // check if this file is excluded via dontLoad
    if (
      manager.server &&
      manager.server.dontLoad(file)
    ) {

      return Promise.resolve({});
    }

    // check if the file is registered, else return
    return this.files().then((data) => {

      if (data.files) {

        for (let i = 0; i < data.files.length; i++) {

          data.files[i] = data.files[i].replace(/\\/g, '/');
        }
      }

      const registered = data.files && data.files.indexOf(file) > -1;

      if (
        editorMeta &&
        editorMeta.diffs.length === 0 &&
        registered
      ) {

        return Promise.resolve({});
      }

      if (registered) {

        // const buffer = editor.getBuffer();
        // if buffer.getMaxCharacterIndex() > 5000
        //   start = 0
        //   end = 0
        //   text = ''
        //   for diff in editorMeta.diffs
        //     start = Math.max(0, diff.oldRange.start.row - 50)
        //     end = Math.min(buffer.getLineCount(), diff.oldRange.end.row + 5)
        //     text = buffer.getTextInRange([[start, 0], [end, buffer.lineLengthForRow(end)]])
        //   promise = this.updatePart(editor, editorMeta, start, text)
        // else
        return this.updateFull(editor, editorMeta);

      } else {

        return Promise.resolve({});
      }
    }).catch((err) => {

      console.error(err);
    });
  }

  rename(file, end, newName) {

    return this.post('query', {

      query: {

        type: 'rename',
        file: file,
        end: end,
        newName: newName
      }
    });
  }

  type(editor, position) {

    const file = atom.project.relativizePath(editor.getURI())[1];
    const end = {

      line: position.row,
      ch: position.column
    };

    return this.post('query', {

      query: {

        type: 'type',
        file: file,
        end: end,
        preferFunction: true
      }
    });
  }

  definition() {

    const editor = atom.workspace.getActiveTextEditor();
    const cursor = editor.getLastCursor();
    const position = cursor.getBufferPosition();
    const [project, file] = atom.project.relativizePath(editor.getURI());
    const end = {

      line: position.row,
      ch: position.column
    };

    return this.post('query', {

      query: {

        type: 'definition',
        file: file,
        end: end
      }

    }).then((data) => {

      if (data && data.start) {

        setMarkerCheckpoint();
        openFileAndGoTo(data.start, `${project}/${data.file}`);
      }
    }).catch((err) => {

      console.error(err);
    });
  }

  files() {

    return this.post('query', {

      query: {

        type: 'files'
      }

    }).then((data) => {

      return data;
    });
  }

  post(type, data) {

    const promise = manager.server.request(type, data);

    return promise;
  }
}
<|endoftext|>