<commit_before>"use strinct";
define("./addons/translate",["../utils"],function(utils){
var cView;
var apiKey;
var nodesT = new Object();
var template = [
{"c":"settings"
, "children":[
	{"t":"h1", "txt":"譯 Translations"}
	,{"t":"p", "txt":"To use translations, you should obtain an API key from Yandex.Translate"}
	,{"c":"sr-info", "txt":"No key set yet"}
	,{"t":"form", "e":{"submit":["addons-translate","setAPIKey"]}
	,"children":[
		{"c":"big-txt-input", "t":"input" ,"p":{"name":"api-key", "placeholder":"paste your key here"} }
		,{"t":"input", "p":{"type":"submit", "value":"use that key"}}
	]}
]}
,{"c":"control", "cl":["inline-control"]
,"children":[
	,{"c":"spacer","t":"span","txt":"-"}
	,{"c":"translate","t":"a","txt":"Translate","e":{"click":["addons-translate","translatePost"]}}
]}
,{"c":"display", "cl":["like-comm"], "t":"a", "e":{"click":["addons-like-comm","show"]}}
];
var handlers = {
	"translatePost": function(e){
		var host = e.target.getNode(["p","post"]);
		var label = cView.doc.createElement("span");
		label.innerHTML = "Translated";
		host.translated = true;

		e.target.parentNode.replaceChild(label, e.target);
		translate(host.getElementsByClassName("long-text"));
	}
	,"evtNewNode": function (e){
		var arrNodes = e.detail;
		if(!arrNodes)return;
		var qNodes = new Array();
		arrNodes = Array.isArray(arrNodes)?arrNodes:[arrNodes];
		arrNodes.forEach(function(node){
			switch(node.classList[0]){
			case "post":
				node.getElementsByClassName(["controls"])[0]
					.appendChild(nodesT["control"].cloneAll());
				break;
			case "comment":
				var nodePost = node.getNode(["p","post"]);
				if (nodePost.translated === true){
					var nodesHC = node.getElementsByClassName("long-text");
					for(var idx = 0; idx < nodesHC.length; idx++ )
						qNodes.push(nodesHC[idx]);
				}
				break;
			}
		});
		translate(qNodes);
	}
	,"evtUpdNode": function (e){
		var node = e.detail;
		if(!node)return;
		var nodePost = node.getNode(["p","post"]);
		if(nodePost.translated !== true) return;
		var victim;
		if (node.classList[0] == "post")
			victim = nodePost.getNode(["c","post-body"],["c","post-cont"]);
		else victim = node;
		translate(victim.getElementsByClassName("long-text"));
	}
	,"setAPIKey": function (e){
		e.preventDefault();
		e.stopImmediatePropagation();
		var key = utils.getInputsByName(e.target)["api-key"].value;
		var node = e.target.getNode(["p","settings"],["c","sr-info"]);
		node.hidden = false;
		node.className = "sr-info";
		node.innerHTML = "Checking the key";
		utils.xhr({
			"url":"https://translate.yandex.net/api/v1.5/tr.json/detect?hint=en&text=test&key="+key
		}).then(function(){
			node.innerHTML = "The key is OK";
			cView.localStorage.setItem("addons-translate-apikey", key);
		},function(){
			node.innerHTML = "The key seams to be invalide";
			node.className = "msg-error";
		});

	}
}
function makeSettings(){
	var node = nodesT["settings"].cloneAll();
	var key = cView.localStorage.getItem("addons-translate-apikey");
	if(key){
		utils.getInputsByName(node)["api-key"].value = key;
		node.cNodes["sr-info"].hidden = true;
	}
	return node;
}
function translate (nodesHC){
	var cView = this.cView;
	var url = "https://translate.yandex.net/api/v1.5/tr.json/translate?"
		+"lang=en"
		+"&format=html"
		+"&options=1"
		+"&key=" + apiKey;

	var payload = "";
	var nodes = new Array(nodesHC.length);
	var amp = "";
	var msg = '
Powered by Yandex.Translate
';
	for(var idx = 0; idx < nodesHC.length; idx++ ){
		nodes[idx] = nodesHC[idx];
		var node = nodes[idx];
		node.translated = true;
		var test = node.getElementsByClassName("folded")[0];
		if(typeof test !== "undefined" ){
			nodes[idx] = test;
			node = test;
		}
		payload += amp+"text=" + encodeURIComponent(node.innerHTML);
		amp = "&";
	}
	utils.xhr({
		"url":url
		,"data":payload
		,"method":"post"
		,"headers":{"Content-Type": "application/x-www-form-urlencoded"}
	}).then(function(res){
		JSON.parse(res).text.forEach(function(txt,idx){
			nodes[idx].innerHTML += msg + txt;
		});
	});
}
return function(cV){
	cView = cV;
	cView["addons-translate"] = handlers;
	cView.Common.genNodes(template).forEach(function(node){
		nodesT[node.classList[0]] = node;
	});
	return {
		"run": function (){
			var key = cView.localStorage.getItem("addons-translate-apikey");
			if(!key) return utils._Promise.resolve();
			apiKey = key;

			cView.Common.genNodes(template).forEach(function(node){
				nodesT[node.classList[0]] = node;
			});
			var postCtrls = cView.doc.getElementsByClassName("post-controls");
			for (var idx = 0; idx < postCtrls.length; idx++)
				postCtrls[idx].cNodes["controls"].appendChild(nodesT["control"].cloneAll());
			window.addEventListener("newNode", handlers.evtNewNode);
			window.addEventListener("updNode", handlers.evtUpdNode);
			return utils._Promise.resolve();
		}
		,"settings": function(){return makeSettings(cView);}
	}
};
});
<commit_msg>Fix updated node translation<commit_after>"use strinct";
define("./addons/translate",["../utils"],function(utils){
var cView;
var apiKey;
var nodesT = new Object();
var template = [
{"c":"settings"
, "children":[
	{"t":"h1", "txt":"譯 Translations"}
	,{"t":"p", "txt":"To use translations, you should obtain an API key from Yandex.Translate"}
	,{"c":"sr-info", "txt":"No key set yet"}
	,{"t":"form", "e":{"submit":["addons-translate","setAPIKey"]}
	,"children":[
		{"c":"big-txt-input", "t":"input" ,"p":{"name":"api-key", "placeholder":"paste your key here"} }
		,{"t":"input", "p":{"type":"submit", "value":"use that key"}}
	]}
]}
,{"c":"control", "cl":["inline-control"]
,"children":[
	,{"c":"spacer","t":"span","txt":"-"}
	,{"c":"translate","t":"a","txt":"Translate","e":{"click":["addons-translate","translatePost"]}}
]}
,{"c":"display", "cl":["like-comm"], "t":"a", "e":{"click":["addons-like-comm","show"]}}
];
var handlers = {
	"translatePost": function(e){
		var host = e.target.getNode(["p","post"]);
		var label = cView.doc.createElement("span");
		label.innerHTML = "Translated";
		host.translated = true;

		e.target.parentNode.replaceChild(label, e.target);
		translate(host.getElementsByClassName("long-text"));
	}
	,"evtNewNode": function (e){
		var arrNodes = e.detail;
		if(!arrNodes)return;
		var qNodes = new Array();
		arrNodes = Array.isArray(arrNodes)?arrNodes:[arrNodes];
		arrNodes.forEach(function(node){
			switch(node.classList[0]){
			case "post":
				node.getElementsByClassName(["controls"])[0]
					.appendChild(nodesT["control"].cloneAll());
				break;
			case "comment":
				var nodePost = node.getNode(["p","post"]);
				if (nodePost.translated === true){
					var nodesHC = node.getElementsByClassName("long-text");
					for(var idx = 0; idx < nodesHC.length; idx++ )
						qNodes.push(nodesHC[idx]);
				}
				break;
			}
		});
		translate(qNodes);
	}
	,"evtUpdNode": function (e){
		var node = e.detail;
		if(!node)return;
		var nodePost = node.getNode(["p","post"]);
		if(nodePost.translated !== true) return;
		var nodes;
		if(node.classList.contains("long-text"))
			nodes = [node];
		else if(node.classList.contains("post"))
			nodes =  [nodePost.getNode(["c","post-body"],["c","post-cont"])];
		else nodes =  node.getElementsByClassName("long-text");
		translate(nodes);
	}
	,"setAPIKey": function (e){
		e.preventDefault();
		e.stopImmediatePropagation();
		var key = utils.getInputsByName(e.target)["api-key"].value;
		var node = e.target.getNode(["p","settings"],["c","sr-info"]);
		node.hidden = false;
		node.className = "sr-info";
		node.innerHTML = "Checking the key";
		utils.xhr({
			"url":"https://translate.yandex.net/api/v1.5/tr.json/detect?hint=en&text=test&key="+key
		}).then(function(){
			node.innerHTML = "The key is OK";
			cView.localStorage.setItem("addons-translate-apikey", key);
		},function(){
			node.innerHTML = "The key seams to be invalide";
			node.className = "msg-error";
		});

	}
}
function makeSettings(){
	var node = nodesT["settings"].cloneAll();
	var key = cView.localStorage.getItem("addons-translate-apikey");
	if(key){
		utils.getInputsByName(node)["api-key"].value = key;
		node.cNodes["sr-info"].hidden = true;
	}
	return node;
}
function translate (nodesHC){
	var cView = this.cView;
	var url = "https://translate.yandex.net/api/v1.5/tr.json/translate?"
		+"lang=en"
		+"&format=html"
		+"&options=1"
		+"&key=" + apiKey;

	var payload = "";
	var nodes = new Array(nodesHC.length);
	var amp = "";
	var msg = '
Powered by Yandex.Translate
';
	for(var idx = 0; idx < nodesHC.length; idx++ ){
		nodes[idx] = nodesHC[idx];
		var node = nodes[idx];
		node.translated = true;
		var test = node.getElementsByClassName("folded")[0];
		if(typeof test !== "undefined" ){
			nodes[idx] = test;
			node = test;
		}
		payload += amp+"text=" + encodeURIComponent(node.innerHTML);
		amp = "&";
	}
	utils.xhr({
		"url":url
		,"data":payload
		,"method":"post"
		,"headers":{"Content-Type": "application/x-www-form-urlencoded"}
	}).then(function(res){
		JSON.parse(res).text.forEach(function(txt,idx){
			nodes[idx].innerHTML += msg + txt;
		});
	});
}
return function(cV){
	cView = cV;
	cView["addons-translate"] = handlers;
	cView.Common.genNodes(template).forEach(function(node){
		nodesT[node.classList[0]] = node;
	});
	return {
		"run": function (){
			var key = cView.localStorage.getItem("addons-translate-apikey");
			if(!key) return utils._Promise.resolve();
			apiKey = key;

			cView.Common.genNodes(template).forEach(function(node){
				nodesT[node.classList[0]] = node;
			});
			var postCtrls = cView.doc.getElementsByClassName("post-controls");
			for (var idx = 0; idx < postCtrls.length; idx++)
				postCtrls[idx].cNodes["controls"].appendChild(nodesT["control"].cloneAll());
			window.addEventListener("newNode", handlers.evtNewNode);
			window.addEventListener("updNode", handlers.evtUpdNode);
			return utils._Promise.resolve();
		}
		,"settings": function(){return makeSettings(cView);}
	}
};
});
<|endoftext|>


