<commit_before>(function(){
	"use strict";

	class KC3BlueprintsDefinition extends KC3ShipListGrid {
		constructor() {
			super("blueprints");
		}

		/* INIT
		Prepares initial static data needed.
		---------------------------------*/
		init() {
			this.defaultSorterDefinitions();
			this.defineSimpleSorter("materials", "Consumptions",
				(ship) => -ship.materials.length);
			this.defineSimpleFilter("materials", [], 0, (index, ship) => ship.materials.length);
			this.showListRowCallback = this.showRemodelMaterials;
			this.heartLockMode = 2;
			this.viewType = "owned";
		}

		/* RELOAD
		Loads latest player or game data if needed.
		---------------------------------*/
		reload() {
			PlayerManager.loadConsumables();
			KC3ShipManager.load();
		}

		/* EXECUTE
		Places data onto the interface from scratch.
		---------------------------------*/
		execute() {
			$(".tab_blueprints .view_type input[type=radio][name=view_type]")
				.on("change", function() {
				const viewType = $("input[type=radio][name=view_type]:checked").val();
				KC3StrategyTabs.gotoTab(undefined, viewType);
			});
			this.shipListDiv = $(".tab_blueprints .ship_list");
			this.shipRowTemplateDiv = $(".tab_blueprints .factory .ship_item");
			this.registerShipListHeaderEvent(
				$(".tab_blueprints .ship_header .ship_field.hover")
			);
			this.shipListDiv.on("preShow", () => {
				$(".tab_blueprints .total").hide();
				$(".tab_blueprints .owned").hide();
			});
			this.shipListDiv.on("postShow", this.showTotalMaterials);
			this.loadView(KC3StrategyTabs.pageParams[1]);
		}

		loadView(viewType = "owned") {
			this.viewType = viewType;
			$(".tab_blueprints .view_type input[type=radio][name=view_type][value={0}]"
				.format(this.viewType)).prop("checked", true);
			switch(this.viewType) {
				case "owned":
					this.setSorter("lv");
					this.prepareShipList(true, this.mapRemodelMaterials);
					break;
				case "all":
					this.setSorter("type");
					this.prepareShipListFromRemodelDb();
					break;
				default:
					console.warn("Unsupported view type:", this.viewType);
					return;
			}
			this.showListGrid();
		}

		prepareShipListFromRemodelDb() {
			const allRemodelInfo = RemodelDb._db.remodelInfo;
			this.shipList.length = 0;
			Object.keys(allRemodelInfo).forEach(key => {
				const remodelInfo = allRemodelInfo[key];
				if(remodelInfo.blueprint || remodelInfo.catapult) {
					const shipMaster = KC3Master.ship(remodelInfo.ship_id_from);
					const shipData = {
						id: remodelInfo.ship_id_from,
						masterId: remodelInfo.ship_id_from,
						stype: shipMaster.api_stype,
						ctype: shipMaster.api_ctype,
						sortno: shipMaster.api_sortno,
						name: KC3Meta.shipName(shipMaster.api_name),
						level: remodelInfo.level,
						levelClass: "",
						locked: 1
					};
					const remodelFormIds = RemodelDb.remodelGroup(remodelInfo.ship_id_to);
					const ownedMasterId = KC3ShipManager.find(
						ship => remodelFormIds.indexOf(ship.masterId) >=
							remodelFormIds.indexOf(remodelInfo.ship_id_to)
					).length > 0 ? remodelInfo.ship_id_to : 0;
					this.attachRemodelMaterials(shipData, [shipData.masterId], ownedMasterId);
					this.shipList.push(shipData);
				}
			});
			return true;
		}

		mapRemodelMaterials(shipObj) {
			const mappedObj = this.defaultShipDataMapping(shipObj);
			this.attachRemodelMaterials(mappedObj,
				RemodelDb.remodelGroup(mappedObj.masterId));
			return mappedObj;
		}

		attachRemodelMaterials(mappedObj, remodelFormIds = [], ownedMasterId = 0) {
			const remodelGroup = RemodelDb.remodelGroup(mappedObj.masterId);
			mappedObj.materials = [];
			for(let masterId of remodelFormIds) {
				const remodelInfo = RemodelDb.remodelInfo(masterId);
				if(remodelInfo) {
					// Check and mark possibly used material
					const isUsed = remodelGroup.indexOf(ownedMasterId || mappedObj.masterId)
						>= remodelGroup.indexOf(remodelInfo.ship_id_to);
					// Current remodel info support these materials
					if(remodelInfo.blueprint) {
						mappedObj.materials.push({
							icon: 58,
							info: remodelInfo,
							used: isUsed
						});
					}
					if(remodelInfo.catapult) {
						mappedObj.materials.push({
							icon: 65,
							info: remodelInfo,
							used: isUsed
						});
					}
				}
			}
			return mappedObj;
		}

		showRemodelMaterials(ship, shipRow) {
			let firstMaterial = null;
			for(let material of ship.materials) {
				firstMaterial = firstMaterial || material;
				const iconDiv = $("
")
					.addClass("ship_field icon")
					.toggleClass("limited", this.viewType === "all");
				$("")
					.attr("src", "../../assets/img/useitems/" + material.icon + ".png")
					.appendTo(iconDiv);
				$("")
					.text(KC3Meta.useItemName(material.icon))
					.toggleClass("used", material.used).appendTo(iconDiv);
				iconDiv.attr("title", this.buildMaterialTooltip(material.info));
				$(".need_materials", shipRow).append(iconDiv);
			}
			if(this.viewType === "all" && firstMaterial) {
				const shipDiv = $("
")
					.addClass("ship_field icon")
					.toggleClass("limited", this.viewType === "all");
				$("").attr("src", "../../assets/img/ui/arrow.png")
					.appendTo(shipDiv);
				$("")
					.attr("src", KC3Meta.shipIcon(firstMaterial.info.ship_id_to))
					.attr("alt", firstMaterial.info.ship_id_to)
					.click(this.shipClickFunc)
					.addClass("hover")
					.appendTo(shipDiv);
				$("")
					.text(KC3Meta.shipName(
						KC3Master.ship(firstMaterial.info.ship_id_to).api_name
					)).appendTo(shipDiv);
				$(".need_materials", shipRow).append(shipDiv);
			}
		}

		showTotalMaterials(event, { shipList }) {
			const totalDiv = $(".tab_blueprints .total .total_items").empty();
			const ownedDiv = $(".tab_blueprints .owned .owned_items").empty();

			let totalItemDiv = $("
").addClass("summary_item").appendTo(totalDiv);
			$("")
				.attr("src", "../../assets/img/client/ship.png")
				.appendTo(totalItemDiv);
			$("")
				.text("x{0}".format(shipList.length))
				.appendTo(totalItemDiv);

			// Count total and used remodel materials
			const countMaterials = (resultMap = ({}), filter = (m => true)) => {
				[].concat(...shipList.map(ship => ship.materials
					.filter(filter).map(
					m => new Array(m.icon === 58 ? m.info.blueprint :
									m.icon === 65 ? m.info.catapult :
									1).fill(m.icon)
				))).map(icon => {
					resultMap[icon] = resultMap[icon] || 0;
					resultMap[icon] += 1;
				});
				return resultMap;
			};
			const materialCount = countMaterials();
			const usedCount = countMaterials({}, (m => m.used));

			// Show total results and owned materials
			const appendOwnedItem = (iconImg, count) => {
				const ownedItemDiv = $("
")
					.addClass("summary_item").appendTo(ownedDiv);
				iconImg.clone().appendTo(ownedItemDiv);
				$("")
					.text("x{0}".format(count || 0))
					.appendTo(ownedItemDiv);
			};
			for(let icon in materialCount) {
				const totalItemDiv = $("
").addClass("summary_item").appendTo(totalDiv);
				const iconImg = $("")
					.attr("src", "../../assets/img/useitems/" + icon + ".png")
					.appendTo(totalItemDiv);
				$("")
					.text("x{0}/{1}".format(
						materialCount[icon] - (usedCount[icon] || 0),
						materialCount[icon]
					)).appendTo(totalItemDiv);
				switch(Number(icon)) {
					case 58:
						appendOwnedItem(iconImg, PlayerManager.consumables.blueprints);
						break;
					case 65:
						appendOwnedItem(iconImg, PlayerManager.consumables.protoCatapult);
						break;
				}
			}
			totalDiv.parent().show();
			ownedDiv.parent().show();
		}

		buildMaterialTooltip(remodelInfo) {
			let title = $("
");
			// Ship icons from to
			let line = $("
");
			$("")
				.attr("src", KC3Meta.shipIcon(remodelInfo.ship_id_from))
				.width(18).height(18).css("vertical-align", "top")
				.appendTo(line);
			$("").attr("src", "../../assets/img/ui/arrow.png")
				.css("margin", "0px 10px 0px 10px")
				.appendTo(line);
			$("")
				.attr("src", KC3Meta.shipIcon(remodelInfo.ship_id_to))
				.width(18).height(18).css("vertical-align", "top")
				.appendTo(line);
			title.append(line);

			// Consumption of ammo and steel
			line = $("
");
			$("")
				.attr("src", "../../assets/img/client/ammo.png")
				.width(15).height(15).css("margin-right", 2)
				.css("vertical-align", "top")
				.appendTo(line);
			$("").css("margin-right", 10)
				.text(remodelInfo.ammo)
				.appendTo(line);
			$("")
				.attr("src", "../../assets/img/client/steel.png")
				.width(15).height(15).css("margin-right", 2)
				.css("vertical-align", "top")
				.appendTo(line);
			$("").css("margin-right", 2)
				.text(remodelInfo.steel)
				.appendTo(line);
			title.append(line);

			// Blueprints or catapults
			line = $("
");
			if(remodelInfo.blueprint) {
				$("")
					.attr("src", "../../assets/img/useitems/58.png")
					.width(15).height(15).css("margin-right", 2)
					.css("vertical-align", "top")
					.appendTo(line);
				$("").css("margin-right", 10)
					.text(remodelInfo.blueprint)
					.appendTo(line);
			}
			if(remodelInfo.catapult) {
				$("")
					.attr("src", "../../assets/img/useitems/65.png")
					.width(15).height(15).css("margin-right", 2)
					.css("vertical-align", "top")
					.appendTo(line);
				$("").css("margin-right", 2)
					.text(remodelInfo.catapult)
					.appendTo(line);
			}
			title.append(line);

			// Consumption of devmats or torch
			line = $("
");
			if(remodelInfo.devmat) {
				$("")
					.attr("src", "../../assets/img/client/devmat.png")
					.width(15).height(15).css("margin-right", 2)
					.css("vertical-align", "top")
					.appendTo(line);
				$("").css("margin-right", 10)
					.text(remodelInfo.devmat)
					.appendTo(line);
			}
			if(remodelInfo.torch) {
				$("")
					.attr("src", "../../assets/img/client/ibuild.png")
					.width(15).height(15).css("margin-right", 2)
					.css("vertical-align", "top")
					.appendTo(line);
				$("").css("margin-right", 2)
					.text(remodelInfo.torch)
					.appendTo(line);
			}
			title.append(line);

			return title.prop("outerHTML");
		}

	}

	KC3StrategyTabs.blueprints = new KC3StrategyTab("blueprints");
	KC3StrategyTabs.blueprints.definition = new KC3BlueprintsDefinition();

})();
<commit_msg>Update tooltip contexts: show names and level<commit_after>(function(){
	"use strict";

	class KC3BlueprintsDefinition extends KC3ShipListGrid {
		constructor() {
			super("blueprints");
		}

		/* INIT
		Prepares initial static data needed.
		---------------------------------*/
		init() {
			this.defaultSorterDefinitions();
			this.defineSimpleSorter("materials", "Consumptions",
				(ship) => -ship.materials.length);
			this.defineSimpleFilter("materials", [], 0, (index, ship) => ship.materials.length);
			this.showListRowCallback = this.showRemodelMaterials;
			this.heartLockMode = 2;
			this.viewType = "owned";
		}

		/* RELOAD
		Loads latest player or game data if needed.
		---------------------------------*/
		reload() {
			PlayerManager.loadConsumables();
			KC3ShipManager.load();
		}

		/* EXECUTE
		Places data onto the interface from scratch.
		---------------------------------*/
		execute() {
			$(".tab_blueprints .view_type input[type=radio][name=view_type]")
				.on("change", function() {
				const viewType = $("input[type=radio][name=view_type]:checked").val();
				KC3StrategyTabs.gotoTab(undefined, viewType);
			});
			this.shipListDiv = $(".tab_blueprints .ship_list");
			this.shipRowTemplateDiv = $(".tab_blueprints .factory .ship_item");
			this.registerShipListHeaderEvent(
				$(".tab_blueprints .ship_header .ship_field.hover")
			);
			this.shipListDiv.on("preShow", () => {
				$(".tab_blueprints .total").hide();
				$(".tab_blueprints .owned").hide();
			});
			this.shipListDiv.on("postShow", this.showTotalMaterials);
			this.loadView(KC3StrategyTabs.pageParams[1]);
		}

		loadView(viewType = "owned") {
			this.viewType = viewType;
			$(".tab_blueprints .view_type input[type=radio][name=view_type][value={0}]"
				.format(this.viewType)).prop("checked", true);
			switch(this.viewType) {
				case "owned":
					this.setSorter("lv");
					this.prepareShipList(true, this.mapRemodelMaterials);
					break;
				case "all":
					this.setSorter("type");
					this.prepareShipListFromRemodelDb();
					break;
				default:
					console.warn("Unsupported view type:", this.viewType);
					return;
			}
			this.showListGrid();
		}

		prepareShipListFromRemodelDb() {
			const allRemodelInfo = RemodelDb._db.remodelInfo;
			this.shipList.length = 0;
			Object.keys(allRemodelInfo).forEach(key => {
				const remodelInfo = allRemodelInfo[key];
				if(remodelInfo.blueprint || remodelInfo.catapult) {
					const shipMaster = KC3Master.ship(remodelInfo.ship_id_from);
					const shipData = {
						id: remodelInfo.ship_id_from,
						masterId: remodelInfo.ship_id_from,
						stype: shipMaster.api_stype,
						ctype: shipMaster.api_ctype,
						sortno: shipMaster.api_sortno,
						name: KC3Meta.shipName(shipMaster.api_name),
						level: remodelInfo.level,
						levelClass: "",
						locked: 1
					};
					const remodelFormIds = RemodelDb.remodelGroup(remodelInfo.ship_id_to);
					const ownedMasterId = KC3ShipManager.find(
						ship => remodelFormIds.indexOf(ship.masterId) >=
							remodelFormIds.indexOf(remodelInfo.ship_id_to)
					).length > 0 ? remodelInfo.ship_id_to : 0;
					this.attachRemodelMaterials(shipData, [shipData.masterId], ownedMasterId);
					this.shipList.push(shipData);
				}
			});
			return true;
		}

		mapRemodelMaterials(shipObj) {
			const mappedObj = this.defaultShipDataMapping(shipObj);
			this.attachRemodelMaterials(mappedObj,
				RemodelDb.remodelGroup(mappedObj.masterId));
			return mappedObj;
		}

		attachRemodelMaterials(mappedObj, remodelFormIds = [], ownedMasterId = 0) {
			const remodelGroup = RemodelDb.remodelGroup(mappedObj.masterId);
			mappedObj.materials = [];
			for(let masterId of remodelFormIds) {
				const remodelInfo = RemodelDb.remodelInfo(masterId);
				if(remodelInfo) {
					// Check and mark possibly used material
					const isUsed = remodelGroup.indexOf(ownedMasterId || mappedObj.masterId)
						>= remodelGroup.indexOf(remodelInfo.ship_id_to);
					// Current remodel info support these materials
					if(remodelInfo.blueprint) {
						mappedObj.materials.push({
							icon: 58,
							info: remodelInfo,
							used: isUsed
						});
					}
					if(remodelInfo.catapult) {
						mappedObj.materials.push({
							icon: 65,
							info: remodelInfo,
							used: isUsed
						});
					}
				}
			}
			return mappedObj;
		}

		showRemodelMaterials(ship, shipRow) {
			let firstMaterial = null;
			for(let material of ship.materials) {
				firstMaterial = firstMaterial || material;
				const iconDiv = $("
")
					.addClass("ship_field icon")
					.toggleClass("limited", this.viewType === "all");
				$("")
					.attr("src", "../../assets/img/useitems/" + material.icon + ".png")
					.appendTo(iconDiv);
				$("")
					.text(KC3Meta.useItemName(material.icon))
					.toggleClass("used", material.used).appendTo(iconDiv);
				iconDiv.attr("title", this.buildMaterialTooltip(material.info));
				$(".need_materials", shipRow).append(iconDiv);
			}
			if(this.viewType === "all" && firstMaterial) {
				const shipDiv = $("
")
					.addClass("ship_field icon")
					.toggleClass("limited", this.viewType === "all");
				$("").attr("src", "../../assets/img/ui/arrow.png")
					.appendTo(shipDiv);
				$("")
					.attr("src", KC3Meta.shipIcon(firstMaterial.info.ship_id_to))
					.attr("alt", firstMaterial.info.ship_id_to)
					.click(this.shipClickFunc)
					.addClass("hover")
					.appendTo(shipDiv);
				$("")
					.text(KC3Meta.shipName(
						KC3Master.ship(firstMaterial.info.ship_id_to).api_name
					)).appendTo(shipDiv);
				$(".need_materials", shipRow).append(shipDiv);
			}
		}

		showTotalMaterials(event, { shipList }) {
			const totalDiv = $(".tab_blueprints .total .total_items").empty();
			const ownedDiv = $(".tab_blueprints .owned .owned_items").empty();

			const totalItemDiv = $("
").addClass("summary_item").appendTo(totalDiv);
			$("")
				.attr("src", "../../assets/img/client/ship.png")
				.appendTo(totalItemDiv);
			$("")
				.text("x{0}".format(shipList.length))
				.appendTo(totalItemDiv);

			// Count total and used remodel materials
			const countMaterials = (resultMap = ({}), filter = (m => true)) => {
				[].concat(...shipList.map(ship => ship.materials
					.filter(filter).map(
					m => new Array(m.icon === 58 ? m.info.blueprint :
									m.icon === 65 ? m.info.catapult :
									1).fill(m.icon)
				))).map(icon => {
					resultMap[icon] = resultMap[icon] || 0;
					resultMap[icon] += 1;
				});
				return resultMap;
			};
			const materialCount = countMaterials();
			const usedCount = countMaterials({}, (m => m.used));

			// Show total results and owned materials
			const appendOwnedItem = (iconImg, count) => {
				const ownedItemDiv = $("
")
					.addClass("summary_item").appendTo(ownedDiv);
				iconImg.clone().appendTo(ownedItemDiv);
				$("")
					.text("x{0}".format(count || 0))
					.appendTo(ownedItemDiv);
			};
			for(let icon in materialCount) {
				const totalItemDiv = $("
").addClass("summary_item").appendTo(totalDiv);
				const iconImg = $("")
					.attr("src", "../../assets/img/useitems/" + icon + ".png")
					.appendTo(totalItemDiv);
				$("")
					.text("x{0}/{1}".format(
						materialCount[icon] - (usedCount[icon] || 0),
						materialCount[icon]
					)).appendTo(totalItemDiv);
				switch(Number(icon)) {
					case 58:
						appendOwnedItem(iconImg, PlayerManager.consumables.blueprints);
						break;
					case 65:
						appendOwnedItem(iconImg, PlayerManager.consumables.protoCatapult);
						break;
				}
			}
			totalDiv.parent().show();
			ownedDiv.parent().show();
		}

		buildMaterialTooltip(remodelInfo) {
			const title = $("
");
			// Ship icon and name from prev to next remodel
			let line = $("
");
			$("")
				.attr("src", KC3Meta.shipIcon(remodelInfo.ship_id_from))
				.width(18).height(18).css("margin-right", 2)
				.css("vertical-align", "bottom")
				.appendTo(line);
			$("").text(
				KC3Meta.shipName(KC3Master.ship(remodelInfo.ship_id_from).api_name)
			).appendTo(line);
			$("").attr("src", "../../assets/img/ui/arrow.png")
				.css("vertical-align", "text-top")
				.css("margin", "0px 5px 0px 5px")
				.appendTo(line);
			$("")
				.attr("src", KC3Meta.shipIcon(remodelInfo.ship_id_to))
				.width(18).height(18).css("margin-right", 2)
				.css("vertical-align", "bottom")
				.appendTo(line);
			$("").text(
				KC3Meta.shipName(KC3Master.ship(remodelInfo.ship_id_to).api_name)
			).appendTo(line);
			title.append(line);

			// Level and consumption of ammo and steel
			line = $("
");
			$("").css("margin-right", 10)
				.text("{0} {1}".format(KC3Meta.term("LevelShort"), remodelInfo.level))
				.appendTo(line);
			$("")
				.attr("src", "../../assets/img/client/ammo.png")
				.width(15).height(15).css("margin-right", 2)
				.css("vertical-align", "top")
				.appendTo(line);
			$("").css("margin-right", 10)
				.text(remodelInfo.ammo)
				.appendTo(line);
			$("")
				.attr("src", "../../assets/img/client/steel.png")
				.width(15).height(15).css("margin-right", 2)
				.css("vertical-align", "top")
				.appendTo(line);
			$("").css("margin-right", 2)
				.text(remodelInfo.steel)
				.appendTo(line);
			title.append(line);

			// Blueprints, catapults, devmats and torches
			line = $("
");
			if(remodelInfo.blueprint) {
				$("")
					.attr("src", "../../assets/img/useitems/58.png")
					.width(15).height(15).css("margin-right", 2)
					.css("vertical-align", "top")
					.appendTo(line);
				$("").css("margin-right", 10)
					.text(remodelInfo.blueprint)
					.appendTo(line);
			}
			if(remodelInfo.catapult) {
				$("")
					.attr("src", "../../assets/img/useitems/65.png")
					.width(15).height(15).css("margin-right", 2)
					.css("vertical-align", "top")
					.appendTo(line);
				$("").css("margin-right", 2)
					.text(remodelInfo.catapult)
					.appendTo(line);
			}
			if(remodelInfo.devmat) {
				$("")
					.attr("src", "../../assets/img/client/devmat.png")
					.width(15).height(15).css("margin-right", 2)
					.css("vertical-align", "top")
					.appendTo(line);
				$("").css("margin-right", 10)
					.text(remodelInfo.devmat)
					.appendTo(line);
			}
			if(remodelInfo.torch) {
				$("")
					.attr("src", "../../assets/img/client/ibuild.png")
					.width(15).height(15).css("margin-right", 2)
					.css("vertical-align", "top")
					.appendTo(line);
				$("").css("margin-right", 2)
					.text(remodelInfo.torch)
					.appendTo(line);
			}
			title.append(line);

			return title.prop("outerHTML");
		}

	}

	KC3StrategyTabs.blueprints = new KC3StrategyTab("blueprints");
	KC3StrategyTabs.blueprints.definition = new KC3BlueprintsDefinition();

})();
<|endoftext|>


<commit_before>(function() {
    "use strict";

    var fn = timbre.fn;

    function DistNode(_args) {
        timbre.Object.call(this, _args);
        fn.fixAR(this);

        var _ = this._;
        _.pre  = timbre(-60);
        _.post = timbre( 18);
        _.samplerate = timbre.samplerate;
        _.x1 = _.x2 = _.y1 = _.y2 = 0;
        _.b0 = _.b1 = _.b2 = _.a1 = _.a2 = 0;
        _.cutoff = 0;
    }
    fn.extend(DistNode);

    var $ = DistNode.prototype;

    Object.defineProperties($, {
        cutoff: {
            set: function(value) {
                if (typeof value === "number" && value > 0) {
                    this._.cutoff = value;
                }
            },
            get: function() {
                return this._.cutoff;
            }
        },
        pre: {
            set: function(value) {
                this._.pre = timbre(value);
            },
            get: function() {
                return this._.pre;
            }
        },
        post: {
            set: function(value) {
                this._.post = timbre(value);
            },
            get: function() {
                return this._.post;
            }
        }
    });

    $.process = function(tickID) {
        var _ = this._;
        var cell = this.cell;

        if (this.tickID !== tickID) {
            this.tickID = tickID;

            fn.inputSignalAR(this);

            var changed = false;

            var preGain = _.pre.process(tickID)[0];
            if (_.prevPreGain !== preGain) {
                _.prevPreGain = preGain;
                changed = true;
            }
            var postGain = _.post.process(tickID)[0];
            if (_.prevPostGain !== postGain) {
                _.prevPostGain = postGain;
                changed = true;
            }
            if (changed) {
                var postScale = Math.pow(2, -postGain * 0.166666666);
                _.preScale = Math.pow(2, -preGain * 0.166666666) * postScale;
                _.limit = postScale;
            }

            var preScale = _.preScale;
            var limit    = _.limit;
            var mul = _.mul, add = _.add;
            var i, imax;
            var x0, y0;

            if (_.cutoff) {
                if (_.prevCutoff !== _.cutoff) {
                    _.prevCutoff = _.cutoff;
                    lowpass_params(_);
                }

                var x1 = _.x1;
                var x2 = _.x2;
                var y1 = _.y1;
                var y2 = _.y2;

                var b0 = _.b0;
                var b1 = _.b1;
                var b2 = _.b2;
                var a1 = _.a1;
                var a2 = _.a2;

                for (i = 0, imax = cell.length; i < imax; ++i) {
                    x0 = cell[i] * preScale;
                    y0 = b0 * x0 + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2;

                    y0 = (y0 > limit) ? limit : (y0 < -limit) ? -limit : y0;

                    cell[i] = y0 * mul + add;

                    x2 = x1;
                    x1 = x0;
                    y2 = y1;
                    y1 = y0;
                }

                // flushDenormalFloatToZero
                if ((x1 > 0 && x1 <  1e-4) || (x1 < 0 && x1 > -1e-4)) {
                    x1 = 0;
                }
                if ((y1 > 0 && y1 <  1e-4) || (y1 < 0 && y1 > -1e-4)) {
                    y1 = 0;
                }

                _.x1 = x1;
                _.x2 = x2;
                _.y1 = y1;
                _.y2 = y2;
            } else {
                for (i = cell.length; i--; ) {
                    x0 = cell[i] * preScale;
                    x0 = (x0 > limit) ? limit : (x0 < -limit) ? -limit : x0;
                    cell[i] = x0 * mul + add;
                }
            }
        }

        return cell;
    };

    var lowpass_params = function(_) {
        var cutoff = _.cutoff / (_.samplerate * 0.5);

        if (cutoff >= 1) {
            _.b0 = 1;
            _.b1 = _.b2 = _.a1 = _.a2 = 0;
        } else if (cutoff <= 0) {
            _.b0 = _.b1 = _.b2 = _.a1 = _.a2 = 0;
        } else {
            var resonance = 1;
            var g = Math.pow(10.0, 0.05 * resonance);
            var d = Math.sqrt((4 - Math.sqrt(16 - 16 / (g * g))) * 0.5);

            var theta = Math.PI * cutoff;
            var sn = 0.5 * d * Math.sin(theta);
            var beta = 0.5 * (1 - sn) / (1 + sn);
            var gamma = (0.5 + beta) * Math.cos(theta);
            var alpha = 0.25 * (0.5 + beta - gamma);

            _.b0 = 2 * alpha;
            _.b1 = 4 * alpha;
            _.b2 = _.b0;
            _.a1 = 2 * -gamma;
            _.a2 = 2 * beta;
        }
    };

    fn.register("distortion", DistNode);
    fn.alias("dist", "distortion");

})();
<commit_msg>fix: gain value<commit_after>(function() {
    "use strict";

    var fn = timbre.fn;

    function DistNode(_args) {
        timbre.Object.call(this, _args);
        fn.fixAR(this);

        var _ = this._;
        _.pre  = timbre( 60);
        _.post = timbre(-18);
        _.samplerate = timbre.samplerate;
        _.x1 = _.x2 = _.y1 = _.y2 = 0;
        _.b0 = _.b1 = _.b2 = _.a1 = _.a2 = 0;
        _.cutoff = 0;
    }
    fn.extend(DistNode);

    var $ = DistNode.prototype;

    Object.defineProperties($, {
        cutoff: {
            set: function(value) {
                if (typeof value === "number" && value > 0) {
                    this._.cutoff = value;
                }
            },
            get: function() {
                return this._.cutoff;
            }
        },
        pre: {
            set: function(value) {
                this._.pre = timbre(value);
            },
            get: function() {
                return this._.pre;
            }
        },
        post: {
            set: function(value) {
                this._.post = timbre(value);
            },
            get: function() {
                return this._.post;
            }
        }
    });

    $.process = function(tickID) {
        var _ = this._;
        var cell = this.cell;

        if (this.tickID !== tickID) {
            this.tickID = tickID;

            fn.inputSignalAR(this);

            var changed = false;

            var preGain = -_.pre.process(tickID)[0];
            if (_.prevPreGain !== preGain) {
                _.prevPreGain = preGain;
                changed = true;
            }
            var postGain = -_.post.process(tickID)[0];
            if (_.prevPostGain !== postGain) {
                _.prevPostGain = postGain;
                changed = true;
            }
            if (changed) {
                var postScale = Math.pow(2, -postGain * 0.166666666);
                _.preScale = Math.pow(2, -preGain * 0.166666666) * postScale;
                _.limit = postScale;
            }

            var preScale = _.preScale;
            var limit    = _.limit;
            var mul = _.mul, add = _.add;
            var i, imax;
            var x0, y0;

            if (_.cutoff) {
                if (_.prevCutoff !== _.cutoff) {
                    _.prevCutoff = _.cutoff;
                    lowpass_params(_);
                }

                var x1 = _.x1;
                var x2 = _.x2;
                var y1 = _.y1;
                var y2 = _.y2;

                var b0 = _.b0;
                var b1 = _.b1;
                var b2 = _.b2;
                var a1 = _.a1;
                var a2 = _.a2;

                for (i = 0, imax = cell.length; i < imax; ++i) {
                    x0 = cell[i] * preScale;
                    y0 = b0 * x0 + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2;

                    y0 = (y0 > limit) ? limit : (y0 < -limit) ? -limit : y0;

                    cell[i] = y0 * mul + add;

                    x2 = x1;
                    x1 = x0;
                    y2 = y1;
                    y1 = y0;
                }

                // flushDenormalFloatToZero
                if ((x1 > 0 && x1 <  1e-4) || (x1 < 0 && x1 > -1e-4)) {
                    x1 = 0;
                }
                if ((y1 > 0 && y1 <  1e-4) || (y1 < 0 && y1 > -1e-4)) {
                    y1 = 0;
                }

                _.x1 = x1;
                _.x2 = x2;
                _.y1 = y1;
                _.y2 = y2;
            } else {
                for (i = cell.length; i--; ) {
                    x0 = cell[i] * preScale;
                    x0 = (x0 > limit) ? limit : (x0 < -limit) ? -limit : x0;
                    cell[i] = x0 * mul + add;
                }
            }
        }

        return cell;
    };

    var lowpass_params = function(_) {
        var cutoff = _.cutoff / (_.samplerate * 0.5);

        if (cutoff >= 1) {
            _.b0 = 1;
            _.b1 = _.b2 = _.a1 = _.a2 = 0;
        } else if (cutoff <= 0) {
            _.b0 = _.b1 = _.b2 = _.a1 = _.a2 = 0;
        } else {
            var resonance = 1;
            var g = Math.pow(10.0, 0.05 * resonance);
            var d = Math.sqrt((4 - Math.sqrt(16 - 16 / (g * g))) * 0.5);

            var theta = Math.PI * cutoff;
            var sn = 0.5 * d * Math.sin(theta);
            var beta = 0.5 * (1 - sn) / (1 + sn);
            var gamma = (0.5 + beta) * Math.cos(theta);
            var alpha = 0.25 * (0.5 + beta - gamma);

            _.b0 = 2 * alpha;
            _.b1 = 4 * alpha;
            _.b2 = _.b0;
            _.a1 = 2 * -gamma;
            _.a2 = 2 * beta;
        }
    };

    fn.register("distortion", DistNode);
    fn.alias("dist", "distortion");

})();
<|endoftext|>


<commit_before>var _ = require('lodash');
var stringify = require('json-stable-stringify');
var debug = require('debug')('iso19139');

var sha1 = require('../../../helpers/hash').sha1;

function hashRecordId(recordId) {
    return sha1(recordId);
}

function hashRecord(record) {
    return sha1(stringify(_.omit(record, '_updated')));
}

var ns = {
    gmd: 'http://www.isotc211.org/2005/gmd',
    srv: 'http://www.isotc211.org/2005/srv',
    gco: 'http://www.isotc211.org/2005/gco',
    xlink: 'http://www.w3.org/1999/xlink'
};

var definitions = {

    Main: {
        './/gmd:identificationInfo//gmd:citation//gmd:title': 'title',
        './/gmd:identificationInfo//gmd:abstract': 'abstract',
        './/gmd:fileIdentifier': 'fileIdentifier',
        './/gmd:identificationInfo//gmd:identifier': 'identifier',
        './/gmd:identificationInfo//gmd:language': 'language',
        './/gmd:dataQualityInfo//gmd:lineage//gmd:statement': 'lineage',
        './/gmd:hierarchyLevel/gmd:MD_ScopeCode/@codeListValue': 'type',
        './/gmd:identificationInfo//gmd:MD_SpatialRepresentationTypeCode/@codeListValue': 'representationType',
        './/gmd:dateStamp': '_updated',

        './/gmd:identificationInfo//gmd:citation//gmd:date': { dest: 'history', type: 'Date', multi: true },
        './/gmd:identificationInfo//gmd:keyword': { dest: 'keywords', multi: true },
        './/gmd:identificationInfo//gmd:topicCategory': { dest: 'topicCategories', multi: true },

        './/gmd:distributionInfo//gmd:transferOptions//gmd:onLine': { dest: 'onlineResources', type: 'Link', multi: true },
        './/gmd:contact': { dest: '_contacts', type: 'Contact', multi: true },
        './/gmd:identificationInfo//gmd:pointOfContact': { dest: 'contacts', type: 'Contact', multi: true },
        './/gmd:identificationInfo//gmd:graphicOverview': { dest: 'graphicOverviews', type: 'GraphicOverview', multi: true },

        // Service
        './/gmd:identificationInfo//srv:serviceType': 'serviceType',
        './/gmd:identificationInfo//srv:couplingType/*/@codeListValue': 'couplingType',
        './/gmd:identificationInfo//srv:coupledResource': { dest: 'coupledResources', type: 'CoupledResource', multi: true }
    },

    Link: {
        './/gmd:linkage': 'link',
        './/gmd:protocol': 'protocol',
        './/gmd:description': 'description',
        './/gmd:name': 'name'
    },

    Contact: {
        './/gmd:organisationName': 'organizationName',
        './/gmd:individualName': 'individualName',
        './/gmd:positionName': 'positionName',
        './/gmd:contactInfo//gmd:phone//gmd:voice': 'phone',
        './/gmd:contactInfo//gmd:phone//gmd:facsimile': 'fax',
        './/gmd:contactInfo//gmd:address//gmd:electronicMailAddress': 'email',
        './/gmd:contactInfo//gmd:address//gmd:deliveryPoint': 'deliveryPoint',
        './/gmd:contactInfo//gmd:address//gmd:city': 'city',
        './/gmd:contactInfo//gmd:address//gmd:postalCode': 'postalCode',
        './/gmd:contactInfo//gmd:address//gmd:country': 'country',
        './/gmd:role/gmd:CI_RoleCode/@codeListValue': 'role'
    },

    GraphicOverview: {
        './/gmd:fileName': 'fileName',
        './/gmd:fileDescription': 'fileDescription',
        './/gmd:fileType': 'fileType'
    },

    Date: {
        './/gmd:date': 'date',
        './/gmd:dateType/gmd:CI_DateTypeCode/@codeListValue': 'type'
    },

    CoupledResource: {
        './/srv:operationName': 'operationName',
        './/srv:identifier': 'identifier',
        './/gco:ScopedName': 'scopedName'
    }

};

/*
** Helpers
*/
var buildObject, buildArray, buildTextValue;

buildTextValue = function(node) {
    if (!node) return undefined;
    var value;
    if (node.type() === 'attribute') value = node.value();
    if (node.type() === 'element') value = node.text();
    if (!value || value.length === 0) return undefined;
    return value;
};

buildArray = function(nodes, type) {
    if (!nodes || nodes.length === 0) return undefined;
    var result = [];
    nodes.forEach(function(node) {
        var value = type ? buildObject(node, type) : buildTextValue(node);
        if (value) result.push(value);
    });
    return result.length ? result : undefined;
};

buildObject = function(node, type) {
    var result = {};
    _.forEach(definitions[type], function(params, xpath) {
        if (_.isString(params)) params = { dest: params };
        var value;
        if (params.multi) value = buildArray(node.find(xpath, ns), params.type);
        else if (params.type) value = buildObject(node.get(xpath, ns), params.type);
        else value = buildTextValue(node.get(xpath, ns));
        if (value) result[params.dest] = value;
    });
    return _.size(result) ? result : undefined;
};

function parseIso(xmlDoc, options) {
    options = options || {};

    var name = xmlDoc.name();
    var namespace = xmlDoc.namespace();

    if (name !== 'MD_Metadata' || namespace.href() !== ns.gmd) {
        debug('Unable to parse record (name: %s, namespace:%s: %s)', name, namespace.prefix(), namespace.href());
        return;
    }

    /*
    ** TODO
    ** Unique resource identifier ? identificationInfo/citation/identifier ! Attention code/codeSpace => merdique
    ** BBOX
    */

    var result = buildObject(xmlDoc, 'Main');
    if (result && options.keepXml) result._xml = xmlDoc;

    return result;
}

function parse(xmlElement) {
    var result = {};
    var parsedRecord = parseIso(xmlElement);
    var errors = [];
    // var warnings = [];

    function error(message) {
        errors.push({ message: message });
    }

    if (!parsedRecord.fileIdentifier) {
        error('no fileIdentifier found');
    } else {
        result.id = parsedRecord.fileIdentifier;

        if (parsedRecord.fileIdentifier.length > 256) {
            error('fileIdentifier too long (more than 256 characters)');
        } else {
            result.hashedId = hashRecordId(parsedRecord.fileIdentifier);
        }
    }

    if (!parsedRecord._updated) {
        error('no dateStamp found');
    } else {
        if (!_.isDate(new Date(parsedRecord._updated))) {
            error('dateStamp not valid');
        } else {
            result.updatedAt = new Date(parsedRecord._updated);
        }
    }

    result.parsedRecord = parsedRecord;
    result.hashedRecord = hashRecord(parsedRecord);
    result.validationErrors = errors;
    result.valid = errors.length === 0;

    return result;
}

exports.parse = parse;
exports.hashRecordId = hashRecordId;
exports.hashRecord = hashRecord;
<commit_msg>[md-parsers] Focus resources detection on CI_OnlineResource<commit_after>var _ = require('lodash');
var stringify = require('json-stable-stringify');
var debug = require('debug')('iso19139');

var sha1 = require('../../../helpers/hash').sha1;

function hashRecordId(recordId) {
    return sha1(recordId);
}

function hashRecord(record) {
    return sha1(stringify(_.omit(record, '_updated')));
}

var ns = {
    gmd: 'http://www.isotc211.org/2005/gmd',
    srv: 'http://www.isotc211.org/2005/srv',
    gco: 'http://www.isotc211.org/2005/gco',
    xlink: 'http://www.w3.org/1999/xlink'
};

var definitions = {

    Main: {
        './/gmd:identificationInfo//gmd:citation//gmd:title': 'title',
        './/gmd:identificationInfo//gmd:abstract': 'abstract',
        './/gmd:fileIdentifier': 'fileIdentifier',
        './/gmd:identificationInfo//gmd:identifier': 'identifier',
        './/gmd:identificationInfo//gmd:language': 'language',
        './/gmd:dataQualityInfo//gmd:lineage//gmd:statement': 'lineage',
        './/gmd:hierarchyLevel/gmd:MD_ScopeCode/@codeListValue': 'type',
        './/gmd:identificationInfo//gmd:MD_SpatialRepresentationTypeCode/@codeListValue': 'representationType',
        './/gmd:dateStamp': '_updated',

        './/gmd:identificationInfo//gmd:citation//gmd:date': { dest: 'history', type: 'Date', multi: true },
        './/gmd:identificationInfo//gmd:keyword': { dest: 'keywords', multi: true },
        './/gmd:identificationInfo//gmd:topicCategory': { dest: 'topicCategories', multi: true },

        './/gmd:distributionInfo//gmd:transferOptions//gmd:CI_OnlineResource': { dest: 'onlineResources', type: 'Link', multi: true },
        './/gmd:contact': { dest: '_contacts', type: 'Contact', multi: true },
        './/gmd:identificationInfo//gmd:pointOfContact': { dest: 'contacts', type: 'Contact', multi: true },
        './/gmd:identificationInfo//gmd:graphicOverview': { dest: 'graphicOverviews', type: 'GraphicOverview', multi: true },

        // Service
        './/gmd:identificationInfo//srv:serviceType': 'serviceType',
        './/gmd:identificationInfo//srv:couplingType/*/@codeListValue': 'couplingType',
        './/gmd:identificationInfo//srv:coupledResource': { dest: 'coupledResources', type: 'CoupledResource', multi: true }
    },

    Link: {
        './/gmd:linkage': 'link',
        './/gmd:protocol': 'protocol',
        './/gmd:description': 'description',
        './/gmd:name': 'name'
    },

    Contact: {
        './/gmd:organisationName': 'organizationName',
        './/gmd:individualName': 'individualName',
        './/gmd:positionName': 'positionName',
        './/gmd:contactInfo//gmd:phone//gmd:voice': 'phone',
        './/gmd:contactInfo//gmd:phone//gmd:facsimile': 'fax',
        './/gmd:contactInfo//gmd:address//gmd:electronicMailAddress': 'email',
        './/gmd:contactInfo//gmd:address//gmd:deliveryPoint': 'deliveryPoint',
        './/gmd:contactInfo//gmd:address//gmd:city': 'city',
        './/gmd:contactInfo//gmd:address//gmd:postalCode': 'postalCode',
        './/gmd:contactInfo//gmd:address//gmd:country': 'country',
        './/gmd:role/gmd:CI_RoleCode/@codeListValue': 'role'
    },

    GraphicOverview: {
        './/gmd:fileName': 'fileName',
        './/gmd:fileDescription': 'fileDescription',
        './/gmd:fileType': 'fileType'
    },

    Date: {
        './/gmd:date': 'date',
        './/gmd:dateType/gmd:CI_DateTypeCode/@codeListValue': 'type'
    },

    CoupledResource: {
        './/srv:operationName': 'operationName',
        './/srv:identifier': 'identifier',
        './/gco:ScopedName': 'scopedName'
    }

};

/*
** Helpers
*/
var buildObject, buildArray, buildTextValue;

buildTextValue = function(node) {
    if (!node) return undefined;
    var value;
    if (node.type() === 'attribute') value = node.value();
    if (node.type() === 'element') value = node.text();
    if (!value || value.length === 0) return undefined;
    return value;
};

buildArray = function(nodes, type) {
    if (!nodes || nodes.length === 0) return undefined;
    var result = [];
    nodes.forEach(function(node) {
        var value = type ? buildObject(node, type) : buildTextValue(node);
        if (value) result.push(value);
    });
    return result.length ? result : undefined;
};

buildObject = function(node, type) {
    var result = {};
    _.forEach(definitions[type], function(params, xpath) {
        if (_.isString(params)) params = { dest: params };
        var value;
        if (params.multi) value = buildArray(node.find(xpath, ns), params.type);
        else if (params.type) value = buildObject(node.get(xpath, ns), params.type);
        else value = buildTextValue(node.get(xpath, ns));
        if (value) result[params.dest] = value;
    });
    return _.size(result) ? result : undefined;
};

function parseIso(xmlDoc, options) {
    options = options || {};

    var name = xmlDoc.name();
    var namespace = xmlDoc.namespace();

    if (name !== 'MD_Metadata' || namespace.href() !== ns.gmd) {
        debug('Unable to parse record (name: %s, namespace:%s: %s)', name, namespace.prefix(), namespace.href());
        return;
    }

    /*
    ** TODO
    ** Unique resource identifier ? identificationInfo/citation/identifier ! Attention code/codeSpace => merdique
    ** BBOX
    */

    var result = buildObject(xmlDoc, 'Main');
    if (result && options.keepXml) result._xml = xmlDoc;

    return result;
}

function parse(xmlElement) {
    var result = {};
    var parsedRecord = parseIso(xmlElement);
    var errors = [];
    // var warnings = [];

    function error(message) {
        errors.push({ message: message });
    }

    if (!parsedRecord.fileIdentifier) {
        error('no fileIdentifier found');
    } else {
        result.id = parsedRecord.fileIdentifier;

        if (parsedRecord.fileIdentifier.length > 256) {
            error('fileIdentifier too long (more than 256 characters)');
        } else {
            result.hashedId = hashRecordId(parsedRecord.fileIdentifier);
        }
    }

    if (!parsedRecord._updated) {
        error('no dateStamp found');
    } else {
        if (!_.isDate(new Date(parsedRecord._updated))) {
            error('dateStamp not valid');
        } else {
            result.updatedAt = new Date(parsedRecord._updated);
        }
    }

    result.parsedRecord = parsedRecord;
    result.hashedRecord = hashRecord(parsedRecord);
    result.validationErrors = errors;
    result.valid = errors.length === 0;

    return result;
}

exports.parse = parse;
exports.hashRecordId = hashRecordId;
exports.hashRecord = hashRecord;
<|endoftext|>


<commit_before>/*
* Copyright 2012 Research In Motion Limited.
*
* 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.
*/

(function($) {

	$.widget("mobile.actionbar", $.mobile.widget, {

		options: {
			initSelector: ":jqmData(role='actionbar')",
			backButtonText: $.mobile.page.prototype.options.backBtnText,
			disableTapToggle: true
		},

		_init: function() {
		},

		_create: function() {
			this.actionBarArea = $( this.element );
			this.showActionOverflow = this.showTabOverflow = false;

			var overflow,
				item, isItemTab,
				self = this,
				o = self.options,
				bar = $( document.createElement( 'div' ) ),
				actions = $( document.createElement( 'div' ) ),
				itemList = this.actionBarArea.children( ":jqmData(role='action'), :jqmData(role='tab')" ),
				actionList = itemList.filter( ":jqmData(role='action')" ),
				tabList = itemList.filter( ":jqmData(role='tab')" ),
				back = this.actionBarArea.children( ":jqmData(role='back')").first(),

				maxTabs = (actionList.length > 0 || tabList.length > 4) ? 3 : 4,
				maxActions = ( tabList.length > 0 ) ? ((actionList.length > 1) ? 0 : 1 ): 3;

			$("[data-role=footer]").fixedtoolbar({ tapToggle: !o.disableTapToggle });

			this.actionBarArea.addClass('action-bar-area');
			bar.addClass('action-bar');
			actions.addClass('action-bar-actions');

			//If we have tabs we can not have a back button
			if (back.length && !tabList.length) {
				this._createBackButton(back, bar);
			} else {
				back.remove();
				actions.addClass('action-bar-actions-full-width');
			}

			if (!itemList || itemList.length < 1) {
				var emptyItem = $(document.createElement('div'));
				emptyItem.addClass('action-bar-action-item');
				actions.append(emptyItem);
			}

			var overflowNeeded = tabList.length > maxTabs;
			for (var i = 0; i < tabList.length; i++) {
				item = tabList.eq(i);
				//add to tab overflow
				if(overflowNeeded || item.data("overflow")) {
					var clone = item.clone();
					this._addToTabOverflow(clone);

					if (i > maxTabs - 1 || item.data("overflow")) {
						item.remove();
						continue;
					} else {
						if(cloneId = clone.attr("id")) {
							clone.attr('data-for', cloneId).attr('id',"");
						}
					}
				}
				//Create Tab item
				actions.append(this._createTabItem(item));
			}

			for (i = 0; i < actionList.length; i++) {
				item = actionList.eq(i);
				if (i > maxActions - 1 || item.data("overflow")) {
					//add to action overflow
					this._addToActionOverflow(item);
					continue;
				}
				//Create action item
				actions.append(this._createActionItem(item));
			}

			if( this.showActionOverflow ) {
				this.overflowActionMenu.find('.menuItem').bind('vclick', {context: self}, this._hideActionOverflow);

				this.overflowActionMenu.bind('vclick', function(event){
					return false;
				});
				this._createOverflowButton(this.overflowActionMenu)
					.addClass("actions")
					.appendTo(actions)
					.bind('vclick', function(){
						self.overflowActionMenu.addClass("showMenu");

						setTimeout(function() {
							$(document).bind('vclick', {context: self}, self._hideActionOverflow);
						}, 0);
					});
			}

			if( this.showTabOverflow ) {
				this.overflowTabMenu.find(".menuItem").bind('vclick',function () {
					$('.ui-page-active, .ui-footer, .ui-header').removeClass('showTabOverflow');
					$(this).find('img').clone().appendTo($('.tabs').first());
					$('

' + $(this).text() + '

').appendTo($('.tabs').first());
					$('.tabs').first().css('background-position-x', '-50%');

					$(".action-bar-tab-item:not(.action-bar-overflow)").one('vclick', function() {
						$('.tabs').first().css('background-position-x', '50%');
						$('.tabs').first().find('img').remove();
						$('.tabs').first().find('.action-bar-action-item-text').remove();

					});
				});
				this.overflowTabMenu.bind('vclick', function() {
					return false;
				});
				this._createOverflowButton(this.overflowTabMenu)
					.addClass("tabs")
					.addClass("action-bar-tab-item")
					.prependTo(actions)
					.bind('vclick', function(event) {
						$('.ui-page-active, .ui-footer-fixed, .ui-header-fixed')
							.addClass('showTabHelper')
							.addClass('showTabOverflow');
						event.stopPropagation();
						setTimeout(function() {
							$(document).one('vclick', function () {
								$('.ui-page-active, .ui-footer-fixed, .ui-header-fixed')
									.removeClass('showTabOverflow')
									.one("webkitTransitionEnd",function() {
										$(this).removeClass('showTabHelper');
									});

							});
						}, 0);
					});
			}

			bar.append(actions);

			this.actionBarArea.append(bar);

			var itemsLen, actionBarItems;

			if (tabList.length > 0) {
				actionBarItems = this.actionBarArea.find(".action-bar-tab-item").not(".tabs");
				itemsize = "action-bar-grid-" + ( actionList.length > 0 ? "tabAction" : "tabs");
			} else {
				actionBarItems = this.actionBarArea.find(".action-bar-action-item");
				itemsize = "action-bar-grid-actions";
			}

			itemsLen = actionBarItems.length;
			itemsize +=  "-" + ( ( itemsLen > 5 ) ? "e" : String.fromCharCode( 96 + itemsLen ) );
			actionBarItems.addClass(itemsize);

			$( '.action-bar-action-item' )
				.bind( 'vmousedown', function( event ) {
					$(event.delegateTarget).addClass( 'pressed' );
				})
				.bind ('vmouseup', function(event) {
					$(event.delegateTarget).removeClass( 'pressed' );
				});

			$( document )
				.bind( 'actionbarIn', function() {
					self._animateIn( back, actions );
				})
				.bind( 'actionbarOut', function() {
					self._animateOut( back, actions );
				});

			$("[data-for]").bind("vclick", function(event) {
				$("#"+$(this).attr("data-for")).trigger(event.type);
				event.stopImmediatePropagation();
			});
		},

		refresh: function() {
		},

		_createOverFlowItem: function(item) {
			item.addClass('menuItem light-text-fade');
			var content = item.children("p").first().html();
			item.children("p").remove();
			item.append(content);
			return item;
		},

		_createActionItem: function(item) {
			item = this._createBarItem(item);
			return item;
		},

		_createTabItem: function(item) {
			item = this._createBarItem(item);
			item.addClass("action-bar-tab-item");
			return item;
		},

		_createBarItem: function(item) {
			var label = item.find('p').first(),
				itemImage = item.find('img').first()
					.addClass('action-bar-action-item-image')
					.appendTo(item);

			item.addClass('action-bar-action-item');

			if (label) {
				var actionItemText = $(document.createElement('div'))
						.addClass('action-bar-action-item-text')
						.html(label)
						.appendTo(item);
			}

			return item;
		},

		_hideActionOverflow: function (event) {
			var self = event.data.context;
			self.overflowActionMenu.removeClass("showMenu");
			$(document).unbind('vclick', self._hideActionOverflow);
		},

		_addToTabOverflow: function(item) {
			if (!this.overflowTabMenu){
				this.overflowTabMenu = this._createOverflowMenu(this.actionBarArea, true);
				this.showTabOverflow = true;
			}

			this._addToOverflow(item, this.overflowTabMenu);
		},

		_addToActionOverflow: function(item) {
			if (!this.overflowActionMenu){
				this.overflowActionMenu = this._createOverflowMenu(this.actionBarArea, false);
				this.showActionOverflow = true;
			}
			this._addToOverflow(item, this.overflowActionMenu);
		},

		_addToOverflow: function (item, menu) {
			if ( !menu ) {
				//init tab overflow
				this.showTabOverflow = true;
			}
			item = this._createOverFlowItem(item);
			item.appendTo(menu.children(".overflowMenuContent").first());
		},

		_createBackButton: function(back, appendto) {
			var backText = $(document.createElement('div'));

			backText
				.addClass('action-bar-back-text')
				.html("
" + this.options.backButtonText + "
");

			back.addClass( 'action-bar-back' )
				.append(backText)
				.bind( 'vmousedown', function(event) {
					$(event.delegateTarget).addClass('pressed');
					window.history.back();
					return false;
				})
				.bind( 'vmouseup', function(event) {
					$(event.delegateTarget).removeClass('pressed');
				})
				.appendTo(appendto);
		},

		_createOverflowMenu: function(element, isLeft) {
			var overflowMenu = $(document.createElement('div'))
					.addClass("overflowMenu" + ( isLeft ? " left" : "" ) ),
				overflowMenuContent = $(document.createElement('div'))
					.addClass("overflowMenuContent")
					.appendTo(overflowMenu);

			if(isLeft) {
				element.closest( '.ui-page' ).first().before(overflowMenu);
			} else {
				element.closest( '.ui-page' ).first().children( ".ui-content" ).append( overflowMenu );
			}
			return overflowMenu;
		},

		_createOverflowButton: function(menu) {
			return $(document.createElement('div'))
				.addClass('action-bar-overflow');
		},

		_animateIn: function(back, actions) {
			if (back) {
				back.removeClass('action-bar-back-offset-right action-bar-back-offset-left');
			}
			actions.removeClass('action-bar-actions-offset-right action-bar-actions-offset-left');
		},

		_animateOut: function(back, actions, bar, callback) {
			if (back) {
				back.addClass('action-bar-back-offset-right');
			}
			actions.addClass('action-bar-actions-offset-right');
			if (callback) {
				actions.on('webkitTransitionEnd', function caller() {actions.off('webkitTransitionEnd', caller); callback(); });
			}
		},

		_animateBelow: function(back, actions) {
			if (back) {
				back.addClass('action-bar-back-offset-left');
			}
			actions.addClass('action-bar-actions-offset-left');
		}
	});
	$( document ).bind( "pagecreate create", function( e ){
		$.mobile.actionbar.prototype.enhanceWithin( e.target );
	});
})(jQuery);
<commit_msg>ActionBar: Moving the overflow menu out of content<commit_after>/*
* Copyright 2012 Research In Motion Limited.
*
* 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.
*/

(function($) {

	$.widget("mobile.actionbar", $.mobile.widget, {

		options: {
			initSelector: ":jqmData(role='actionbar')",
			backButtonText: $.mobile.page.prototype.options.backBtnText,
			disableTapToggle: true
		},

		_init: function() {
		},

		_create: function() {
			this.actionBarArea = $( this.element );
			this.showActionOverflow = this.showTabOverflow = false;

			var overflow,
				item, isItemTab,
				self = this,
				o = self.options,
				bar = $( document.createElement( 'div' ) ),
				actions = $( document.createElement( 'div' ) ),
				itemList = this.actionBarArea.children( ":jqmData(role='action'), :jqmData(role='tab')" ),
				actionList = itemList.filter( ":jqmData(role='action')" ),
				tabList = itemList.filter( ":jqmData(role='tab')" ),
				back = this.actionBarArea.children( ":jqmData(role='back')").first(),

				maxTabs = (actionList.length > 0 || tabList.length > 4) ? 3 : 4,
				maxActions = ( tabList.length > 0 ) ? ((actionList.length > 1) ? 0 : 1 ): 3;

			$("[data-role=footer]").fixedtoolbar({ tapToggle: !o.disableTapToggle });

			this.actionBarArea.addClass('action-bar-area');
			bar.addClass('action-bar');
			actions.addClass('action-bar-actions');

			//If we have tabs we can not have a back button
			if (back.length && !tabList.length) {
				this._createBackButton(back, bar);
			} else {
				back.remove();
				actions.addClass('action-bar-actions-full-width');
			}

			if (!itemList || itemList.length < 1) {
				var emptyItem = $(document.createElement('div'));
				emptyItem.addClass('action-bar-action-item');
				actions.append(emptyItem);
			}

			var overflowNeeded = tabList.length > maxTabs;
			for (var i = 0; i < tabList.length; i++) {
				item = tabList.eq(i);
				//add to tab overflow
				if(overflowNeeded || item.data("overflow")) {
					var clone = item.clone();
					this._addToTabOverflow(clone);

					if (i > maxTabs - 1 || item.data("overflow")) {
						item.remove();
						continue;
					} else {
						if(cloneId = clone.attr("id")) {
							clone.attr('data-for', cloneId).attr('id',"");
						}
					}
				}
				//Create Tab item
				actions.append(this._createTabItem(item));
			}

			for (i = 0; i < actionList.length; i++) {
				item = actionList.eq(i);
				if (i > maxActions - 1 || item.data("overflow")) {
					//add to action overflow
					this._addToActionOverflow(item);
					continue;
				}
				//Create action item
				actions.append(this._createActionItem(item));
			}

			if( this.showActionOverflow ) {
				this.overflowActionMenu.find('.menuItem').bind('vclick', {context: self}, this._hideActionOverflow);

				this.overflowActionMenu.bind('vclick', function(event){
					return false;
				});
				this._createOverflowButton(this.overflowActionMenu)
					.addClass("actions")
					.appendTo(actions)
					.bind('vclick', function(){
						self.overflowActionMenu.addClass("showMenu");

						setTimeout(function() {
							$(document).bind('vclick', {context: self}, self._hideActionOverflow);
						}, 0);
					});
			}

			if( this.showTabOverflow ) {
				this.overflowTabMenu.find(".menuItem").bind('vclick',function () {
					$('.ui-page-active, .ui-footer, .ui-header').removeClass('showTabOverflow');
					$(this).find('img').clone().appendTo($('.tabs').first());
					$('

' + $(this).text() + '

').appendTo($('.tabs').first());
					$('.tabs').first().css('background-position-x', '-50%');

					$(".action-bar-tab-item:not(.action-bar-overflow)").one('vclick', function() {
						$('.tabs').first().css('background-position-x', '50%');
						$('.tabs').first().find('img').remove();
						$('.tabs').first().find('.action-bar-action-item-text').remove();

					});
				});
				this.overflowTabMenu.bind('vclick', function() {
					return false;
				});
				this._createOverflowButton(this.overflowTabMenu)
					.addClass("tabs")
					.addClass("action-bar-tab-item")
					.prependTo(actions)
					.bind('vclick', function(event) {
						$('.ui-page-active, .ui-footer-fixed, .ui-header-fixed')
							.addClass('showTabHelper')
							.addClass('showTabOverflow');
						event.stopPropagation();
						setTimeout(function() {
							$(document).one('vclick', function () {
								$('.ui-page-active, .ui-footer-fixed, .ui-header-fixed')
									.removeClass('showTabOverflow')
									.one("webkitTransitionEnd",function() {
										$(this).removeClass('showTabHelper');
									});

							});
						}, 0);
					});
			}

			bar.append(actions);

			this.actionBarArea.append(bar);

			var itemsLen, actionBarItems;

			if (tabList.length > 0) {
				actionBarItems = this.actionBarArea.find(".action-bar-tab-item").not(".tabs");
				itemsize = "action-bar-grid-" + ( actionList.length > 0 ? "tabAction" : "tabs");
			} else {
				actionBarItems = this.actionBarArea.find(".action-bar-action-item");
				itemsize = "action-bar-grid-actions";
			}

			itemsLen = actionBarItems.length;
			itemsize +=  "-" + ( ( itemsLen > 5 ) ? "e" : String.fromCharCode( 96 + itemsLen ) );
			actionBarItems.addClass(itemsize);

			$( '.action-bar-action-item' )
				.bind( 'vmousedown', function( event ) {
					$(event.delegateTarget).addClass( 'pressed' );
				})
				.bind ('vmouseup', function(event) {
					$(event.delegateTarget).removeClass( 'pressed' );
				});

			$( document )
				.bind( 'actionbarIn', function() {
					self._animateIn( back, actions );
				})
				.bind( 'actionbarOut', function() {
					self._animateOut( back, actions );
				});

			$("[data-for]").bind("vclick", function(event) {
				$("#"+$(this).attr("data-for")).trigger(event.type);
				event.stopImmediatePropagation();
			});
		},

		refresh: function() {
		},

		destroy: function() {
			$(this.overflowActionMenu).remove();
			$(this.overflowTabMenu).remove();
		},

		_createOverFlowItem: function(item) {
			item.addClass('menuItem light-text-fade');
			var content = item.children("p").first().html();
			item.children("p").remove();
			item.append(content);
			return item;
		},

		_createActionItem: function(item) {
			item = this._createBarItem(item);
			return item;
		},

		_createTabItem: function(item) {
			item = this._createBarItem(item);
			item.addClass("action-bar-tab-item");
			return item;
		},

		_createBarItem: function(item) {
			var label = item.find('p').first(),
				itemImage = item.find('img').first()
					.addClass('action-bar-action-item-image')
					.appendTo(item);

			item.addClass('action-bar-action-item');

			if (label) {
				var actionItemText = $(document.createElement('div'))
						.addClass('action-bar-action-item-text')
						.html(label)
						.appendTo(item);
			}

			return item;
		},

		_hideActionOverflow: function (event) {
			var self = event.data.context;
			self.overflowActionMenu.removeClass("showMenu");
			$(document).unbind('vclick', self._hideActionOverflow);
		},

		_addToTabOverflow: function(item) {
			if (!this.overflowTabMenu){
				this.overflowTabMenu = this._createOverflowMenu(this.actionBarArea, true);
				this.showTabOverflow = true;
			}

			this._addToOverflow(item, this.overflowTabMenu);
		},

		_addToActionOverflow: function(item) {
			if (!this.overflowActionMenu){
				this.overflowActionMenu = this._createOverflowMenu(this.actionBarArea, false);
				this.showActionOverflow = true;
			}
			this._addToOverflow(item, this.overflowActionMenu);
		},

		_addToOverflow: function (item, menu) {
			if ( !menu ) {
				//init tab overflow
				this.showTabOverflow = true;
			}
			item = this._createOverFlowItem(item);
			item.appendTo(menu.children(".overflowMenuContent").first());
		},

		_createBackButton: function(back, appendto) {
			var backText = $(document.createElement('div'));

			backText
				.addClass('action-bar-back-text')
				.html("
" + this.options.backButtonText + "
");

			back.addClass( 'action-bar-back' )
				.append(backText)
				.bind( 'vmousedown', function(event) {
					$(event.delegateTarget).addClass('pressed');
					window.history.back();
					return false;
				})
				.bind( 'vmouseup', function(event) {
					$(event.delegateTarget).removeClass('pressed');
				})
				.appendTo(appendto);
		},

		_createOverflowMenu: function(element, isLeft) {
			var overflowMenu = $(document.createElement('div'))
					.addClass("overflowMenu" + ( isLeft ? " left" : "" ) ),
				overflowMenuContent = $(document.createElement('div'))
					.addClass("overflowMenuContent")
					.appendTo(overflowMenu);
			if(isLeft) {
				element.closest( '.ui-page' ).first().before(overflowMenu);
			} else {
				element.closest( '.ui-page' ).first().append(overflowMenu);
			}
			return overflowMenu;
		},

		_createOverflowButton: function(menu) {
			return $(document.createElement('div'))
				.addClass('action-bar-overflow');
		},

		_animateIn: function(back, actions) {
			if (back) {
				back.removeClass('action-bar-back-offset-right action-bar-back-offset-left');
			}
			actions.removeClass('action-bar-actions-offset-right action-bar-actions-offset-left');
		},

		_animateOut: function(back, actions, bar, callback) {
			if (back) {
				back.addClass('action-bar-back-offset-right');
			}
			actions.addClass('action-bar-actions-offset-right');
			if (callback) {
				actions.on('webkitTransitionEnd', function caller() {actions.off('webkitTransitionEnd', caller); callback(); });
			}
		},

		_animateBelow: function(back, actions) {
			if (back) {
				back.addClass('action-bar-back-offset-left');
			}
			actions.addClass('action-bar-actions-offset-left');
		}
	});
	$( document ).bind( "pagecreate create", function( e ){
		$.mobile.actionbar.prototype.enhanceWithin( e.target );
	});
})(jQuery);
<|endoftext|>


<commit_before>const { KafkaJSNonRetriableError } = require('../../../errors')

const toNodeCompatible = crypto => ({
  randomBytes: size => crypto.getRandomValues(Buffer.allocUnsafe(size)),
})

let cryptoImplementation = null
if (global && global.crypto) {
  cryptoImplementation = toNodeCompatible(global.crypto)
} else if (global && global.msCrypto) {
  cryptoImplementation = toNodeCompatible(global.msCrypto)
} else if (global && !global.crypto) {
  cryptoImplementation = require('crypto')
}

const MAX_BYTES = 65536

module.exports = size => {
  if (size > MAX_BYTES) {
    throw new KafkaJSNonRetriableError(
      `Byte length (${size}) exceeds the max number of bytes of entropy available (${MAX_BYTES})`
    )
  }

  if (!cryptoImplementation) {
    throw new KafkaJSNonRetriableError('No available crypto implementation')
  }

  return cryptoImplementation.randomBytes(size)
}
<commit_msg>make NodeJS REPL get correct randomBytes()<commit_after>const { KafkaJSNonRetriableError } = require('../../../errors')

const toNodeCompatible = crypto => ({
  randomBytes: size => crypto.getRandomValues(Buffer.allocUnsafe(size)),
})

let cryptoImplementation = null
if (global && global.crypto) {
  cryptoImplementation =
    global.crypto.randomBytes === undefined ? toNodeCompatible(global.crypto) : global.crypto
} else if (global && global.msCrypto) {
  cryptoImplementation = toNodeCompatible(global.msCrypto)
} else if (global && !global.crypto) {
  cryptoImplementation = require('crypto')
}

const MAX_BYTES = 65536

module.exports = size => {
  if (size > MAX_BYTES) {
    throw new KafkaJSNonRetriableError(
      `Byte length (${size}) exceeds the max number of bytes of entropy available (${MAX_BYTES})`
    )
  }

  if (!cryptoImplementation) {
    throw new KafkaJSNonRetriableError('No available crypto implementation')
  }

  return cryptoImplementation.randomBytes(size)
}
<|endoftext|>


<commit_before>/**
 * @module ol/source/DataTile
 */
import DataTile from '../DataTile.js';
import EventType from '../events/EventType.js';
import ReprojDataTile from '../reproj/DataTile.js';
import TileCache from '../TileCache.js';
import TileEventType from './TileEventType.js';
import TileSource, {TileSourceEvent} from './Tile.js';
import TileState from '../TileState.js';
import {
  createXYZ,
  extentFromProjection,
  getForProjection as getTileGridForProjection,
} from '../tilegrid.js';
import {equivalent, get as getProjection} from '../proj.js';
import {getKeyZXY} from '../tilecoord.js';
import {getUid} from '../util.js';
import {toPromise} from '../functions.js';
import {toSize} from '../size.js';

/**
 * Data tile loading function.  The function is called with z, x, and y tile coordinates and
 * returns {@link import("../DataTile.js").Data data} for a tile or a promise for the same.
 * @typedef {function(number, number, number) : (import("../DataTile.js").Data|Promise<import("../DataTile.js").Data>)} Loader
 */

/**
 * @typedef {Object} Options
 * @property {Loader} [loader] Data loader.  Called with z, x, and y tile coordinates.
 * Returns {@link import("../DataTile.js").Data data} for a tile or a promise for the same.
 * @property {import("./Source.js").AttributionLike} [attributions] Attributions.
 * @property {boolean} [attributionsCollapsible=true] Attributions are collapsible.
 * @property {number} [maxZoom=42] Optional max zoom level. Not used if `tileGrid` is provided.
 * @property {number} [minZoom=0] Optional min zoom level. Not used if `tileGrid` is provided.
 * @property {number|import("../size.js").Size} [tileSize=[256, 256]] The pixel width and height of the source tiles.
 * This may be different than the rendered pixel size if a `tileGrid` is provided.
 * @property {number} [gutter=0] The size in pixels of the gutter around data tiles to ignore.
 * This allows artifacts of rendering at tile edges to be ignored.
 * Supported data should be wider and taller than the tile size by a value of `2 x gutter`.
 * @property {number} [maxResolution] Optional tile grid resolution at level zero. Not used if `tileGrid` is provided.
 * @property {import("../proj.js").ProjectionLike} [projection='EPSG:3857'] Tile projection.
 * @property {import("../tilegrid/TileGrid.js").default} [tileGrid] Tile grid.
 * @property {boolean} [opaque=false] Whether the layer is opaque.
 * @property {import("./Source.js").State} [state] The source state.
 * @property {boolean} [wrapX=false] Render tiles beyond the antimeridian.
 * @property {number} [transition] Transition time when fading in new tiles (in miliseconds).
 * @property {number} [bandCount=4] Number of bands represented in the data.
 * @property {boolean} [interpolate=false] Use interpolated values when resampling.  By default,
 * the nearest neighbor is used when resampling.
 */

/**
 * @classdesc
 * A source for typed array data tiles.
 *
 * @fires import("./Tile.js").TileSourceEvent
 * @api
 */
class DataTileSource extends TileSource {
  /**
   * @param {Options} options DataTile source options.
   */
  constructor(options) {
    const projection =
      options.projection === undefined ? 'EPSG:3857' : options.projection;

    let tileGrid = options.tileGrid;
    if (tileGrid === undefined && projection) {
      tileGrid = createXYZ({
        extent: extentFromProjection(projection),
        maxResolution: options.maxResolution,
        maxZoom: options.maxZoom,
        minZoom: options.minZoom,
        tileSize: options.tileSize,
      });
    }

    super({
      cacheSize: 0.1, // don't cache on the source
      attributions: options.attributions,
      attributionsCollapsible: options.attributionsCollapsible,
      projection: projection,
      tileGrid: tileGrid,
      opaque: options.opaque,
      state: options.state,
      wrapX: options.wrapX,
      transition: options.transition,
      interpolate: options.interpolate,
    });

    /**
     * @private
     * @type {number}
     */
    this.gutter_ = options.gutter !== undefined ? options.gutter : 0;

    /**
     * @private
     * @type {import('../size.js').Size|null}
     */
    this.tileSize_ = options.tileSize ? toSize(options.tileSize) : null;

    /**
     * @private
     * @type {Array<import('../size.js').Size>|null}
     */
    this.tileSizes_ = null;

    /**
     * @private
     * @type {!Object<string, boolean>}
     */
    this.tileLoadingKeys_ = {};

    /**
     * @private
     */
    this.loader_ = options.loader;

    this.handleTileChange_ = this.handleTileChange_.bind(this);

    /**
     * @type {number}
     */
    this.bandCount = options.bandCount === undefined ? 4 : options.bandCount; // assume RGBA if undefined

    /**
     * @private
     * @type {!Object<string, import("../tilegrid/TileGrid.js").default>}
     */
    this.tileGridForProjection_ = {};

    /**
     * @private
     * @type {!Object<string, import("../TileCache.js").default>}
     */
    this.tileCacheForProjection_ = {};
  }

  /**
   * Set the source tile sizes.  The length of the array is expected to match the number of
   * levels in the tile grid.
   * @protected
   * @param {Array<import('../size.js').Size>} tileSizes An array of tile sizes.
   */
  setTileSizes(tileSizes) {
    this.tileSizes_ = tileSizes;
  }

  /**
   * Get the source tile size at the given zoom level.  This may be different than the rendered tile
   * size.
   * @protected
   * @param {number} z Tile zoom level.
   * @return {import('../size.js').Size} The source tile size.
   */
  getTileSize(z) {
    if (this.tileSizes_) {
      return this.tileSizes_[z];
    }
    if (this.tileSize_) {
      return this.tileSize_;
    }
    const tileGrid = this.getTileGrid();
    return tileGrid ? toSize(tileGrid.getTileSize(z)) : [256, 256];
  }

  /**
   * @param {import("../proj/Projection.js").default} projection Projection.
   * @return {number} Gutter.
   */
  getGutterForProjection(projection) {
    const thisProj = this.getProjection();
    if (!thisProj || equivalent(thisProj, projection)) {
      return this.gutter_;
    } else {
      return 0;
    }
  }

  /**
   * @param {Loader} loader The data loader.
   * @protected
   */
  setLoader(loader) {
    this.loader_ = loader;
  }

  /**
   * @param {number} z Tile coordinate z.
   * @param {number} x Tile coordinate x.
   * @param {number} y Tile coordinate y.
   * @param {number} pixelRatio Pixel ratio.
   * @param {import("../proj/Projection.js").default} projection Projection.
   * @return {!DataTile} Tile.
   */
  getTile(z, x, y, pixelRatio, projection) {
    const sourceProjection = this.getProjection();
    if (
      sourceProjection &&
      projection &&
      !equivalent(sourceProjection, projection)
    ) {
      const cache = this.getTileCacheForProjection(projection);
      let tile;
      const tileCoordKey = getKeyZXY(z, x, y);
      if (cache.containsKey(tileCoordKey)) {
        tile = cache.get(tileCoordKey);
      }
      const key = this.getKey();
      if (tile && tile.key == key) {
        return tile;
      } else {
        const tileGrid = this.getTileGrid();
        const reprojTilePixelRatio = Math.max.apply(
          null,
          tileGrid.getResolutions().map((r, z) => {
            const tileSize = toSize(tileGrid.getTileSize(z));
            const textureSize = this.getTileSize(z);
            return Math.max(
              textureSize[0] / tileSize[0],
              textureSize[1] / tileSize[1]
            );
          })
        );

        const sourceTileGrid = this.getTileGridForProjection(sourceProjection);
        const targetTileGrid = this.getTileGridForProjection(projection);
        const tileCoord = [z, x, y];
        const wrappedTileCoord = this.getTileCoordForTileUrlFunction(
          tileCoord,
          projection
        );
        const newTile = new ReprojDataTile(
          sourceProjection,
          sourceTileGrid,
          projection,
          targetTileGrid,
          tileCoord,
          wrappedTileCoord,
          reprojTilePixelRatio,
          this.getGutterForProjection(sourceProjection),
          function (z, x, y, pixelRatio) {
            return this.getTile(z, x, y, pixelRatio, sourceProjection);
          }.bind(this),
          this.getInterpolate()
        );
        newTile.key = key;
        return newTile;
      }
    }

    const size = this.getTileSize(z);
    const tileCoordKey = getKeyZXY(z, x, y);
    if (this.tileCache.containsKey(tileCoordKey)) {
      return this.tileCache.get(tileCoordKey);
    }

    const sourceLoader = this.loader_;

    function loader() {
      return toPromise(function () {
        return sourceLoader(z, x, y);
      });
    }

    const options = Object.assign(
      {
        tileCoord: [z, x, y],
        loader: loader,
        size: size,
      },
      this.tileOptions
    );

    const tile = new DataTile(options);
    tile.key = this.getKey();
    tile.addEventListener(EventType.CHANGE, this.handleTileChange_);

    this.tileCache.set(tileCoordKey, tile);
    return tile;
  }

  /**
   * Handle tile change events.
   * @param {import("../events/Event.js").default} event Event.
   */
  handleTileChange_(event) {
    const tile = /** @type {import("../Tile.js").default} */ (event.target);
    const uid = getUid(tile);
    const tileState = tile.getState();
    let type;
    if (tileState == TileState.LOADING) {
      this.tileLoadingKeys_[uid] = true;
      type = TileEventType.TILELOADSTART;
    } else if (uid in this.tileLoadingKeys_) {
      delete this.tileLoadingKeys_[uid];
      type =
        tileState == TileState.ERROR
          ? TileEventType.TILELOADERROR
          : tileState == TileState.LOADED
          ? TileEventType.TILELOADEND
          : undefined;
    }
    if (type) {
      this.dispatchEvent(new TileSourceEvent(type, tile));
    }
  }

  /**
   * @param {import("../proj/Projection.js").default} projection Projection.
   * @return {!import("../tilegrid/TileGrid.js").default} Tile grid.
   */
  getTileGridForProjection(projection) {
    const thisProj = this.getProjection();
    if (this.tileGrid && (!thisProj || equivalent(thisProj, projection))) {
      return this.tileGrid;
    } else {
      const projKey = getUid(projection);
      if (!(projKey in this.tileGridForProjection_)) {
        this.tileGridForProjection_[projKey] =
          getTileGridForProjection(projection);
      }
      return this.tileGridForProjection_[projKey];
    }
  }

  /**
   * Sets the tile grid to use when reprojecting the tiles to the given
   * projection instead of the default tile grid for the projection.
   *
   * This can be useful when the default tile grid cannot be created
   * (e.g. projection has no extent defined) or
   * for optimization reasons (custom tile size, resolutions, ...).
   *
   * @param {import("../proj.js").ProjectionLike} projection Projection.
   * @param {import("../tilegrid/TileGrid.js").default} tilegrid Tile grid to use for the projection.
   * @api
   */
  setTileGridForProjection(projection, tilegrid) {
    const proj = getProjection(projection);
    if (proj) {
      const projKey = getUid(proj);
      if (!(projKey in this.tileGridForProjection_)) {
        this.tileGridForProjection_[projKey] = tilegrid;
      }
    }
  }

  /**
   * @param {import("../proj/Projection.js").default} projection Projection.
   * @return {import("../TileCache.js").default} Tile cache.
   */
  getTileCacheForProjection(projection) {
    const thisProj = this.getProjection();
    if (!thisProj || equivalent(thisProj, projection)) {
      return this.tileCache;
    } else {
      const projKey = getUid(projection);
      if (!(projKey in this.tileCacheForProjection_)) {
        this.tileCacheForProjection_[projKey] = new TileCache(0.1); // don't cache
      }
      return this.tileCacheForProjection_[projKey];
    }
  }

  /**
   * @param {import("../proj/Projection.js").default} projection Projection.
   * @param {!Object<string, boolean>} usedTiles Used tiles.
   */
  expireCache(projection, usedTiles) {
    const usedTileCache = this.getTileCacheForProjection(projection);

    this.tileCache.expireCache(
      this.tileCache == usedTileCache ? usedTiles : {}
    );
    for (const id in this.tileCacheForProjection_) {
      const tileCache = this.tileCacheForProjection_[id];
      tileCache.expireCache(tileCache == usedTileCache ? usedTiles : {});
    }
  }

  clear() {
    super.clear();
    for (const id in this.tileCacheForProjection_) {
      this.tileCacheForProjection_[id].clear();
    }
  }
}

export default DataTileSource;
<commit_msg>Code shuffle<commit_after>/**
 * @module ol/source/DataTile
 */
import DataTile from '../DataTile.js';
import EventType from '../events/EventType.js';
import ReprojDataTile from '../reproj/DataTile.js';
import TileCache from '../TileCache.js';
import TileEventType from './TileEventType.js';
import TileSource, {TileSourceEvent} from './Tile.js';
import TileState from '../TileState.js';
import {
  createXYZ,
  extentFromProjection,
  getForProjection as getTileGridForProjection,
} from '../tilegrid.js';
import {equivalent, get as getProjection} from '../proj.js';
import {getKeyZXY} from '../tilecoord.js';
import {getUid} from '../util.js';
import {toPromise} from '../functions.js';
import {toSize} from '../size.js';

/**
 * Data tile loading function.  The function is called with z, x, and y tile coordinates and
 * returns {@link import("../DataTile.js").Data data} for a tile or a promise for the same.
 * @typedef {function(number, number, number) : (import("../DataTile.js").Data|Promise<import("../DataTile.js").Data>)} Loader
 */

/**
 * @typedef {Object} Options
 * @property {Loader} [loader] Data loader.  Called with z, x, and y tile coordinates.
 * Returns {@link import("../DataTile.js").Data data} for a tile or a promise for the same.
 * @property {import("./Source.js").AttributionLike} [attributions] Attributions.
 * @property {boolean} [attributionsCollapsible=true] Attributions are collapsible.
 * @property {number} [maxZoom=42] Optional max zoom level. Not used if `tileGrid` is provided.
 * @property {number} [minZoom=0] Optional min zoom level. Not used if `tileGrid` is provided.
 * @property {number|import("../size.js").Size} [tileSize=[256, 256]] The pixel width and height of the source tiles.
 * This may be different than the rendered pixel size if a `tileGrid` is provided.
 * @property {number} [gutter=0] The size in pixels of the gutter around data tiles to ignore.
 * This allows artifacts of rendering at tile edges to be ignored.
 * Supported data should be wider and taller than the tile size by a value of `2 x gutter`.
 * @property {number} [maxResolution] Optional tile grid resolution at level zero. Not used if `tileGrid` is provided.
 * @property {import("../proj.js").ProjectionLike} [projection='EPSG:3857'] Tile projection.
 * @property {import("../tilegrid/TileGrid.js").default} [tileGrid] Tile grid.
 * @property {boolean} [opaque=false] Whether the layer is opaque.
 * @property {import("./Source.js").State} [state] The source state.
 * @property {boolean} [wrapX=false] Render tiles beyond the antimeridian.
 * @property {number} [transition] Transition time when fading in new tiles (in miliseconds).
 * @property {number} [bandCount=4] Number of bands represented in the data.
 * @property {boolean} [interpolate=false] Use interpolated values when resampling.  By default,
 * the nearest neighbor is used when resampling.
 */

/**
 * @classdesc
 * A source for typed array data tiles.
 *
 * @fires import("./Tile.js").TileSourceEvent
 * @api
 */
class DataTileSource extends TileSource {
  /**
   * @param {Options} options DataTile source options.
   */
  constructor(options) {
    const projection =
      options.projection === undefined ? 'EPSG:3857' : options.projection;

    let tileGrid = options.tileGrid;
    if (tileGrid === undefined && projection) {
      tileGrid = createXYZ({
        extent: extentFromProjection(projection),
        maxResolution: options.maxResolution,
        maxZoom: options.maxZoom,
        minZoom: options.minZoom,
        tileSize: options.tileSize,
      });
    }

    super({
      cacheSize: 0.1, // don't cache on the source
      attributions: options.attributions,
      attributionsCollapsible: options.attributionsCollapsible,
      projection: projection,
      tileGrid: tileGrid,
      opaque: options.opaque,
      state: options.state,
      wrapX: options.wrapX,
      transition: options.transition,
      interpolate: options.interpolate,
    });

    /**
     * @private
     * @type {number}
     */
    this.gutter_ = options.gutter !== undefined ? options.gutter : 0;

    /**
     * @private
     * @type {import('../size.js').Size|null}
     */
    this.tileSize_ = options.tileSize ? toSize(options.tileSize) : null;

    /**
     * @private
     * @type {Array<import('../size.js').Size>|null}
     */
    this.tileSizes_ = null;

    /**
     * @private
     * @type {!Object<string, boolean>}
     */
    this.tileLoadingKeys_ = {};

    /**
     * @private
     */
    this.loader_ = options.loader;

    this.handleTileChange_ = this.handleTileChange_.bind(this);

    /**
     * @type {number}
     */
    this.bandCount = options.bandCount === undefined ? 4 : options.bandCount; // assume RGBA if undefined

    /**
     * @private
     * @type {!Object<string, import("../tilegrid/TileGrid.js").default>}
     */
    this.tileGridForProjection_ = {};

    /**
     * @private
     * @type {!Object<string, import("../TileCache.js").default>}
     */
    this.tileCacheForProjection_ = {};
  }

  /**
   * Set the source tile sizes.  The length of the array is expected to match the number of
   * levels in the tile grid.
   * @protected
   * @param {Array<import('../size.js').Size>} tileSizes An array of tile sizes.
   */
  setTileSizes(tileSizes) {
    this.tileSizes_ = tileSizes;
  }

  /**
   * Get the source tile size at the given zoom level.  This may be different than the rendered tile
   * size.
   * @protected
   * @param {number} z Tile zoom level.
   * @return {import('../size.js').Size} The source tile size.
   */
  getTileSize(z) {
    if (this.tileSizes_) {
      return this.tileSizes_[z];
    }
    if (this.tileSize_) {
      return this.tileSize_;
    }
    const tileGrid = this.getTileGrid();
    return tileGrid ? toSize(tileGrid.getTileSize(z)) : [256, 256];
  }

  /**
   * @param {import("../proj/Projection.js").default} projection Projection.
   * @return {number} Gutter.
   */
  getGutterForProjection(projection) {
    const thisProj = this.getProjection();
    if (!thisProj || equivalent(thisProj, projection)) {
      return this.gutter_;
    }

    return 0;
  }

  /**
   * @param {Loader} loader The data loader.
   * @protected
   */
  setLoader(loader) {
    this.loader_ = loader;
  }

  /**
   * @param {number} z Tile coordinate z.
   * @param {number} x Tile coordinate x.
   * @param {number} y Tile coordinate y.
   * @param {import("../proj/Projection.js").default} targetProjection The output projection.
   * @param {import("../proj/Projection.js").default} sourceProjection The input projection.
   * @return {!DataTile} Tile.
   */
  getReprojTile_(z, x, y, targetProjection, sourceProjection) {
    const cache = this.getTileCacheForProjection(targetProjection);
    const tileCoordKey = getKeyZXY(z, x, y);
    if (cache.containsKey(tileCoordKey)) {
      const tile = cache.get(tileCoordKey);
      if (tile && tile.key == this.getKey()) {
        return tile;
      }
    }

    const tileGrid = this.getTileGrid();
    const reprojTilePixelRatio = Math.max.apply(
      null,
      tileGrid.getResolutions().map((r, z) => {
        const tileSize = toSize(tileGrid.getTileSize(z));
        const textureSize = this.getTileSize(z);
        return Math.max(
          textureSize[0] / tileSize[0],
          textureSize[1] / tileSize[1]
        );
      })
    );

    const sourceTileGrid = this.getTileGridForProjection(sourceProjection);
    const targetTileGrid = this.getTileGridForProjection(targetProjection);
    const tileCoord = [z, x, y];
    const wrappedTileCoord = this.getTileCoordForTileUrlFunction(
      tileCoord,
      targetProjection
    );
    const newTile = new ReprojDataTile(
      sourceProjection,
      sourceTileGrid,
      targetProjection,
      targetTileGrid,
      tileCoord,
      wrappedTileCoord,
      reprojTilePixelRatio,
      this.getGutterForProjection(sourceProjection),
      function (z, x, y, pixelRatio) {
        return this.getTile(z, x, y, pixelRatio, sourceProjection);
      }.bind(this),
      this.getInterpolate()
    );
    newTile.key = this.getKey();
    return newTile;
  }

  /**
   * @param {number} z Tile coordinate z.
   * @param {number} x Tile coordinate x.
   * @param {number} y Tile coordinate y.
   * @param {number} pixelRatio Pixel ratio.
   * @param {import("../proj/Projection.js").default} projection Projection.
   * @return {!DataTile} Tile.
   */
  getTile(z, x, y, pixelRatio, projection) {
    const sourceProjection = this.getProjection();
    if (
      sourceProjection &&
      projection &&
      !equivalent(sourceProjection, projection)
    ) {
      return this.getReprojTile_(z, x, y, projection, sourceProjection);
    }

    const size = this.getTileSize(z);
    const tileCoordKey = getKeyZXY(z, x, y);
    if (this.tileCache.containsKey(tileCoordKey)) {
      return this.tileCache.get(tileCoordKey);
    }

    const sourceLoader = this.loader_;

    function loader() {
      return toPromise(function () {
        return sourceLoader(z, x, y);
      });
    }

    const options = Object.assign(
      {
        tileCoord: [z, x, y],
        loader: loader,
        size: size,
      },
      this.tileOptions
    );

    const tile = new DataTile(options);
    tile.key = this.getKey();
    tile.addEventListener(EventType.CHANGE, this.handleTileChange_);

    this.tileCache.set(tileCoordKey, tile);
    return tile;
  }

  /**
   * Handle tile change events.
   * @param {import("../events/Event.js").default} event Event.
   */
  handleTileChange_(event) {
    const tile = /** @type {import("../Tile.js").default} */ (event.target);
    const uid = getUid(tile);
    const tileState = tile.getState();
    let type;
    if (tileState == TileState.LOADING) {
      this.tileLoadingKeys_[uid] = true;
      type = TileEventType.TILELOADSTART;
    } else if (uid in this.tileLoadingKeys_) {
      delete this.tileLoadingKeys_[uid];
      type =
        tileState == TileState.ERROR
          ? TileEventType.TILELOADERROR
          : tileState == TileState.LOADED
          ? TileEventType.TILELOADEND
          : undefined;
    }
    if (type) {
      this.dispatchEvent(new TileSourceEvent(type, tile));
    }
  }

  /**
   * @param {import("../proj/Projection.js").default} projection Projection.
   * @return {!import("../tilegrid/TileGrid.js").default} Tile grid.
   */
  getTileGridForProjection(projection) {
    const thisProj = this.getProjection();
    if (this.tileGrid && (!thisProj || equivalent(thisProj, projection))) {
      return this.tileGrid;
    }

    const projKey = getUid(projection);
    if (!(projKey in this.tileGridForProjection_)) {
      this.tileGridForProjection_[projKey] =
        getTileGridForProjection(projection);
    }
    return this.tileGridForProjection_[projKey];
  }

  /**
   * Sets the tile grid to use when reprojecting the tiles to the given
   * projection instead of the default tile grid for the projection.
   *
   * This can be useful when the default tile grid cannot be created
   * (e.g. projection has no extent defined) or
   * for optimization reasons (custom tile size, resolutions, ...).
   *
   * @param {import("../proj.js").ProjectionLike} projection Projection.
   * @param {import("../tilegrid/TileGrid.js").default} tilegrid Tile grid to use for the projection.
   * @api
   */
  setTileGridForProjection(projection, tilegrid) {
    const proj = getProjection(projection);
    if (proj) {
      const projKey = getUid(proj);
      if (!(projKey in this.tileGridForProjection_)) {
        this.tileGridForProjection_[projKey] = tilegrid;
      }
    }
  }

  /**
   * @param {import("../proj/Projection.js").default} projection Projection.
   * @return {import("../TileCache.js").default} Tile cache.
   */
  getTileCacheForProjection(projection) {
    const thisProj = this.getProjection();
    if (!thisProj || equivalent(thisProj, projection)) {
      return this.tileCache;
    }

    const projKey = getUid(projection);
    if (!(projKey in this.tileCacheForProjection_)) {
      this.tileCacheForProjection_[projKey] = new TileCache(0.1); // don't cache
    }
    return this.tileCacheForProjection_[projKey];
  }

  /**
   * @param {import("../proj/Projection.js").default} projection Projection.
   * @param {!Object<string, boolean>} usedTiles Used tiles.
   */
  expireCache(projection, usedTiles) {
    const usedTileCache = this.getTileCacheForProjection(projection);

    this.tileCache.expireCache(
      this.tileCache == usedTileCache ? usedTiles : {}
    );
    for (const id in this.tileCacheForProjection_) {
      const tileCache = this.tileCacheForProjection_[id];
      tileCache.expireCache(tileCache == usedTileCache ? usedTiles : {});
    }
  }

  clear() {
    super.clear();
    for (const id in this.tileCacheForProjection_) {
      this.tileCacheForProjection_[id].clear();
    }
  }
}

export default DataTileSource;
<|endoftext|>


<commit_before>/**
 * Copyright 2013 - present by OpenGamma Inc. and the OpenGamma group of companies
 * Please see distribution for license.
 */
$.register_module({
    name: 'og.blotter.forms.fxdigitaloptionsecurity',
    dependencies: [],
    obj: function () {
        return function (config) {
            config.title = 'FX Digital Option';
            config.type = 'FXDigitalOptionSecurity';
            config.digital = true;
            return new og.blotter.forms.fxoptionbasesecurity(config);
        };
    }<commit_msg>[PLAT-4681] fx digital option missing '});' in blotter<commit_after>/**
 * Copyright 2013 - present by OpenGamma Inc. and the OpenGamma group of companies
 * Please see distribution for license.
 */
$.register_module({
    name: 'og.blotter.forms.fxdigitaloptionsecurity',
    dependencies: [],
    obj: function () {
        return function (config) {
            config.title = 'FX Digital Option';
            config.type = 'FXDigitalOptionSecurity';
            config.digital = true;
            return new og.blotter.forms.fxoptionbasesecurity(config);
        };
    }
});<|endoftext|>


<commit_before>(function($) {

  $('form').on('submit', function(e) {
    e.preventDefault();
    var data = $(this).serialize();
    console.log(data);
    $.ajax({
      url: '/',
      type: 'POST',
      data: data,
      dataType: 'json',
      success: function(data) {
        console.log(data);
      },
      error: function(err) {
        console.log(err);
      }
    });
  });

})(jQuery);
<commit_msg>Tokens<commit_after>(function($, window) {

  const TOKEN_STORAGE_NAME = 'hack-start-token';

  function saveToken(token) {
    window.localStorage.setItem(TOKEN_STORAGE_NAME, token);
  }

  function getToken() {
    return window.localStorage.getItem(TOKEN_STORAGE_NAME);
  }

  function isLoggedIn() {
    var token = getToken();

    if (token) {
      var payload = JSON.parse(window.atob(token.split('.')[1]));

      return payload.exp > (Date.now() / 1000);
    }

    return false;
  }

  function logout() {
    window.localStorage.removeItem(TOKEN_STORAGE_NAME);
  }

  $('form').on('submit', function(e) {
    e.preventDefault();
    var data = $(this).serialize();
    console.log(data);
    $.ajax({
      url: '/',
      type: 'POST',
      data: data,
      dataType: 'json',
      success: function(data) {
        console.log(data);
        saveToken(data.token);
      },
      error: function(err) {
        console.log(err);
      }
    });
  });

})(jQuery, window);
<|endoftext|>


<commit_before>(function(window, undefined)
{
    window.SocketIOReadyHandlers = [];

    if (info.logined)
    {
        var socket = window._socket = null;

        $(document).ready(function()
        {
            socket = io.connect();

            socket.on('connect', function()
            {

                for (var i in SocketIOReadyHandlers)
                {
                    SocketIOReadyHandlers[i].call(socket);
                }

                var splash = $('#jSplash');

                if (splash.length > 0)
                {
                    splash.fadeOut(1000, function()
                    {
                        $(this).remove();
                    });
                }

            });
        });
    }
})(window);<commit_msg>fix the bug that socket is undefined<commit_after>(function(window, undefined)
{
    window.SocketIOReadyHandlers = [];

    if (info.logined)
    {
        var socket = window._socket = null;

        $(document).ready(function()
        {
            socket = window._socket = io.connect();

            socket.on('connect', function()
            {

                for (var i in SocketIOReadyHandlers)
                {
                    SocketIOReadyHandlers[i].call(socket);
                }

                var splash = $('#jSplash');

                if (splash.length > 0)
                {
                    splash.fadeOut(1000, function()
                    {
                        $(this).remove();
                    });
                }

            });
        });
    }
})(window);<|endoftext|>