<commit_before>/**
 * Requires newline before line comments
 *
 * Types: `Boolean` or `Object`
 *
 * Values:
 * - `true`: always require a newline before line comments
 * - `Object`:
 *      - `"allExcept"`: `"firstAfterCurly"` Comments may be first line of block without extra padding
 *
 * #### Examples
 * ```js
 * "requirePaddingNewLinesBeforeLineComments": true
 * "requirePaddingNewLinesBeforeLineComments": { "allExcept": "firstAfterCurly" }
 * ```
 *
 * ##### Valid for `true`
 *
 * ```js
 * var a = 2;
 * var b = 3; // comment
 *
 * // comment
 * return a;
 *
 * function() {
 *
 *   // comment
 * }
 * ```
 *
 * ##### Valid for `{ "allExcept": "firstAfterCurly" }`
 *
 * ```js
 * var a = 2;
 *
 * // comment
 * return a;
 *
 * function() {
 *   // comment
 * }
 * ```
 *
 * ##### Invalid
 *
 * ```js
 * var a = 2;
 * //comment
 * return a;
 *
 * function() {
 *   // comment
 * }
 * ```
 */

var assert = require('assert');

module.exports = function() {};

module.exports.prototype = {

    configure: function(value) {
        this._allowFirstAfterCurly = false;

        if (typeof value === 'object') {
            assert(typeof value.allExcept === 'string' && value.allExcept === 'firstAfterCurly',
                this.getOptionName() + ' option requires the "allExcept" ' +
                 'property to equal "firstAfterCurly"');
            this._allowFirstAfterCurly = true;
        } else {
            assert(value === true,
                this.getOptionName() + ' option requires true value or object'
            );
        }
    },

    getOptionName: function() {
        return 'requirePaddingNewLinesBeforeLineComments';
    },

    check: function(file, errors) {
        var allowFirstAfterCurly = this._allowFirstAfterCurly;

        file.iterateTokensByType('Line', function(comment) {
            if (comment.loc.start.line === 1) {
                return;
            }

            var firstToken = file.getFirstTokenOnLine(comment.loc.start.line);

            // Should not consider code and comment on the same line (#1194)
            if (firstToken !== undefined && firstToken.type !== 'EOF') {
                return;
            }

            var prevToken = file.getPrevToken(comment, {includeComments: true});

            if (!prevToken || prevToken.type === 'Line') {
                return;
            }

            if (allowFirstAfterCurly && prevToken.type === 'Punctuator' && prevToken.value === '{') {
                return;
            }

            errors.assert.linesBetween({
                token: prevToken,
                nextToken: comment,
                atLeast: 2,
                message: 'Line comments must be preceded with a blank line'
            });
        });
    }
};
<commit_msg>JS-file: all return values should be consistent<commit_after>/**
 * Requires newline before line comments
 *
 * Types: `Boolean` or `Object`
 *
 * Values:
 * - `true`: always require a newline before line comments
 * - `Object`:
 *      - `"allExcept"`: `"firstAfterCurly"` Comments may be first line of block without extra padding
 *
 * #### Examples
 * ```js
 * "requirePaddingNewLinesBeforeLineComments": true
 * "requirePaddingNewLinesBeforeLineComments": { "allExcept": "firstAfterCurly" }
 * ```
 *
 * ##### Valid for `true`
 *
 * ```js
 * var a = 2;
 * var b = 3; // comment
 *
 * // comment
 * return a;
 *
 * function() {
 *
 *   // comment
 * }
 * ```
 *
 * ##### Valid for `{ "allExcept": "firstAfterCurly" }`
 *
 * ```js
 * var a = 2;
 *
 * // comment
 * return a;
 *
 * function() {
 *   // comment
 * }
 * ```
 *
 * ##### Invalid
 *
 * ```js
 * var a = 2;
 * //comment
 * return a;
 *
 * function() {
 *   // comment
 * }
 * ```
 */

var assert = require('assert');

module.exports = function() {};

module.exports.prototype = {

    configure: function(value) {
        this._allowFirstAfterCurly = false;

        if (typeof value === 'object') {
            assert(typeof value.allExcept === 'string' && value.allExcept === 'firstAfterCurly',
                this.getOptionName() + ' option requires the "allExcept" ' +
                 'property to equal "firstAfterCurly"');
            this._allowFirstAfterCurly = true;
        } else {
            assert(value === true,
                this.getOptionName() + ' option requires true value or object'
            );
        }
    },

    getOptionName: function() {
        return 'requirePaddingNewLinesBeforeLineComments';
    },

    check: function(file, errors) {
        var allowFirstAfterCurly = this._allowFirstAfterCurly;

        file.iterateTokensByType('Line', function(comment) {
            if (comment.loc.start.line === 1) {
                return;
            }

            var firstToken = file.getFirstTokenOnLine(comment.loc.start.line);

            // Should not consider code and comment on the same line (#1194)
            if (firstToken !== null && firstToken.type !== 'EOF') {
                return;
            }

            var prevToken = file.getPrevToken(comment, {includeComments: true});

            if (!prevToken || prevToken.type === 'Line') {
                return;
            }

            if (allowFirstAfterCurly && prevToken.type === 'Punctuator' && prevToken.value === '{') {
                return;
            }

            errors.assert.linesBetween({
                token: prevToken,
                nextToken: comment,
                atLeast: 2,
                message: 'Line comments must be preceded with a blank line'
            });
        });
    }
};
<|endoftext|>


<commit_before>//! This script contains the WaterTankSimulation class.
//!

//! Notes about the Xilinx WaterTank simulation mode.
//!
//! The following FPGA board inputs/outputs are used thus:
//!
//! LEDs are used as inputs for the simulation.
//! LED 0: RightPump on or off.
//! LED 1: LeftPump on or off.
//!
//! Switches are used as sensor inputs and the like. Thus, the FPGA board
//! can infer the "state" of the simulation, and the user's program react
//! accordingly.
//! SWI0, SWI1, SWI2 are level sensors. They indicate the following:
//! 20%, 50%, 80%
//!
//! If the watertank_temperatures mode is enabled, then:
//! SWI3 is the warning for the first pump.
//! SWI4 is the warning for the second pump.

/// The following references are for VisualStudio, so that Intellisense recognizes every library.
/// <reference path="../jslib/weblabjs.js" />
/// <reference path="../jslib/three.min.js" />
/// <reference path="../jslib/stats.min.js" />
/// <reference path="../jslib/THREEx.FullScreen.js" />
/// <reference path="../jslib/jquery-1.9.1.js" />
/// <reference path="../jslib/jquery-ui-1.10.2.custom/js/jquery-ui-1.10.2.custom.js" />

WaterTankSimulation = function () {

    this._init = function () {
        this.world = new WorldLoader();
        this.waterOutputLevel = 0.5;
        this.rightPumpLevel = 0.5;
        this.leftPumpLevel = 0.5;
        this.waterLevel = 0.5;
        this.rightPumpTemperature = 0.0;
        this.leftPumpTemperature = 0.0;

        this._loadingDeferred = $.Deferred();
    }

    this.setLeftPumpTemperature = function (temp) {
        var pump = this.world.getObject("waterpumpLeft");
        if(temp > 0.8)
            pump.material = new THREE.MeshLambertMaterial({ color: 0xFF0000, ambient: 0x00 });
        else if(temp > 0.5)
            pump.material = new THREE.MeshLambertMaterial({ color: 0xFF6600, ambient: 0x00 });
        else if (temp > 0.2)
            pump.material = new THREE.MeshLambertMaterial({ color: 0xFFFF00, ambient: 0x00 });
        else
            pump.material = new THREE.MeshLambertMaterial({ color: 0x0000FF, ambient: 0x00 });
    }

    this.setRightPumpTemperature = function (temp) {
        var pump = this.world.getObject("waterpumpRight");
        if (temp > 0.8)
            pump.material = new THREE.MeshLambertMaterial({ color: 0xFF0000, ambient: 0x00 });
        else if (temp > 0.5)
            pump.material = new THREE.MeshLambertMaterial({ color: 0xFF6600, ambient: 0x00 });
        else if (temp > 0.2)
            pump.material = new THREE.MeshLambertMaterial({ color: 0xFFFF00, ambient: 0x00 });
        else
            pump.material = new THREE.MeshLambertMaterial({ color: 0x0000FF, ambient: 0x00 });
    }

    this.setWaterOutputLevel = function (level) {
        var wo = this.world.getObject("waterfallOut");
        this.waterOutputLevel = level;

        if (this.waterOutputLevel == 0 || this.waterLevel == 0) {
            wo.visible = false;
        } else {
            wo.scale.set(50 + 100 * level, 100, 100);
            wo.visible = true;
        }
    }

    this.setWaterLevel = function (level) {
        var water = this.world.getObject("water");
        this.waterLevel = level;

        if (this.waterLevel == 0) {
            water.visible = false;

            // Invoke this so that it can hide the output waterflow if there
            // isn't actually any water left on the deposit.
            this.setWaterOutputLevel(this.waterOutputLevel);
        } else {
            water.scale.set(.95, level, .95);
            water.visible = true;
        }

    }

    this.setRightPumpLevel = function (level) {
        var wr = this.world.getObject("waterfallRight");
        this.rightPumpLevel = level;

        if (this.rightPumpLevel == 0) {
            wr.visible = false;
        } else {
            wr.scale.set(50 + 100 * level, 100, 100);
            wr.visible = true;
        }
    }

    this.setLeftPumpLevel = function (level) {
        var wl = this.world.getObject("waterfallLeft");
        this.leftPumpLevel = level;

        if (this.leftPumpLevel == 0) {
            wl.visible = false;
        } else {
            wl.scale.set(50 + 100 * level, 100, 100);
            wl.visible = true;
        }
    }

    this.loadScene = function (scene, camera) {

        this.world.setOnLoad(function () {
            water = this.world.getObject("water");
            waterfall = this.world.getObject("waterfallRight");
            waterfall2 = this.world.getObject("waterfallLeft");
            waterfallOut = this.world.getObject("waterfallOut");

            this._animate_water(waterfall);
            this._animate_water(waterfall2);
            this._animate_water(waterfallOut);

            this._loadingDeferred.resolve();

        }.bind(this)); //! OnLoad

        this.world.load("World.js", scene);

        return this._loadingDeferred.promise();
    }

    this._animate_water = function (water) {

        new function (water, range, target_scale, increment) {
            return;
            setInterval(
                function () {

                    var currentX = water.scale.x;

                    if (target_scale == undefined || currentX == target_scale) {
                        var target = Math.random(range) * range;
                        var positive = Math.floor(Math.random(2) * 2) == 1 ? true : false;

                    }

                    wfcurrent += wfinc;

                    if (wfcurrent > wftarget) {
                        wfcurrent = wftarget;
                        wfinc *= -1;

                        wftarget = 100 + Math.random(40) * 20;
                    }

                    if (wfcurrent < 0) {
                        wfcurrent = 0;
                        wfinc *= -1;

                        wftarget = 100 + Math.random(40) * 20;
                    }

                    wfscale = 100 + wfcurrent / 100.0 * wfrange;
                    //console.log("New scale: " + wfscale + " " + wfcurrent + " " + wfinc);

                    water.scale.set(wfscale, 100, 100);

                },
                    100
            );

        }(water, 5, 50, 0, 100);
    } // !_animate_water()

    this._init();

}

//! Pseudo-class to constantly update the state of the simulation, asking
//! Weblab for the state. Should not be used before the simulation has been
//! loaded.
//!
WeblabSimulationUpdater = function ( simulation ) {

    this._init = function () {
        this._active = undefined;
        this._simulation = simulation;
        this._initialized = false
    }

    this.startUpdating = function () {
        this._active = true;
        // Not using an Interval lets us respond more appropriately to network limitations. (Several requests won't queue up when the network is slow).
        setTimeout( this._requestUpdate.bind(this), 1500 );
    }

    this._initialize_watertank = function () {
        Weblab.dbgSetOfflineSendCommandResponse("");

        if (Weblab.isExperimentActive() && Weblab.checkOnline())
            Weblab.sendCommand("VIRTUALWORLD_MODE watertank", function (msg) { this._initialized = true; }.bind(this));
    }

    this._requestUpdate = function () {
        if (!this._initialized)
            this._initialize_watertank()

        // Note: These commands are actually sent asynchronously, so the second one might actually get called before
        // the first one finishes. Shouldn't matter in this instance, however. Though it's not tidy.
        // Maybe we could consider adding Promises support to the Weblab class (though it would add a dependency on
        // jquery.

        Weblab.dbgSetOfflineSendCommandResponse("{\"water\": 0.56, \"inputs\": [0.5, 0.5], \"outputs\": [0.5]}");
        if( Weblab.isExperimentActive() && Weblab.checkOnline() )
            Weblab.sendCommand("VIRTUALWORLD_STATE", this._onStateReceived.bind(this), this._onStateReceivedError.bind(this));
    }

    this.stopUpdating = function () {
        this._active = false;
    }

    this._onStateReceived = function (state_json) {
        state = $.parseJSON(state_json);

        if ($.isEmptyObject(state))
            return;

        this._simulation.setWaterLevel(state["water"]);
        this._simulation.setLeftPumpLevel(state["inputs"][0]);
        this._simulation.setRightPumpLevel(state["inputs"][1]);
        this._simulation.setWaterOutputLevel(state["outputs"][0]);
        this._simulation.setLeftPumpTemperature(state["temperatures"][0]);
        this._simulation.setRightPumpTemperature(state["temperatures"][1]);

        if( this._active )
            this.startUpdating(); // Does actually *continue* updating.
    }

    this._onStateReceivedError = function (state_json) {
        state = $.parseJSON(state_json);

        if( this._active )
            this.startUpdating(); // Does actually *continue* updating.
    }

    this._init();
}

//waterLevel = 0.01;
//waterLevelChange = 0.03;
//setTimeout(
//    function () {
//        setInterval(
//            function () {

//                elapsed = 50;

//                waterLevel += waterLevelChange;
//                if (waterLevel > 1)
//                    waterLevel = 1;
//                else if (waterLevel < 0)
//                    waterLevel = 0;

//                if (waterLevel >= 1 || waterLevel <= 0) {
//                    waterLevelChange *= -1;

//                    if (typeof (waterfall) != "undefined") {
//                        if (waterLevelChange > 0) {
//                            waterfall.scale.set(150, 100, 100);
//                            waterfall2.scale.set(150, 100, 100);
//                        }
//                        else {
//                            waterfall.scale.set(50, 100, 100);
//                            waterfall2.scale.set(50, 100, 100);
//                        }

//                    }
//                }

//                water.scale.set(.95, waterLevel, .95);

//            },
//                50
//            );
//    },
//3000
//);

//wfrange = 5;
//wfinc = 25;
//wfcurrent = 0;
//wftarget = 100;

//setTimeout(
//    function () {
//        setInterval(
//            function () {

//                wfcurrent += wfinc;

//                if (wfcurrent > wftarget) {
//                    wfcurrent = wftarget;
//                    wfinc *= -1;

//                    wftarget = 100 + Math.random(40) * 20;
//                }

//                if (wfcurrent < 0) {
//                    wfcurrent = 0;
//                    wfinc *= -1;

//                    wftarget = 100 + Math.random(40) * 20;
//                }

//                wfscale = 100 + wfcurrent / 100.0 * wfrange;
//                //console.log("New scale: " + wfscale + " " + wfcurrent + " " + wfinc);

//                waterfallOut.scale.set(wfscale, 100, 100);

//            },
//                50
//            );
//    },
//3000
//);
<commit_msg>[js]: Minor potential fix in watertank<commit_after>//! This script contains the WaterTankSimulation class.
//!

//! Notes about the Xilinx WaterTank simulation mode.
//!
//! The following FPGA board inputs/outputs are used thus:
//!
//! LEDs are used as inputs for the simulation.
//! LED 0: RightPump on or off.
//! LED 1: LeftPump on or off.
//!
//! Switches are used as sensor inputs and the like. Thus, the FPGA board
//! can infer the "state" of the simulation, and the user's program react
//! accordingly.
//! SWI0, SWI1, SWI2 are level sensors. They indicate the following:
//! 20%, 50%, 80%
//!
//! If the watertank_temperatures mode is enabled, then:
//! SWI3 is the warning for the first pump.
//! SWI4 is the warning for the second pump.

/// The following references are for VisualStudio, so that Intellisense recognizes every library.
/// <reference path="../jslib/weblabjs.js" />
/// <reference path="../jslib/three.min.js" />
/// <reference path="../jslib/stats.min.js" />
/// <reference path="../jslib/THREEx.FullScreen.js" />
/// <reference path="../jslib/jquery-1.9.1.js" />
/// <reference path="../jslib/jquery-ui-1.10.2.custom/js/jquery-ui-1.10.2.custom.js" />

WaterTankSimulation = function () {

    this._init = function () {
        this.world = new WorldLoader();
        this.waterOutputLevel = 0.5;
        this.rightPumpLevel = 0.5;
        this.leftPumpLevel = 0.5;
        this.waterLevel = 0.5;
        this.rightPumpTemperature = 0.0;
        this.leftPumpTemperature = 0.0;

        this._loadingDeferred = $.Deferred();
    }

    this.setLeftPumpTemperature = function (temp) {
        var pump = this.world.getObject("waterpumpLeft");
        if(temp > 0.8)
            pump.material = new THREE.MeshLambertMaterial({ color: 0xFF0000, ambient: 0x00 });
        else if(temp > 0.5)
            pump.material = new THREE.MeshLambertMaterial({ color: 0xFF6600, ambient: 0x00 });
        else if (temp > 0.2)
            pump.material = new THREE.MeshLambertMaterial({ color: 0xFFFF00, ambient: 0x00 });
        else
            pump.material = new THREE.MeshLambertMaterial({ color: 0x0000FF, ambient: 0x00 });
    }

    this.setRightPumpTemperature = function (temp) {
        var pump = this.world.getObject("waterpumpRight");
        if (temp > 0.8)
            pump.material = new THREE.MeshLambertMaterial({ color: 0xFF0000, ambient: 0x00 });
        else if (temp > 0.5)
            pump.material = new THREE.MeshLambertMaterial({ color: 0xFF6600, ambient: 0x00 });
        else if (temp > 0.2)
            pump.material = new THREE.MeshLambertMaterial({ color: 0xFFFF00, ambient: 0x00 });
        else
            pump.material = new THREE.MeshLambertMaterial({ color: 0x0000FF, ambient: 0x00 });
    }

    this.setWaterOutputLevel = function (level) {
        var wo = this.world.getObject("waterfallOut");
        this.waterOutputLevel = level;

        if (this.waterOutputLevel == 0 || this.waterLevel == 0) {
            wo.visible = false;
        } else {
            wo.scale.set(50 + 100 * level, 100, 100);
            wo.visible = true;
        }
    }

    this.setWaterLevel = function (level) {
        var water = this.world.getObject("water");
        this.waterLevel = level;

        if (this.waterLevel == 0) {
            water.visible = false;

            // Invoke this so that it can hide the output waterflow if there
            // isn't actually any water left on the deposit.
            this.setWaterOutputLevel(this.waterOutputLevel);
        } else {
            water.scale.set(.95, level, .95);
            water.visible = true;
        }

    }

    this.setRightPumpLevel = function (level) {
        var wr = this.world.getObject("waterfallRight");
        this.rightPumpLevel = level;

        if (this.rightPumpLevel == 0) {
            wr.visible = false;
        } else {
            wr.scale.set(50 + 100 * level, 100, 100);
            wr.visible = true;
        }
    }

    this.setLeftPumpLevel = function (level) {
        var wl = this.world.getObject("waterfallLeft");
        this.leftPumpLevel = level;

        if (this.leftPumpLevel == 0) {
            wl.visible = false;
        } else {
            wl.scale.set(50 + 100 * level, 100, 100);
            wl.visible = true;
        }
    }

    this.loadScene = function (scene, camera) {

        this.world.setOnLoad(function () {
            water = this.world.getObject("water");
            waterfall = this.world.getObject("waterfallRight");
            waterfall2 = this.world.getObject("waterfallLeft");
            waterfallOut = this.world.getObject("waterfallOut");

            this._animate_water(waterfall);
            this._animate_water(waterfall2);
            this._animate_water(waterfallOut);

            this._loadingDeferred.resolve();

        }.bind(this)); //! OnLoad

        this.world.load("World.js", scene);

        return this._loadingDeferred.promise();
    }

    this._animate_water = function (water) {

        new function (water, range, target_scale, increment) {
            return;
            setInterval(
                function () {

                    var currentX = water.scale.x;

                    if (target_scale == undefined || currentX == target_scale) {
                        var target = Math.random(range) * range;
                        var positive = Math.floor(Math.random(2) * 2) == 1 ? true : false;

                    }

                    wfcurrent += wfinc;

                    if (wfcurrent > wftarget) {
                        wfcurrent = wftarget;
                        wfinc *= -1;

                        wftarget = 100 + Math.random(40) * 20;
                    }

                    if (wfcurrent < 0) {
                        wfcurrent = 0;
                        wfinc *= -1;

                        wftarget = 100 + Math.random(40) * 20;
                    }

                    wfscale = 100 + wfcurrent / 100.0 * wfrange;
                    //console.log("New scale: " + wfscale + " " + wfcurrent + " " + wfinc);

                    water.scale.set(wfscale, 100, 100);

                },
                    100
            );

        }(water, 5, 50, 0, 100);
    } // !_animate_water()

    this._init();

}

//! Pseudo-class to constantly update the state of the simulation, asking
//! Weblab for the state. Should not be used before the simulation has been
//! loaded.
//!
WeblabSimulationUpdater = function ( simulation ) {

    this._init = function () {
        this._active = undefined;
        this._simulation = simulation;
        this._initialized = false
    }

    this.startUpdating = function () {
        this._active = true;
        // Not using an Interval lets us respond more appropriately to network limitations. (Several requests won't queue up when the network is slow).
        setTimeout( this._requestUpdate.bind(this), 1500 );
    }

    this._initialize_watertank = function () {
        Weblab.dbgSetOfflineSendCommandResponse("");

        if (Weblab.isExperimentActive() && Weblab.checkOnline())
            Weblab.sendCommand("VIRTUALWORLD_MODE watertank", function (msg) { this._initialized = true; }.bind(this));
    }

    this._requestUpdate = function () {
        if (!this._initialized)
            this._initialize_watertank()

        // Note: These commands are actually sent asynchronously, so the second one might actually get called before
        // the first one finishes. Shouldn't matter in this instance, however. Though it's not tidy.
        // Maybe we could consider adding Promises support to the Weblab class (though it would add a dependency on
        // jquery.

        Weblab.dbgSetOfflineSendCommandResponse("{\"water\": 0.56, \"inputs\": [0.5, 0.5], \"outputs\": [0.5]}");
        if( Weblab.isExperimentActive() && Weblab.checkOnline() )
            Weblab.sendCommand("VIRTUALWORLD_STATE", this._onStateReceived.bind(this), this._onStateReceivedError.bind(this));
    }

    this.stopUpdating = function () {
        this._active = false;
    }

    this._onStateReceived = function (state_json) {
        state = $.parseJSON(state_json);

        if ($.isEmptyObject(state))
            return;

        this._simulation.setWaterLevel(state["water"]);
        this._simulation.setLeftPumpLevel(state["inputs"][0]);
        this._simulation.setRightPumpLevel(state["inputs"][1]);
        this._simulation.setWaterOutputLevel(state["outputs"][0]);

        if("temperatures" in state) {
            this._simulation.setLeftPumpTemperature(state["temperatures"][0]);
            this._simulation.setRightPumpTemperature(state["temperatures"][1]);
        }

        if( this._active )
            this.startUpdating(); // Does actually *continue* updating.
    }

    this._onStateReceivedError = function (state_json) {
        state = $.parseJSON(state_json);

        if( this._active )
            this.startUpdating(); // Does actually *continue* updating.
    }

    this._init();
}

//waterLevel = 0.01;
//waterLevelChange = 0.03;
//setTimeout(
//    function () {
//        setInterval(
//            function () {

//                elapsed = 50;

//                waterLevel += waterLevelChange;
//                if (waterLevel > 1)
//                    waterLevel = 1;
//                else if (waterLevel < 0)
//                    waterLevel = 0;

//                if (waterLevel >= 1 || waterLevel <= 0) {
//                    waterLevelChange *= -1;

//                    if (typeof (waterfall) != "undefined") {
//                        if (waterLevelChange > 0) {
//                            waterfall.scale.set(150, 100, 100);
//                            waterfall2.scale.set(150, 100, 100);
//                        }
//                        else {
//                            waterfall.scale.set(50, 100, 100);
//                            waterfall2.scale.set(50, 100, 100);
//                        }

//                    }
//                }

//                water.scale.set(.95, waterLevel, .95);

//            },
//                50
//            );
//    },
//3000
//);

//wfrange = 5;
//wfinc = 25;
//wfcurrent = 0;
//wftarget = 100;

//setTimeout(
//    function () {
//        setInterval(
//            function () {

//                wfcurrent += wfinc;

//                if (wfcurrent > wftarget) {
//                    wfcurrent = wftarget;
//                    wfinc *= -1;

//                    wftarget = 100 + Math.random(40) * 20;
//                }

//                if (wfcurrent < 0) {
//                    wfcurrent = 0;
//                    wfinc *= -1;

//                    wftarget = 100 + Math.random(40) * 20;
//                }

//                wfscale = 100 + wfcurrent / 100.0 * wfrange;
//                //console.log("New scale: " + wfscale + " " + wfcurrent + " " + wfinc);

//                waterfallOut.scale.set(wfscale, 100, 100);

//            },
//                50
//            );
//    },
//3000
//);
<|endoftext|>


<commit_before>List.prototype.templateEngines.jquerytemplates = function(settings) {
    this.reload = function(item) {
        item.elm = $('#'+this.template).tmpl(item.getValues());
    };
    this.add = function(item, options) {
       if (effect) {
            item.elm.hide();
            self.list.append(item.elm);
            item.elm[effect]();
        } else {
            self.list.appendChild(item.elm);
        }
    };
    this.remove = function(item, options) {
        $(this.elm)[effect]($(this.elm).remove);
    };
    this.show = function(item, options) {
        item.elm.style.display = "block";
    };
    this.hide = function(item, options) {
        item.elm.style.display = "none";
    };
};<commit_msg>Added unfinished notice<commit_after>/* not finished */
List.prototype.templateEngines.jquerytemplates = function(settings) {
    this.reload = function(item) {
        item.elm = $('#'+this.template).tmpl(item.getValues());
    };
    this.add = function(item, options) {
       if (effect) {
            item.elm.hide();
            self.list.append(item.elm);
            item.elm[effect]();
        } else {
            self.list.appendChild(item.elm);
        }
    };
    this.remove = function(item, options) {
        $(this.elm)[effect]($(this.elm).remove);
    };
    this.show = function(item, options) {
        item.elm.style.display = "block";
    };
    this.hide = function(item, options) {
        item.elm.style.display = "none";
    };
};<|endoftext|>


<commit_before>const path = require('path')
const minimumNodeVersion = require('minimum-node-version').default
const nodeExternals = require('webpack-node-externals')
const pkg = require('./package.json')

const configsPromise = minimumNodeVersion().then(nodeVersion => {
  const commonConfig = {
    context: path.resolve(__dirname, 'src'),
    devtool: 'source-map',
    stats: 'minimal'
  }

  const nodeConfig = Object.assign({}, commonConfig, {
    entry: ['./index.js'],
    output: {
      path: path.resolve(__dirname, 'bin'),
      filename: 'node.bundle.js',
      libraryTarget: 'commonjs2',
      library: ['botpress', pkg.name]
    },
    resolve: {
      extensions: ['.js'],
      modules: [path.resolve(__dirname, 'node_modules'), 'node_modules']
    },
    externals: [nodeExternals(), 'botpress'],
    target: 'node',
    node: {
      __filename: false,
      __dirname: false
    },
    module: {
      rules: [
        {
          test: /\.js$/,
          exclude: /node_modules/,
          use: {
            loader: 'babel-loader',
            options: {
              sourceMaps: true,
              presets: [
                [
                  'env',
                  {
                    targets: {
                      node: nodeVersion
                    }
                  }
                ]
              ],
              plugins: ['transform-object-rest-spread', 'add-module-exports']
            }
          }
        }
      ]
    }
  })

  const webConfig = Object.assign({}, commonConfig, {
    entry: ['./views/index.jsx'],
    output: {
      path: path.resolve(__dirname, 'bin'),
      publicPath: '/js/modules/',
      filename: 'web.bundle.js',
      libraryTarget: 'assign',
      library: ['botpress', pkg.name]
    },
    resolve: {
      extensions: ['.js', '.jsx']
    },
    externals: {
      react: 'React',
      'react-dom': 'ReactDOM'
    },
    module: {
      rules: [
        {
          test: /\.jsx?$/,
          exclude: /node_modules/,
          use: {
            loader: 'babel-loader',
            options: {
              presets: [
                'react',
                [
                  'env',
                  {
                    targets: {
                      browsers: ['last 2 versions', 'ie >= 10']
                    }
                  }
                ]
              ],

              plugins: ['transform-object-rest-spread']
            }
          }
        },
        {
          test: /\.scss$/,
          use: [
            'style-loader',
            {
              loader: 'css-loader',
              options: {
                modules: true,
                importLoaders: 1,
                localIdentName: pkg.name + '__[name]__[local]___[hash:base64:5]'
              }
            },
            'sass-loader'
          ]
        },
        {
          test: /\.css$/,
          use: ['style-loader', 'css-loader']
        },
        {
          test: /\.woff|\.woff2|\.svg|.eot|\.ttf/,
          use: {
            loader: 'file-loader',
            options: {
              name: '../fonts/[name].[ext]'
            }
          }
        }
      ]
    }
  })

  // eslint-disable-next-line no-unused-vars
  const liteConfig = Object.assign({}, webConfig, {
    // Add your lite views here, see example below
    context: path.resolve(__dirname, 'src'),
    entry: {
      // example: './views/example.lite.jsx'
    },
    output: {
      path: path.resolve(__dirname, 'bin/lite'),
      publicPath: '/js/lite-modules/',
      filename: '[name].bundle.js',
      libraryTarget: 'assign',
      library: ['botpress', pkg.name]
    }
  })

  return [nodeConfig, webConfig /*, liteConfig*/]
})

module.exports = configsPromise
<commit_msg>add webpack externals to the bot template<commit_after>const path = require('path')
const minimumNodeVersion = require('minimum-node-version').default
const nodeExternals = require('webpack-node-externals')
const pkg = require('./package.json')

const configsPromise = minimumNodeVersion().then(nodeVersion => {
  const commonConfig = {
    context: path.resolve(__dirname, 'src'),
    devtool: 'source-map',
    stats: 'minimal'
  }

  const nodeConfig = Object.assign({}, commonConfig, {
    entry: ['./index.js'],
    output: {
      path: path.resolve(__dirname, 'bin'),
      filename: 'node.bundle.js',
      libraryTarget: 'commonjs2',
      library: ['botpress', pkg.name]
    },
    resolve: {
      extensions: ['.js'],
      modules: [path.resolve(__dirname, 'node_modules'), 'node_modules']
    },
    externals: [nodeExternals(), 'botpress'],
    target: 'node',
    node: {
      __filename: false,
      __dirname: false
    },
    module: {
      rules: [
        {
          test: /\.js$/,
          exclude: /node_modules/,
          use: {
            loader: 'babel-loader',
            options: {
              sourceMaps: true,
              presets: [
                [
                  'env',
                  {
                    targets: {
                      node: nodeVersion
                    }
                  }
                ]
              ],
              plugins: ['transform-object-rest-spread', 'add-module-exports']
            }
          }
        }
      ]
    }
  })

  const webConfig = Object.assign({}, commonConfig, {
    entry: ['./views/index.jsx'],
    output: {
      path: path.resolve(__dirname, 'bin'),
      publicPath: '/js/modules/',
      filename: 'web.bundle.js',
      libraryTarget: 'assign',
      library: ['botpress', pkg.name]
    },
    resolve: {
      extensions: ['.js', '.jsx']
    },
    externals: {
      react: 'React',
      'react-dom': 'ReactDOM',
      'react-bootstrap': 'ReactBootstrap',
      'prop-types': 'PropTypes'
    },
    module: {
      rules: [
        {
          test: /\.jsx?$/,
          exclude: /node_modules/,
          use: {
            loader: 'babel-loader',
            options: {
              presets: [
                'react',
                [
                  'env',
                  {
                    targets: {
                      browsers: ['last 2 versions', 'ie >= 10']
                    }
                  }
                ]
              ],

              plugins: ['transform-object-rest-spread']
            }
          }
        },
        {
          test: /\.scss$/,
          use: [
            'style-loader',
            {
              loader: 'css-loader',
              options: {
                modules: true,
                importLoaders: 1,
                localIdentName: pkg.name + '__[name]__[local]___[hash:base64:5]'
              }
            },
            'sass-loader'
          ]
        },
        {
          test: /\.css$/,
          use: ['style-loader', 'css-loader']
        },
        {
          test: /\.woff|\.woff2|\.svg|.eot|\.ttf/,
          use: {
            loader: 'file-loader',
            options: {
              name: '../fonts/[name].[ext]'
            }
          }
        }
      ]
    }
  })

  // eslint-disable-next-line no-unused-vars
  const liteConfig = Object.assign({}, webConfig, {
    // Add your lite views here, see example below
    context: path.resolve(__dirname, 'src'),
    entry: {
      // example: './views/example.lite.jsx'
    },
    output: {
      path: path.resolve(__dirname, 'bin/lite'),
      publicPath: '/js/lite-modules/',
      filename: '[name].bundle.js',
      libraryTarget: 'assign',
      library: ['botpress', pkg.name]
    }
  })

  return [nodeConfig, webConfig /*, liteConfig*/]
})

module.exports = configsPromise
<|endoftext|>


<commit_before>module.exports = [
  {database:'BioGrid', url:'http://identifiers.org/biogrid/', search:''},
  {database:'DrugBank', url:'https://www.drugbank.ca/', search:''},
  {database:'mirtarBase', url:'http://identifiers.org/mirtarbase/', search:''},
  {database:'NetPath', url:'http://www.netpath.org/', search:'molecule?molecule_id='},
  {database:'Panther', url:'http://pantherdb.org/', search:'genes/geneList.do?searchType=basic&fieldName=all&organism=all&listType=1&fieldValue='},
  {database:'PID', url:null},
  {database:'PhosphoSitePlus', url:null},
  {database:'Reactome', url:'http://identifiers.org/reactome/', search:''},
  {database:'SMPD', url:null},
  {database:'Wikipathways', url:'http://identifiers.org/wikipathways/' , search:''},
  {database:'UniProt', url:'http://identifiers.org/uniprot/', search:''},
  {database:'HGNC Symbol', url:'http://identifiers.org/hgnc.symbol/', search:''},
  {database:'HGNC', url:'http://identifiers.org/hgnc/', search:''},
  {database:'ChEBI', url:'http://identifiers.org/chebi/', search:''},
  {database:'KEGG', url:'http://identifiers.org/kegg/', search:''},
  {database:'PubMed', url:'http://identifiers.org/pubmed/', search:''},
  {database:'Ensembl', url:'http://identifiers.org/ensembl/', search:''},
  {database:'Enzyme Nomenclature', url:'http://identifiers.org/ec-code/', search:''},
  {database:'PubChem-Substance', url:'http://identifiers.org/pubchem.substance/', search:''},
  {database:'3DMET', url:'http://identifiers.org/3dmet/', search:''},
  {database:'Chemical Component Dictionary', url:'http://identifiers.org/pdb-ccd/', search:''},
  {database:'CAS', url:'http://identifiers.org/cas/', search:''},
  {database:'HPRD',url:'http://identifiers.org/hprd/',search:''},
  {database:'RefSeq',url:'http://identifiers.org/refseq/',search:''},
  {database:'NCBI Gene',url:'http://identifiers.org/ncbigene/',search:''},
  {database:'Gene Cards',url:'http://identifiers.org/genecards/',search:''}
];<commit_msg>delete external database links that we won't show anymore<commit_after>module.exports = [
  {database:'Reactome', url:'http://identifiers.org/reactome/', search:''},
  {database:'UniProt', url:'http://identifiers.org/uniprot/', search:''},
  {database:'HGNC Symbol', url:'http://identifiers.org/hgnc.symbol/', search:''},
  {database:'HGNC', url:'http://identifiers.org/hgnc/', search:''},
  {database:'ChEBI', url:'http://identifiers.org/chebi/', search:''},
  {database:'PubMed', url:'http://identifiers.org/pubmed/', search:''},
  {database:'Ensembl', url:'http://identifiers.org/ensembl/', search:''},
  {database:'NCBI Gene',url:'http://identifiers.org/ncbigene/',search:''},
  {database:'Gene Cards',url:'http://identifiers.org/genecards/',search:''}
];<|endoftext|>


<commit_before>import { AudioContext } from '../audio/AudioContext.js';
import { FileLoader } from './FileLoader.js';
import { DefaultLoadingManager } from './LoadingManager.js';

/**
 * @author Reece Aaron Lecrivain / http://reecenotes.com/
 */

function AudioLoader( manager ) {

	this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;

}

Object.assign( AudioLoader.prototype, {

	load: function ( url, onLoad, onProgress, onError ) {

		var loader = new FileLoader( this.manager );
		loader.setResponseType( 'arraybuffer' );
		loader.load( url, function ( buffer ) {

			var context = AudioContext.getContext();

			context.decodeAudioData( buffer, function ( audioBuffer ) {

				onLoad( audioBuffer );

			} );

		}, onProgress, onError );

	}

} );

export { AudioLoader };
<commit_msg>AudioLoader: Clone buffer prior to decoding to allow reuse<commit_after>import { AudioContext } from '../audio/AudioContext.js';
import { FileLoader } from './FileLoader.js';
import { DefaultLoadingManager } from './LoadingManager.js';

/**
 * @author Reece Aaron Lecrivain / http://reecenotes.com/
 */

function AudioLoader( manager ) {

	this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;

}

Object.assign( AudioLoader.prototype, {

	load: function ( url, onLoad, onProgress, onError ) {

		var loader = new FileLoader( this.manager );
		loader.setResponseType( 'arraybuffer' );
		loader.load( url, function ( buffer ) {

			// Create a copy of the buffer. The `decodeAudioData` method
			// detaches the buffer when complete, preventing reuse.
			var bufferCopy = buffer.slice( 0 );

			var context = AudioContext.getContext();
			context.decodeAudioData( bufferCopy, function ( audioBuffer ) {

				onLoad( audioBuffer );

			} );

		}, onProgress, onError );

	}

} );

export { AudioLoader };
<|endoftext|>


<commit_before>Seed({
		name : "Mold.Lib.Filter",
		dna : "static"
	},
	function(){

		var _filter = {};
		var undefined;

		var _add = function(name, code){
			_filter[name] = code;
		}

		var _get = function(name){
			return _filter[name] || false;
		}

		_add("currency", function(value){
			value = +value;
			value = value.toFixed(2).replace(".", ",");
			value = value.substring(0, value.lastIndexOf(",") - 3)
					+ "." + value.substring(value.lastIndexOf(",") - 3, value.lastIndexOf(","))
					+ value.substring(value.lastIndexOf(","))

			return value;
		});

		_add("maxlen", function(data, conf){
			if(Mold.isArray(data)){
				data = data.splice(0, conf.len);
			}
			return data;
		})

		_add("topath", function(data, conf){
			var target = (conf.prefix) ? conf.prefix : "" + data.replace(/./g, "/");
			return target + (conf.ending) ? conf.ending : '.js';
		})

		_add("sort", function(data, conf){
			if(Mold.isArray(data)){
				if(conf.value){
					data.sort(function (a, b) {
						a = a[conf.value];
						b = b[conf.value];

						if (a > b) {
							return 1;
						}
						if (a < b) {
							return -1;
						}
						return 0;
					});
				}

				if(conf.desc){
					data.reverse();
				}
			}
			return data;
		});

		_add("exists", function(data, conf){
			console.log("data", data)

			if(Mold.isArray(data) && !data.length){
				return false;
			}

			if(Mold.isObject(data)){
				var test = 0;
				for(var prop in data){
					test++;
					if(data.hasProperty(prop)){

					}
				}
				if(test === 0){
					return false;
				}
			}

			if(data == undefined && data == null && data == false){
				return false;
			}

			return true;
		})

		_add("case", function(data, conf){
			for(var prop in conf){
				break;
			}
			if(data === prop){

				return true;
			}else{
				return false;
			}
		})

		_add("if", function(data, conf){
			if(conf.expression){
				conf.expression = conf.expression.replace(/this/g, "data");
				if(eval(conf.expression)){
					return data;
				}
				return false;
			}else{
				return true;
			}
		});

		return {
			add : _add,
			get : _get
		}
	}
)<commit_msg>console.log removed<commit_after>Seed({
		name : "Mold.Lib.Filter",
		dna : "static"
	},
	function(){

		var _filter = {};
		var undefined;

		var _add = function(name, code){
			_filter[name] = code;
		}

		var _get = function(name){
			return _filter[name] || false;
		}

		_add("currency", function(value){
			value = +value;
			value = value.toFixed(2).replace(".", ",");
			value = value.substring(0, value.lastIndexOf(",") - 3)
					+ "." + value.substring(value.lastIndexOf(",") - 3, value.lastIndexOf(","))
					+ value.substring(value.lastIndexOf(","))

			return value;
		});

		_add("maxlen", function(data, conf){
			if(Mold.isArray(data)){
				data = data.splice(0, conf.len);
			}
			return data;
		})

		_add("topath", function(data, conf){
			var target = (conf.prefix) ? conf.prefix : "" + data.replace(/./g, "/");
			return target + (conf.ending) ? conf.ending : '.js';
		})

		_add("sort", function(data, conf){
			if(Mold.isArray(data)){
				if(conf.value){
					data.sort(function (a, b) {
						a = a[conf.value];
						b = b[conf.value];

						if (a > b) {
							return 1;
						}
						if (a < b) {
							return -1;
						}
						return 0;
					});
				}

				if(conf.desc){
					data.reverse();
				}
			}
			return data;
		});

		_add("exists", function(data, conf){

			if(Mold.isArray(data) && !data.length){
				return false;
			}

			if(Mold.isObject(data)){
				var test = 0;
				for(var prop in data){
					test++;
					if(data.hasProperty(prop)){

					}
				}
				if(test === 0){
					return false;
				}
			}

			if(data == undefined && data == null && data == false){
				return false;
			}

			return true;
		})

		_add("case", function(data, conf){
			for(var prop in conf){
				break;
			}
			if(data === prop){

				return true;
			}else{
				return false;
			}
		})

		_add("if", function(data, conf){
			if(conf.expression){
				conf.expression = conf.expression.replace(/this/g, "data");
				if(eval(conf.expression)){
					return data;
				}
				return false;
			}else{
				return true;
			}
		});

		return {
			add : _add,
			get : _get
		}
	}
)<|endoftext|>


<commit_before>if (!Caminae) var Caminae = {};

Caminae.ObjectsLayer = L.GeoJSON.extend({
    COLOR: 'blue',
    HIGHLIGHT: 'red',
    WEIGHT: 2,
    OPACITY: 0.8,

    includes: L.Mixin.Events,

    initialize: function (geojson, options) {
        // Hold the definition of all layers - immutable
        this._objects = {};
        // Hold the currently added layers (subset of _objects)
        this._current_objects = {};

        this.spinner = null;
        this.rtree = new RTree();

        var onFeatureParse = function (geojson, layer) {
            this._mapObjects(geojson, layer);
            if (this._onEachFeature) this._onEachFeature(geojson, layer);
        };
        if (!options) options = {};
        this._onEachFeature = options.onEachFeature;
        options.onEachFeature = L.Util.bind(onFeatureParse, this);

        if (!options.style) {
            options.style = function (geojson) {
                return {
                    // TODO: fucking JS
                    //'color': Caminae.ObjectsLayer.COLOR,
                    //'opacity': Caminae.ObjectsLayer.OPACITY,
                    //'weight': Caminae.ObjectsLayer.WEIGHT,
                    'weight': 2
                }
            };
        }

        var dataurl = null;
        if (typeof(geojson) == 'string') {
            dataurl = geojson;
            geojson = null;
        }
        L.GeoJSON.prototype.initialize.call(this, geojson, options);

        if (dataurl) {
            this.load(dataurl);
        }
    },

    _rtbounds: function (bounds) {
        return {x: bounds.getSouthWest().lng,
                y: bounds.getSouthWest().lat,
                w: bounds.getSouthEast().lng - bounds.getSouthWest().lng,
                h: bounds.getNorthWest().lat - bounds.getSouthWest().lat};
    },

    _mapObjects: function (geojson, layer) {
        var pk = geojson.properties.pk
        this._objects[pk] = this._current_objects[pk] = layer;

        // Spatial indexing
        var bounds = layer.getBounds();
        this.rtree.insert(this._rtbounds(bounds), layer);

        // Highlight on mouse over
        layer.on('mouseover', L.Util.bind(function (e) {
            this.highlight(pk);
        }, this));
        layer.on('mouseout', L.Util.bind(function (e) {
            this.highlight(pk, false);
        }, this));

        // Optionnaly make them clickable
        if (this.options.objectUrl) {
            layer.on('click', L.Util.bind(function (e) {
                window.location = this.options.objectUrl(geojson, layer);
            }, this));
        }
    },

    load: function (url) {
        var jsonLoad = function (data) {
            this.addData(data);
            this.fire('load');
            if (this.spinner) this.spinner.stop();
        };
        if (this._map) this.spinner = new Spinner().spin(this._map._container);
        $.getJSON(url, L.Util.bind(jsonLoad, this));
    },

    getLayer: function (pk) {
        return this._objects[pk];
    },

    search: function (bounds) {
        var rtbounds = this._rtbounds(bounds);
        return this.rtree.search(rtbounds);
    },

    // Show all layers matching the pks
    updateFromPks: function(pks) {
        var self = this
          , new_objects = {}
          , already_added_layer
          , to_add_layer
        ;

        // Gather all layer to see in new objects
        // Remove them from _current_objects if they are already shown
        // This way _current_objects will only contain layer to be removed
        $.each(pks, function(idx, to_add_pk) {
            already_added_layer = self._current_objects[to_add_pk];
            if (already_added_layer) {
                new_objects[to_add_pk] = already_added_layer;
                delete self._current_objects[to_add_pk]
            } else {
                to_add_layer = new_objects[to_add_pk] = self._objects[to_add_pk];
                // list can be ready before map, on first load
                if (to_add_layer) self.addLayer(to_add_layer);
            }
        });

        // Remove all remaining layer
        $.each(self._current_objects, function(pk, layer) {
            self.removeLayer(layer);
        });

        self._current_objects = new_objects;
    },

    highlight: function (pk, on) {
        var off = false;
        if (arguments.length == 2)
            off = !on;
        var l = this.getLayer(pk);
        if (l) l.setStyle({
            'opacity': off ? 0.8 : 1.0,
            'color': off ? 'blue' : 'red',
            'weight': off ? 2 : 5,
        });
    },
});

Caminae.getWKT = function(layer) {
    coord2str = function (obj) {
        if(obj.lng) return '(' + obj.lng + ' ' + obj.lat + ' 0.0)';
        var n, wkt = [];
        for (n in obj) {
            wkt.push(coord2str(obj[n]));
        }
        return ("(" + String(wkt) + ")");
    };
    var coords = '()';
    if(layer.getLatLng) {
        coords = coord2str(layer.getLatLng());
    }
    else if (layer.getLatLngs) {
        coords = coord2str(layer.getLatLngs());
    }
    var wkt = '';
    if (layer instanceof L.Marker) wkt += 'POINT'+coords;
    else if (layer instanceof L.Polygon) wkt += 'POLYGON'+coords;
    else if (layer instanceof L.MultiPolygon) wkt += 'MULTIPOLYGON'+coords;
    else if (layer instanceof L.Polyline) wkt += 'LINESTRING'+coords;
    else if (layer instanceof L.MultiPolyline) wkt += 'MULTILINESTRING'+coords;
    else {
        wkt += 'GEOMETRY'+coords;
    }
    return wkt;
};

L.Control.Information = L.Control.extend({
    options: {
        position: 'bottomright',
    },

    onAdd: function (map) {
        this._container = L.DomUtil.create('div', 'leaflet-control-attribution');
        L.DomEvent.disableClickPropagation(this._container);

        map.on('layeradd', this._onLayerAdd, this)
           .on('layerremove', this._onLayerRemove, this);

        return this._container;
    },

    onRemove: function (map) {
        map.off('layeradd', this._onLayerAdd)
           .off('layerremove', this._onLayerRemove);

    },

    _onLayerAdd: function (e) {
        e.layer.on('info', L.Util.bind(function (ei) {
            this._container.innerHTML = ei.info;
        }, this));
    },

    _onLayerRemove: function (e) {
        e.layer.off('info');
    }
});

L.Handler.SnappedEdit = L.Handler.PolyEdit.extend({
    SNAP_DISTANCE: 15,  // snap on marker move
    TOLERANCE: 0.00005, // snap existing object

    initialize: function (poly, options) {
        L.Handler.PolyEdit.prototype.initialize.call(this, poly, options);
        this._snaplist = [];
    },

    setSnapList: function (l) {
        this._snaplist = l;
        this._markerGroup.eachLayer(L.Util.bind(function (marker) {
            // Mark as snap if any object of snaplist is already snapped !
            var closest = this._closest(marker),
                chosen = closest[0],
                point = closest[1];
            if (point &&
                (Math.abs(point.lat - marker.getLatLng().lat) < this.TOLERANCE)  &&
                (Math.abs(point.lng - marker.getLatLng().lng) < this.TOLERANCE)) {
                $(marker._icon).addClass('marker-snapped');
            }
        }, this));
    },

    distance: function (latlng1, latlng2) {
        return this._poly._map.latLngToLayerPoint(latlng1).distanceTo(this._poly._map.latLngToLayerPoint(latlng2));
    },

    distanceSegment: function (latlng, latlngA, latlngB) {
        var p = this._poly._map.latLngToLayerPoint(latlng),
           p1 = this._poly._map.latLngToLayerPoint(latlngA),
           p2 = this._poly._map.latLngToLayerPoint(latlngB);
        return L.LineUtil.pointToSegmentDistance(p, p1, p2);
    },

    latlngOnSegment: function (latlng, latlngA, latlngB) {
        var p = this._poly._map.latLngToLayerPoint(latlng),
           p1 = this._poly._map.latLngToLayerPoint(latlngA),
           p2 = this._poly._map.latLngToLayerPoint(latlngB);
           closest = L.LineUtil.closestPointOnSegment(p, p1, p2);
        return this._poly._map.layerPointToLatLng(closest);
    },

    _closest: function (marker) {
        var mindist = Number.MAX_VALUE,
             chosen = null,
             point = null;
        var n = this._snaplist.length;
        // /!\ Careful with size of this list, iterated at every marker move!
        if (n>1000) console.warn("Snap list is very big : " + n + " objects!");

        // Iterate the whole snaplist
        for (var i = 0; i < this._snaplist.length; i++) {
            var object = this._snaplist[i],
                ll = null,
                distance = Number.MAX_VALUE;
            if (object.getLatLng) {
                // Single dimension, snap on points
                ll = object.getLatLng();
                distance = this.distance(marker.getLatLng(), ll);
            }
            else {
                // Iterate on line segments
                var lls = object.getLatLngs(),
                    segmentmindist = Number.MAX_VALUE;
                // Keep the closest point of all segments
                for (var j = 0; j < lls.length - 1; j++) {
                    var p1 = lls[j],
                        p2 = lls[j+1],
                        d = this.distanceSegment(marker.getLatLng(), p1, p2);
                    if (d < segmentmindist) {
                        segmentmindist = d;
                        ll = this.latlngOnSegment(marker.getLatLng(), p1, p2);
                        distance = d;
                    }
                }
            }
            // Keep the closest point of all objects
            if (distance < this.SNAP_DISTANCE && distance < mindist) {
                mindist = distance;
                chosen = object;
                point = ll;
            }
        }
        return [chosen, point];
    },

    _snapMarker: function (e) {
        var marker = e.target
        var closest = this._closest(marker),
            chosen = closest[0],
            point = closest[1];
        if (chosen) {
            marker.setLatLng(point);
            if (marker.snap != chosen) {
                marker.snap = chosen;
                $(marker._icon).addClass('marker-snapped');
                this._poly.fire('snap', {object:chosen, marker: marker, location: point});
            }
        }
        else {
            if (marker.snap) {
                $(marker._icon).removeClass('marker-snapped');
                this._poly.fire('unsnap', {object:marker.snap, marker: marker});
            }
            marker.snap = null;
        }
    },

    _createMarker: function (latlng, index) {
        var marker = L.Handler.PolyEdit.prototype._createMarker.call(this, latlng, index);
        marker.on('move', this._snapMarker, this);
        return marker;
    },
});

Caminae.makeGeoFieldProxy = function($field, layer) {
    // Proxy to field storing WKT. It also stores the matching layer.
    var _current_layer = layer || null;

    return {
        storeLayerGeomInField: function(layer) {
            var old_layer = _current_layer;
            _current_layer = layer;

            var wkt = layer ? Caminae.getWKT(layer) : '';
            $field.val(wkt);

            return old_layer;
        },
        getLayer: function () {
            return _current_layer;
        }
    };
};
<commit_msg>Rework snapped layer handler (ref #109)<commit_after>if (!Caminae) var Caminae = {};

Caminae.ObjectsLayer = L.GeoJSON.extend({
    COLOR: 'blue',
    HIGHLIGHT: 'red',
    WEIGHT: 2,
    OPACITY: 0.8,

    includes: L.Mixin.Events,

    initialize: function (geojson, options) {
        // Hold the definition of all layers - immutable
        this._objects = {};
        // Hold the currently added layers (subset of _objects)
        this._current_objects = {};

        this.spinner = null;
        this.rtree = new RTree();

        var onFeatureParse = function (geojson, layer) {
            this._mapObjects(geojson, layer);
            if (this._onEachFeature) this._onEachFeature(geojson, layer);
        };
        if (!options) options = {};
        this._onEachFeature = options.onEachFeature;
        options.onEachFeature = L.Util.bind(onFeatureParse, this);

        if (!options.style) {
            options.style = function (geojson) {
                return {
                    // TODO: fucking JS
                    //'color': Caminae.ObjectsLayer.COLOR,
                    //'opacity': Caminae.ObjectsLayer.OPACITY,
                    //'weight': Caminae.ObjectsLayer.WEIGHT,
                    'weight': 2
                }
            };
        }

        var dataurl = null;
        if (typeof(geojson) == 'string') {
            dataurl = geojson;
            geojson = null;
        }
        L.GeoJSON.prototype.initialize.call(this, geojson, options);

        if (dataurl) {
            this.load(dataurl);
        }
    },

    _rtbounds: function (bounds) {
        return {x: bounds.getSouthWest().lng,
                y: bounds.getSouthWest().lat,
                w: bounds.getSouthEast().lng - bounds.getSouthWest().lng,
                h: bounds.getNorthWest().lat - bounds.getSouthWest().lat};
    },

    _mapObjects: function (geojson, layer) {
        var pk = geojson.properties.pk
        this._objects[pk] = this._current_objects[pk] = layer;

        // Spatial indexing
        var bounds = null;
        if (layer.getBounds) {
            bounds = layer.getBounds();
        }
        else {
            bounds = new L.LatLngBounds(layer.getLatLng(), layer.getLatLng());
        }
        this.rtree.insert(this._rtbounds(bounds), layer);

        // Highlight on mouse over
        layer.on('mouseover', L.Util.bind(function (e) {
            this.highlight(pk);
        }, this));
        layer.on('mouseout', L.Util.bind(function (e) {
            this.highlight(pk, false);
        }, this));

        // Optionnaly make them clickable
        if (this.options.objectUrl) {
            layer.on('click', L.Util.bind(function (e) {
                window.location = this.options.objectUrl(geojson, layer);
            }, this));
        }
    },

    load: function (url) {
        var jsonLoad = function (data) {
            this.addData(data);
            this.fire('load');
            if (this.spinner) this.spinner.stop();
        };
        if (this._map) this.spinner = new Spinner().spin(this._map._container);
        $.getJSON(url, L.Util.bind(jsonLoad, this));
    },

    getLayer: function (pk) {
        return this._objects[pk];
    },

    search: function (bounds) {
        var rtbounds = this._rtbounds(bounds);
        return this.rtree.search(rtbounds);
    },

    // Show all layers matching the pks
    updateFromPks: function(pks) {
        var self = this
          , new_objects = {}
          , already_added_layer
          , to_add_layer
        ;

        // Gather all layer to see in new objects
        // Remove them from _current_objects if they are already shown
        // This way _current_objects will only contain layer to be removed
        $.each(pks, function(idx, to_add_pk) {
            already_added_layer = self._current_objects[to_add_pk];
            if (already_added_layer) {
                new_objects[to_add_pk] = already_added_layer;
                delete self._current_objects[to_add_pk]
            } else {
                to_add_layer = new_objects[to_add_pk] = self._objects[to_add_pk];
                // list can be ready before map, on first load
                if (to_add_layer) self.addLayer(to_add_layer);
            }
        });

        // Remove all remaining layer
        $.each(self._current_objects, function(pk, layer) {
            self.removeLayer(layer);
        });

        self._current_objects = new_objects;
    },

    highlight: function (pk, on) {
        var off = false;
        if (arguments.length == 2)
            off = !on;
        var l = this.getLayer(pk);
        if (l) l.setStyle({
            'opacity': off ? 0.8 : 1.0,
            'color': off ? 'blue' : 'red',
            'weight': off ? 2 : 5,
        });
    },
});

Caminae.getWKT = function(layer) {
    coord2str = function (obj) {
        if(obj.lng) return '(' + obj.lng + ' ' + obj.lat + ' 0.0)';
        var n, wkt = [];
        for (n in obj) {
            wkt.push(coord2str(obj[n]));
        }
        return ("(" + String(wkt) + ")");
    };
    var coords = '()';
    if(layer.getLatLng) {
        coords = coord2str(layer.getLatLng());
    }
    else if (layer.getLatLngs) {
        coords = coord2str(layer.getLatLngs());
    }
    var wkt = '';
    if (layer instanceof L.Marker) wkt += 'POINT'+coords;
    else if (layer instanceof L.Polygon) wkt += 'POLYGON'+coords;
    else if (layer instanceof L.MultiPolygon) wkt += 'MULTIPOLYGON'+coords;
    else if (layer instanceof L.Polyline) wkt += 'LINESTRING'+coords;
    else if (layer instanceof L.MultiPolyline) wkt += 'MULTILINESTRING'+coords;
    else {
        wkt += 'GEOMETRY'+coords;
    }
    return wkt;
};

L.Control.Information = L.Control.extend({
    options: {
        position: 'bottomright',
    },

    onAdd: function (map) {
        this._container = L.DomUtil.create('div', 'leaflet-control-attribution');
        L.DomEvent.disableClickPropagation(this._container);

        map.on('layeradd', this._onLayerAdd, this)
           .on('layerremove', this._onLayerRemove, this);

        return this._container;
    },

    onRemove: function (map) {
        map.off('layeradd', this._onLayerAdd)
           .off('layerremove', this._onLayerRemove);

    },

    _onLayerAdd: function (e) {
        e.layer.on('info', L.Util.bind(function (ei) {
            this._container.innerHTML = ei.info;
        }, this));
    },

    _onLayerRemove: function (e) {
        e.layer.off('info');
    }
});

Caminae.MarkerSnapping = L.Handler.extend({
    SNAP_DISTANCE: 15,  // snap on marker move
    TOLERANCE: 0.00005, // snap existing object

    initialize: function (marker) {
        this._map = null;
        this._snaplist = [];
        this._markers = []
        if (marker) {
            this.snapMarker(marker);
        }
    },

    enable: function () {
        for (var i=0; i<this._markers.length; i++) {
            this.snapMarker(this._markers[i]);
        }
    },

    disable: function () {
        for (var i=0; i<this._markers.length; i++) {
            this.unsnapMarker(this._markers[i]);
        }
    },

    snapMarker: function (marker) {
        if (!this._map) this._map = marker._map;
        this._markers.push(marker);
        marker.on('move', this._snapMarker, this);
    },

    unsnapMarker: function (marker) {
        marker.off('move', this._snapMarker);
    },

    setSnapList: function (l) {
        this._snaplist = l;
        for (var i=0; i<this._markers.length; i++) {
            var marker = this._markers[i];
            // Mark as snap if any object of snaplist is already snapped !
            var closest = this._closest(marker),
                chosen = closest[0],
                point = closest[1];
            if (point &&
                (Math.abs(point.lat - marker.getLatLng().lat) < this.TOLERANCE)  &&
                (Math.abs(point.lng - marker.getLatLng().lng) < this.TOLERANCE)) {
                $(marker._icon).addClass('marker-snapped');
            }
        }
    },

    distance: function (latlng1, latlng2) {
        return this._map.latLngToLayerPoint(latlng1).distanceTo(this._map.latLngToLayerPoint(latlng2));
    },

    distanceSegment: function (latlng, latlngA, latlngB) {
        var p = this._map.latLngToLayerPoint(latlng),
           p1 = this._map.latLngToLayerPoint(latlngA),
           p2 = this._map.latLngToLayerPoint(latlngB);
        return L.LineUtil.pointToSegmentDistance(p, p1, p2);
    },

    latlngOnSegment: function (latlng, latlngA, latlngB) {
        var p = this._map.latLngToLayerPoint(latlng),
           p1 = this._map.latLngToLayerPoint(latlngA),
           p2 = this._map.latLngToLayerPoint(latlngB);
           closest = L.LineUtil.closestPointOnSegment(p, p1, p2);
        return this._map.layerPointToLatLng(closest);
    },

    _closest: function (marker) {
        var mindist = Number.MAX_VALUE,
             chosen = null,
             point = null;
        var n = this._snaplist.length;
        // /!\ Careful with size of this list, iterated at every marker move!
        if (n>1000) console.warn("Snap list is very big : " + n + " objects!");

        // Iterate the whole snaplist
        for (var i = 0; i < this._snaplist.length; i++) {
            var object = this._snaplist[i],
                ll = null,
                distance = Number.MAX_VALUE;
            if (object.getLatLng) {
                // Single dimension, snap on points
                ll = object.getLatLng();
                distance = this.distance(marker.getLatLng(), ll);
            }
            else {
                // Iterate on line segments
                var lls = object.getLatLngs(),
                    segmentmindist = Number.MAX_VALUE;
                // Keep the closest point of all segments
                for (var j = 0; j < lls.length - 1; j++) {
                    var p1 = lls[j],
                        p2 = lls[j+1],
                        d = this.distanceSegment(marker.getLatLng(), p1, p2);
                    if (d < segmentmindist) {
                        segmentmindist = d;
                        ll = this.latlngOnSegment(marker.getLatLng(), p1, p2);
                        distance = d;
                    }
                }
            }
            // Keep the closest point of all objects
            if (distance < this.SNAP_DISTANCE && distance < mindist) {
                mindist = distance;
                chosen = object;
                point = ll;
            }
        }
        return [chosen, point];
    },

    _snapMarker: function (e) {
        var marker = e.target
        var closest = this._closest(marker),
            chosen = closest[0],
            point = closest[1];
        if (chosen) {
            marker.setLatLng(point);
            if (marker.snap != chosen) {
                marker.snap = chosen;
                $(marker._icon).addClass('marker-snapped');
                marker.fire('snap', {object:chosen, location: point});
            }
        }
        else {
            if (marker.snap) {
                $(marker._icon).removeClass('marker-snapped');
                marker.fire('unsnap', {object:marker.snap});
            }
            marker.snap = null;
        }
    },
});

L.Handler.SnappedEdit = L.Handler.PolyEdit.extend({

    initialize: function (poly, options) {
        L.Handler.PolyEdit.prototype.initialize.call(this, poly, options);
        this._snapper = new Caminae.MarkerSnapping(this._poly._map);
    },

    setSnapList: function (l) {
        this._snapper.setSnapList(l);
    },

    _createMarker: function (latlng, index) {
        var marker = L.Handler.PolyEdit.prototype._createMarker.call(this, latlng, index);
        this._snapper.snapMarker(marker);
        return marker;
    },
});

Caminae.makeGeoFieldProxy = function($field, layer) {
    // Proxy to field storing WKT. It also stores the matching layer.
    var _current_layer = layer || null;

    return {
        storeLayerGeomInField: function(layer) {
            var old_layer = _current_layer;
            _current_layer = layer;

            var wkt = layer ? Caminae.getWKT(layer) : '';
            $field.val(wkt);

            return old_layer;
        },
        getLayer: function () {
            return _current_layer;
        }
    };
};
<|endoftext|>


<commit_before>import React from 'react'
import { Route } from 'react-router'
import App from './containers/App'
import UserPage from './containers/UserPage'
import RepoPage from './containers/RepoPage'

export default <Route path="/" component={App}>
  <Route path="/:login/:name"
         component={RepoPage} />
  <Route path="/:login"
         component={UserPage} />
</Route>
<commit_msg>Remove the unuse file. (#2595)<commit_after><|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var chef = require('gulp-chef');

var consolidate = require('gulp-consolidate').bind(null, 'nunjucks');

var configs = {
	$description: 'This is to demo what gulp-chef can achieve, not encourage you write configuration this way.',
	src: 'src/',
	dest: 'dist/',
	'.gulp-cheagsheet': {
		description: 'Recipes from gulp cheatsheet: https://github.com/osscafe/gulp-cheatsheet.',
		'single-dest-and-watch': {
			src: 'js/',
			dest: 'js/',
			pipe: {
				'.coffee': {
					plugin: 'gulp-coffee',
					src: '*.coffee'
				},
				'.uglify': {
					plugin: 'gulp-uglify',
					spit: true
				}
			}
		},
		'multi-dest': {
			src: 'css/',
			dest: 'css/',
			pipe: {
				'.autoprefixer': {
					plugin: 'gulp-autoprefixer',
					src: 'style.css',
					options: 'last 2 versions',
					spit: true
				},
				'.minify': {
					plugin: 'gulp-minify-css'
				},
				'.rename': {
					plugin: 'gulp-rename',
					options: {
						extname: '.min.css'
					},
					spit: true
				}
			}
		},
		'incremental-rebuilding': {
			src: 'js/',
			dest: 'js/',
			pipe: {
				'.cached': {
					plugin: 'gulp-cached',
					src: '*.js'
				},
				'.uglify': {
					plugin: 'gulp-uglify'
				},
				'.remember': {
					plugin: 'gulp-remember'
				},
				'.concat': {
					plugin: 'gulp-concat',
					options: 'app.js',
					spit: true
				}
			}
		},
		'only-changed': {
			pipe: {
				'.changed': {
					plugin: 'gulp-changed',
					options: '{{dest.path}}'
				},
				'.uglify': {
					plugin: 'gulp-uglify',
					spit: true
				}
			}
		},
		'async-streams': {
			src: 'css/',
			dest: 'css/',
			merge: {
				'.less': {
					plugin: 'gulp-less',
					src: 'first.less'
				},
				'.autoprefixer': {
					plugin: 'gulp-autoprefixer',
					src: 'second.css'
				}
			}
		},
		'serial-join': {
			src: 'css/',
			dest: 'css/',
			pipe: {
				queue: {
					'.less': {
						plugin: 'gulp-less',
						src: 'first.less'
					},
					pipe: {
						src: 'second.css',
						'.cssimport': {
							plugin: 'gulp-cssimport'
						},
						'.autoprefixer': {
							plugin: 'gulp-autoprefixer',
							options: 'last 2 versions'
						}
					}
				},
				'.concat': {
					plugin: 'gulp-concat',
					options: 'app.css'
				},
				'.minify': {
					plugin: 'gulp-minify-css',
					spit: true
				}
			}
		},
		'stream-array': {
			src: 'template/',
			dest: 'html/',
			each: {
				values: [{
					name: 'apple',
					title: 'Apple Cake',
					price: '25'
				}, {
					name: 'orange',
					title: 'Orange Cookie',
					price: '18'
				}],
				pipe: {
					'.consolidate': {
						plugin: consolidate,
						src: 'a.ejs',
						options: {
							title: '{{title}}',
							price: '{{price}}'
						}
					},
					'.rename': {
						plugin: 'gulp-rename',
						options: {
							basename: '{{name}}',
							extname: '.html'
						},
						spit: true
					}
				}
			}
		}
	},
	default: 'async-streams'
};

var meal = chef(configs);

gulp.registry(meal);
<commit_msg>feature (examples/recipes-demo): make gulpfile.js default to all<commit_after>'use strict';

var gulp = require('gulp');
var chef = require('gulp-chef');

var consolidate = require('gulp-consolidate').bind(null, 'nunjucks');

var configs = {
	$description: 'This is to demo what gulp-chef can achieve, not encourage you write configuration this way.',
	src: 'src/',
	dest: 'dist/',
	'.gulp-cheagsheet': {
		description: 'Recipes from gulp cheatsheet: https://github.com/osscafe/gulp-cheatsheet.',
		'single-dest-and-watch': {
			src: 'js/',
			dest: 'js/',
			pipe: {
				'.coffee': {
					plugin: 'gulp-coffee',
					src: '*.coffee'
				},
				'.uglify': {
					plugin: 'gulp-uglify',
					spit: true
				}
			}
		},
		'multi-dest': {
			src: 'css/',
			dest: 'css/',
			pipe: {
				'.autoprefixer': {
					plugin: 'gulp-autoprefixer',
					src: 'style.css',
					options: 'last 2 versions',
					spit: true
				},
				'.minify': {
					plugin: 'gulp-minify-css'
				},
				'.rename': {
					plugin: 'gulp-rename',
					options: {
						extname: '.min.css'
					},
					spit: true
				}
			}
		},
		'incremental-rebuilding': {
			src: 'js/',
			dest: 'js/',
			pipe: {
				'.cached': {
					plugin: 'gulp-cached',
					src: '*.js'
				},
				'.uglify': {
					plugin: 'gulp-uglify'
				},
				'.remember': {
					plugin: 'gulp-remember'
				},
				'.concat': {
					plugin: 'gulp-concat',
					options: 'app.js',
					spit: true
				}
			}
		},
		'only-changed': {
			pipe: {
				'.changed': {
					plugin: 'gulp-changed',
					options: '{{dest.path}}'
				},
				'.uglify': {
					plugin: 'gulp-uglify',
					spit: true
				}
			}
		},
		'async-streams': {
			src: 'css/',
			dest: 'css/',
			merge: {
				'.less': {
					plugin: 'gulp-less',
					src: 'first.less'
				},
				'.autoprefixer': {
					plugin: 'gulp-autoprefixer',
					src: 'second.css'
				}
			}
		},
		'serial-join': {
			src: 'css/',
			dest: 'css/',
			pipe: {
				queue: {
					'.less': {
						plugin: 'gulp-less',
						src: 'first.less'
					},
					pipe: {
						src: 'second.css',
						'.cssimport': {
							plugin: 'gulp-cssimport'
						},
						'.autoprefixer': {
							plugin: 'gulp-autoprefixer',
							options: 'last 2 versions'
						}
					}
				},
				'.concat': {
					plugin: 'gulp-concat',
					options: 'app.css'
				},
				'.minify': {
					plugin: 'gulp-minify-css',
					spit: true
				}
			}
		},
		'stream-array': {
			src: 'template/',
			dest: 'html/',
			each: {
				values: [{
					name: 'apple',
					title: 'Apple Cake',
					price: '25'
				}, {
					name: 'orange',
					title: 'Orange Cookie',
					price: '18'
				}],
				pipe: {
					'.consolidate': {
						plugin: consolidate,
						src: 'a.ejs',
						options: {
							title: '{{title}}',
							price: '{{price}}'
						}
					},
					'.rename': {
						plugin: 'gulp-rename',
						options: {
							basename: '{{name}}',
							extname: '.html'
						},
						spit: true
					}
				}
			}
		}
	},
	default: {
		parallel: ['single-dest-and-watch', 'multi-dest', 'incremental-rebuilding', 'only-changed', 'async-streams', 'serial-join', 'stream-array']
	}
};

var meal = chef(configs);

gulp.registry(meal);
<|endoftext|>


<commit_before>/*eslint-disable no-unused-vars*/
import "babel-polyfill"

import React from 'react'
import ReactDOM from 'react-dom'
import { createStore, applyMiddleware } from 'redux'
import createSagaMiddleware from 'redux-saga'
// import sagaMonitor from './sagaMonitor'

import Counter from './components/Counter'
import reducer from './reducers'
import rootSaga from './sagas'

const sagaMiddleware = createSagaMiddleware(/* {sagaMonitor} */)
const store = createStore(
  reducer,
  applyMiddleware(sagaMiddleware)
)
sagaMiddleware.run(rootSaga)

const action = type => store.dispatch({type})

function render() {
  ReactDOM.render(
    <Counter
      value={store.getState()}
      onIncrement={() => action('INCREMENT')}
      onDecrement={() => action('DECREMENT')}
      onIncrementIfOdd={() => action('INCREMENT_IF_ODD')}
      onIncrementAsync={() => action('INCREMENT_ASYNC')} />,
    document.getElementById('root')
  )
}

render()
store.subscribe(render)
<commit_msg>Apply extension's enhancer to saga-counter example<commit_after>/*eslint-disable no-unused-vars*/
import "babel-polyfill"

import React from 'react'
import ReactDOM from 'react-dom'
import { createStore, applyMiddleware, compose } from 'redux'
import createSagaMiddleware from 'redux-saga'
// import sagaMonitor from './sagaMonitor'

import Counter from './components/Counter'
import reducer from './reducers'
import rootSaga from './sagas'

const sagaMiddleware = createSagaMiddleware(/* {sagaMonitor} */)
const store = createStore(
  reducer,
  compose(
    applyMiddleware(sagaMiddleware),
    window.devToolsExtension && window.devToolsExtension()
  )
)
sagaMiddleware.run(rootSaga)

const action = type => store.dispatch({type})

function render() {
  ReactDOM.render(
    <Counter
      value={store.getState()}
      onIncrement={() => action('INCREMENT')}
      onDecrement={() => action('DECREMENT')}
      onIncrementIfOdd={() => action('INCREMENT_IF_ODD')}
      onIncrementAsync={() => action('INCREMENT_ASYNC')} />,
    document.getElementById('root')
  )
}

render()
store.subscribe(render)
<|endoftext|>