<commit_before>/*
 * Copyright (c) 2014ff Thomas Feuster
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * Support for selecting with cntrl + mouse
 *
 * functions to disable & enable dragging & zooming when cntrl mouse pressed & release
 * function to retrieve bounds of the currently shown map to scale javafx rect to lat/lon
 *
 */

// disable drag & zoom for events with control key
function disableCntrlDrag(e) {
    if (e.originalEvent.ctrlKey) {
        myMap.dragging.disable();
        myMap.boxZoom.disable();
    }
}

// enable drag & zoom for events with control key
function enableCntrlDrag(e) {
    if (e.originalEvent.ctrlKey) {
        myMap.dragging.enable();
        myMap.boxZoom.enable();
    }
}

// disable on cntrl mouse down
myMap.on('mousedown', disableCntrlDrag);
// disable on cntrl mouse up
myMap.on('mouseup', enableCntrlDrag);

// TFE, 20181124
// add callbacks for map move or zoom that send bounds back to java
function mapViewChanged(e) {
    var bounds = getMapBounds();
//    jscallback.log('mapViewChanged: ' + e.type + ", " + bounds[0] + ", " + bounds[1] + ", " + bounds[2] + ", " + bounds[3]);
    jscallback.mapViewChanged(e.type, bounds[0], bounds[1], bounds[2], bounds[3]);
}
myMap.on('zoomend', mapViewChanged);
myMap.on('moveend', mapViewChanged);
myMap.on('resize', mapViewChanged);

// wrap around world borders
// https://stackoverflow.com/a/28323349
myMap.options.worldCopyJump = true;

// alternative to use setView - avoids calculating center and zoom from bounds manually
function setMapBounds(latMin, latMax, lngMin, lngMax) {
//    jscallback.log('addClickToLayer: ' + latMin + ", " + latMax + ", " + lngMin + ", " + lngMax);
    myMap.fitBounds([
        [latMin, lngMin],
        [latMax, lngMax]
    ]);
}

// return lower left and upper right corners of currently shown map
function getMapBounds() {
    var bounds = myMap.getBounds();
    return [bounds.getSouthWest().lat, bounds.getSouthWest().lng, bounds.getNorthEast().lat, bounds.getNorthEast().lng];
}

// ability to change a marker icon and color (e.g. for highlighting)
function updateMarkerIcon(layer, icon) {
    window[layer].setIcon(window[icon]);
}
function updateMarkerColor(layer, color) {
    window[layer].setStyle({
        color: color,
        weight: 2
    });
}
// move marker around
function updateMarkerLocation(layer, lat, lng) {
    var marker = window[layer];
    var newLatLng = new L.LatLng(lat, lng);
    marker.setLatLng(newLatLng);
}

/*
 * add click handler to layer to send back lat/lon
 */
function addClickToLayer(layer, lat, lng) {
    var marker = window[layer];

    //jscallback.log('addClickToLayer: ' + layer + ", " + marker);
    marker.on('click', function(e) {
        jscallback.selectMarker(layer, lat, lng, e.originalEvent.shiftKey);
    });
}

/*
 * add name to layer for tooltip
 */
function addNameToLayer(layer, name) {
    var polyline = window[layer];

    if (polyline instanceof L.Polyline) {
        //jscallback.log('addNameToLayer: ' + layer + ", " + name);
        polyline.options.interactive = true;

        polyline.bindTooltip(name, {sticky: true});
        setTitle(layer, name);
    }
}

/*
 * support for draggable markers including callback at dragend
 */
function makeDraggable(layer, lat, lng) {
    var marker = window[layer];

    marker.dragging.enable();
    marker.on('dragend', function(e) {
        var newPos = marker.getLatLng();
        jscallback.moveMarker(layer, lat, lng, newPos.lat, newPos.lng);
    });
}
function setTitle(layer, title) {
    var marker = window[layer];

    //jscallback.log('setTitle: ' + layer + ", " + marker);
    if (marker._icon) {
        marker._icon.title = title;
    } else {
        marker.options.title = title;
    }
}

/*
 * convert pixel coordinates into latlng
 */
function getLatLngForPoint(x, y) {
    var point = L.point(x, y);
    // take pane & zoom into account when transforming - therefore containerPointToLatLng and not layerPointToLatLng
    var latlng = myMap.containerPointToLatLng(point);
    return [latlng.lat, latlng.lng];
}
function getLatLngForRect(startx, starty, endx, endy) {
    return getLatLngForPoint(startx, starty).concat(getLatLngForPoint(endx, endy));
}
/*
 * JSON.stringify doesn't work on LatLngs...
 */
function coordsToString(coords) {
    var coordsString = "";

    var arrayLength = coords.length;
    for (var i = 0; i < arrayLength; i++) {
        var latlan = coords[i];

        coordsString = coordsString + "lat:" + latlan.lat + ", lon:" + latlan.lng;

        if (i < arrayLength-1) {
            coordsString = coordsString + " - "
        }
    }
    return coordsString;
}

/*
 * search and add results to marker layer
 * inspired by https://jsfiddle.net/chk1/b5wgds4n/
 */
// use separate layer for search results for easy removal
// register / deregister marker under mouse
function registerMarker(e) {
    var marker = e.target;
    var markerPos = marker.getLatLng();
    jscallback.registerMarker(JSON.stringify(marker.properties), markerPos.lat, markerPos.lng);
}
function deregisterMarker(e) {
    var marker = e.target;
    var markerPos = marker.getLatLng();
    jscallback.deregisterMarker(JSON.stringify(marker.properties), markerPos.lat, markerPos.lng);
}

// keep track of the markers for later communication with java
var searchResultsLayer = L.layerGroup().addTo(myMap);
var searchResults;
var searchCount;

function clearSearchResults() {
    searchResultsLayer.clearLayers();
    searchResults = [];
    searchCount = 0;
}
clearSearchResults();

function removeSearchResult(markerCount) {
    if (markerCount in searchResults) {
        searchResultsLayer.removeLayer(searchResults[markerCount]);
    }
}

function showSearchResults(searchItem, result, iconName) {
    //callback.log("result: " + result);
    var data = JSON.parse(result);
    var icon = window[iconName];

    if(data.hasOwnProperty("elements")) {
        if(data.elements.length > 0) {
            for(var i in data.elements) {
                var point = new L.marker([data.elements[i].lat, data.elements[i].lon], {icon: icon}).addTo(searchResultsLayer);
                point.properties = {};
                point.properties.SearchItem = searchItem;
                point.on('mouseover', registerMarker);
                point.on('mouseout', deregisterMarker);

                var title = getTitleFromTags(point, data.elements[i]);

                if (title.length > 0) {
                    if (point._icon) {
                        point._icon.title = title;
                    } else {
                        point.options.title = title;
                    }
                }

                // add result to the big list...
                point.properties.MarkerCount = searchCount;
                searchResults.push(point);
                searchCount++;
            }
        }
    }
}
/*
 * Scan data for tags and build title from existing values:
 * name
 * cuisine
 * phone
 * email
 * website
 */
function getTitleFromTags(point, data) {
    var title = "";
    if(data.hasOwnProperty("tags")) {
        if(data.tags.hasOwnProperty("name")) {
            title = data.tags.name;
            point.properties.Name = data.tags.name;
        }
        if(data.tags.hasOwnProperty("cuisine")) {
            if (title.length > 0) {
                title = title + "\n";
            }
            title = title + data.tags.cuisine;
            point.properties.Cuisine = data.tags.cuisine;
        }
        if(data.tags.hasOwnProperty("phone")) {
            if (title.length > 0) {
                title = title + "\n";
            }
            title = title + data.tags.phone;
            point.properties.Phone = data.tags.phone;
        }
        if(data.tags.hasOwnProperty("email")) {
            if (title.length > 0) {
                title = title + "\n";
            }
            title = title + data.tags.email;
            point.properties.Email = data.tags.email;
        }
        if(data.tags.hasOwnProperty("website")) {
            if (title.length > 0) {
                title = title + "\n";
            }
            title = title + data.tags.website;
            point.properties.Website = data.tags.website;
        }
        if(data.tags.hasOwnProperty("description")) {
            if (title.length > 0) {
                title = title + "\n";
            }
            title = title + data.tags.description;
            point.properties.Description = data.tags.description;
        }
    }

    return title;
}
<commit_msg>Fixed callback<commit_after>/*
 * Copyright (c) 2014ff Thomas Feuster
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * Support for selecting with cntrl + mouse
 *
 * functions to disable & enable dragging & zooming when cntrl mouse pressed & release
 * function to retrieve bounds of the currently shown map to scale javafx rect to lat/lon
 *
 */

// disable drag & zoom for events with control key
function disableCntrlDrag(e) {
    if (e.originalEvent.ctrlKey) {
        myMap.dragging.disable();
        myMap.boxZoom.disable();
    }
}

// enable drag & zoom for events with control key
function enableCntrlDrag(e) {
    if (e.originalEvent.ctrlKey) {
        myMap.dragging.enable();
        myMap.boxZoom.enable();
    }
}

// disable on cntrl mouse down
myMap.on('mousedown', disableCntrlDrag);
// disable on cntrl mouse up
myMap.on('mouseup', enableCntrlDrag);

// TFE, 20181124
// add callbacks for map move or zoom that send bounds back to java
function mapViewChanged(e) {
    var bounds = getMapBounds();
//    jscallback.log('mapViewChanged: ' + e.type + ", " + bounds[0] + ", " + bounds[1] + ", " + bounds[2] + ", " + bounds[3]);
    jscallback.mapViewChanged(e.type, bounds[0], bounds[1], bounds[2], bounds[3]);
}
myMap.on('zoomend', mapViewChanged);
myMap.on('moveend', mapViewChanged);
myMap.on('resize', mapViewChanged);

// wrap around world borders
// https://stackoverflow.com/a/28323349
myMap.options.worldCopyJump = true;

// alternative to use setView - avoids calculating center and zoom from bounds manually
function setMapBounds(latMin, latMax, lngMin, lngMax) {
//    jscallback.log('addClickToLayer: ' + latMin + ", " + latMax + ", " + lngMin + ", " + lngMax);
    myMap.fitBounds([
        [latMin, lngMin],
        [latMax, lngMax]
    ]);
}

// return lower left and upper right corners of currently shown map
function getMapBounds() {
    var bounds = myMap.getBounds();
    return [bounds.getSouthWest().lat, bounds.getSouthWest().lng, bounds.getNorthEast().lat, bounds.getNorthEast().lng];
}

// ability to change a marker icon and color (e.g. for highlighting)
function updateMarkerIcon(layer, icon) {
    window[layer].setIcon(window[icon]);
}
function updateMarkerColor(layer, color) {
    window[layer].setStyle({
        color: color,
        weight: 2
    });
}
// move marker around
function updateMarkerLocation(layer, lat, lng) {
    var marker = window[layer];
    var newLatLng = new L.LatLng(lat, lng);
    marker.setLatLng(newLatLng);
}

/*
 * add click handler to layer to send back lat/lon
 */
function addClickToLayer(layer, lat, lng) {
    var marker = window[layer];

    //jscallback.log('addClickToLayer: ' + layer + ", " + marker);
    marker.on('click', function(e) {
        jscallback.selectMarker(layer, lat, lng, e.originalEvent.shiftKey);
    });
}

/*
 * add name to layer for tooltip
 */
function addNameToLayer(layer, name) {
    var polyline = window[layer];

    if (polyline instanceof L.Polyline) {
        //jscallback.log('addNameToLayer: ' + layer + ", " + name);
        polyline.options.interactive = true;

        polyline.bindTooltip(name, {sticky: true});
        setTitle(layer, name);
    }
}

/*
 * support for draggable markers including callback at dragend
 */
function makeDraggable(layer, lat, lng) {
    var marker = window[layer];

    marker.dragging.enable();
    marker.on('dragend', function(e) {
        var newPos = marker.getLatLng();
        jscallback.moveMarker(layer, lat, lng, newPos.lat, newPos.lng);
    });
}
function setTitle(layer, title) {
    var marker = window[layer];

    //jscallback.log('setTitle: ' + layer + ", " + marker);
    if (marker._icon) {
        marker._icon.title = title;
    } else {
        marker.options.title = title;
    }
}

/*
 * convert pixel coordinates into latlng
 */
function getLatLngForPoint(x, y) {
    var point = L.point(x, y);
    // take pane & zoom into account when transforming - therefore containerPointToLatLng and not layerPointToLatLng
    var latlng = myMap.containerPointToLatLng(point);
    return [latlng.lat, latlng.lng];
}
function getLatLngForRect(startx, starty, endx, endy) {
    return getLatLngForPoint(startx, starty).concat(getLatLngForPoint(endx, endy));
}
/*
 * JSON.stringify doesn't work on LatLngs...
 */
function coordsToString(coords) {
    var coordsString = "";

    var arrayLength = coords.length;
    for (var i = 0; i < arrayLength; i++) {
        var latlan = coords[i];

        coordsString = coordsString + "lat:" + latlan.lat + ", lon:" + latlan.lng;

        if (i < arrayLength-1) {
            coordsString = coordsString + " - "
        }
    }
    return coordsString;
}

/*
 * search and add results to marker layer
 * inspired by https://jsfiddle.net/chk1/b5wgds4n/
 */
// use separate layer for search results for easy removal
// register / deregister marker under mouse
function registerMarker(e) {
    var marker = e.target;
    var markerPos = marker.getLatLng();
    jscallback.registerMarker(JSON.stringify(marker.properties), markerPos.lat, markerPos.lng);
}
function deregisterMarker(e) {
    var marker = e.target;
    var markerPos = marker.getLatLng();
    jscallback.deregisterMarker(JSON.stringify(marker.properties), markerPos.lat, markerPos.lng);
}

// keep track of the markers for later communication with java
var searchResultsLayer = L.layerGroup().addTo(myMap);
var searchResults;
var searchCount;

function clearSearchResults() {
    searchResultsLayer.clearLayers();
    searchResults = [];
    searchCount = 0;
}
clearSearchResults();

function removeSearchResult(markerCount) {
    if (markerCount in searchResults) {
        searchResultsLayer.removeLayer(searchResults[markerCount]);
    }
}

function showSearchResults(searchItem, result, iconName) {
//    jscallback.log("result: " + result);
    var data = JSON.parse(result);
    var icon = window[iconName];

    if(data.hasOwnProperty("elements")) {
        if(data.elements.length > 0) {
            for(var i in data.elements) {
                var point = new L.marker([data.elements[i].lat, data.elements[i].lon], {icon: icon}).addTo(searchResultsLayer);
                point.properties = {};
                point.properties.SearchItem = searchItem;
                point.on('mouseover', registerMarker);
                point.on('mouseout', deregisterMarker);

                var title = getTitleFromTags(point, data.elements[i]);

                if (title.length > 0) {
                    if (point._icon) {
                        point._icon.title = title;
                    } else {
                        point.options.title = title;
                    }
                }

                // add result to the big list...
                point.properties.MarkerCount = searchCount;
//                jscallback.log("title: " + title);
//                jscallback.log("point: " + point);
                searchResults.push(point);
                searchCount++;
            }
        }
    }
}
/*
 * Scan data for tags and build title from existing values:
 * name
 * cuisine
 * phone
 * email
 * website
 */
function getTitleFromTags(point, data) {
    var title = "";
    if(data.hasOwnProperty("tags")) {
        if(data.tags.hasOwnProperty("name")) {
            title = data.tags.name;
            point.properties.Name = data.tags.name;
        }
        if(data.tags.hasOwnProperty("cuisine")) {
            if (title.length > 0) {
                title = title + "\n";
            }
            title = title + data.tags.cuisine;
            point.properties.Cuisine = data.tags.cuisine;
        }
        if(data.tags.hasOwnProperty("phone")) {
            if (title.length > 0) {
                title = title + "\n";
            }
            title = title + data.tags.phone;
            point.properties.Phone = data.tags.phone;
        }
        if(data.tags.hasOwnProperty("email")) {
            if (title.length > 0) {
                title = title + "\n";
            }
            title = title + data.tags.email;
            point.properties.Email = data.tags.email;
        }
        if(data.tags.hasOwnProperty("website")) {
            if (title.length > 0) {
                title = title + "\n";
            }
            title = title + data.tags.website;
            point.properties.Website = data.tags.website;
        }
        if(data.tags.hasOwnProperty("description")) {
            if (title.length > 0) {
                title = title + "\n";
            }
            title = title + data.tags.description;
            point.properties.Description = data.tags.description;
        }
    }

    return title;
}
<|endoftext|>


<commit_before>export default function listify(addons) {
  return Object.keys(addons)
               .sort()
               .map(slug => addons[slug]);
}
<commit_msg>Gracefully fail when attempting to listify an undefined value.<commit_after>export default function listify(addons) {
	if (!addons) {
		return [];
	}
  return Object.keys(addons)
               .sort()
               .map(slug => addons[slug]);
}
<|endoftext|>


<commit_before>/*
 * moleculer
 * Copyright (c) 2019 MoleculerJS (https://github.com/moleculerjs/moleculer)
 * MIT Licensed
 */

"use strict";

const { defaultsDeep } = require("lodash");
const { parseByteString } = require("../../utils");
const zlib = require("zlib");
const { promisify } = require("util");

/**
 * This is a transmission compression middleware. It supports
 * the `deflate`, `deflateRaw` & `gzip` compression methods.
 *
 * @param {String} method
 */
module.exports = function CompressionMiddleware(opts) {
	opts = defaultsDeep(opts, { method: "deflate", threshold: "1kb" });

	let compress, decompress;
	const threshold = parseByteString(opts.threshold);

	switch(opts.method) {
		case "deflate":
			compress = promisify(zlib.deflate);
			decompress = promisify(zlib.inflate);
			break;
		case "deflateRaw":
			compress = promisify(zlib.deflateRaw);
			decompress = promisify(zlib.inflateRaw);
			break;
		case "gzip":
			compress = promisify(zlib.gzip);
			decompress = promisify(zlib.gunzip);
			break;
		default:
			/* istanbul ignore next */
			throw new Error("Unknow compression method: " + opts.method);
	}

	let logger;

	return {
		name: "Compression",

		created(broker) {
			logger = broker.getLogger("TX-COMPRESS");
			/* istanbul ignore next */
			logger.info(`The transmission is COMPRESSED by '${opts.method}'. Threshold: ${ threshold != null ? opts.threshold : "none"}`);
		},

		transporterSend(next) {
			return (topic, data, meta) => {
				if (threshold != null && data.length < threshold) {
					logger.debug(`Packet '${topic}' is small and not compressed. Size: ${data.length}`);
					return next(topic, Buffer.concat([Buffer.from([0x00]), data]), meta);
				}
				return compress(data)
					.then(res => {
						logger.debug(`Packet '${topic}' compressed. Saving: ${Number((1 - (res.length / data.length)) * 100).toFixed(0)}%`, data.length, res.length);
						return next(topic, Buffer.concat([Buffer.from([0x01]), res]), meta);
					});
			};
		},

		transporterReceive(next) {
			return (cmd, data, s) => {
				const isCompressed = data.readInt8(0);
				if (isCompressed == 0) {
					logger.debug(`Packet '${cmd}' is small and not compressed. Size: ${data.length}`);
					return next(cmd, data.slice(1), s);
				} else {
					return decompress(data.slice(1))
						.then(res => {
							logger.debug(`Packet '${cmd}' decompressed. Saving: ${Number((1 - (data.length / res.length)) * 100).toFixed(0)}%`, res.length, data.length);
							return next(cmd, res, s);
						});
				}
			};
		}
	};
};
<commit_msg>add comments<commit_after>/*
 * moleculer
 * Copyright (c) 2019 MoleculerJS (https://github.com/moleculerjs/moleculer)
 * MIT Licensed
 */

"use strict";

const { defaultsDeep } = require("lodash");
const { parseByteString } = require("../../utils");
const zlib = require("zlib");
const { promisify } = require("util");

/**
 * This is a transmission compression middleware. It supports
 * the `deflate`, `deflateRaw` & `gzip` compression methods.
 *
 * @param {String?} opts.method
 * @param {String|Number} opts.threshold
 */
module.exports = function CompressionMiddleware(opts) {
	opts = defaultsDeep(opts, { method: "deflate", threshold: "1kb" });

	let compress, decompress;
	const threshold = parseByteString(opts.threshold);

	switch(opts.method) {
		case "deflate":
			compress = promisify(zlib.deflate);
			decompress = promisify(zlib.inflate);
			break;
		case "deflateRaw":
			compress = promisify(zlib.deflateRaw);
			decompress = promisify(zlib.inflateRaw);
			break;
		case "gzip":
			compress = promisify(zlib.gzip);
			decompress = promisify(zlib.gunzip);
			break;
		default:
			/* istanbul ignore next */
			throw new Error("Unknow compression method: " + opts.method);
	}

	let logger;

	return {
		name: "Compression",

		created(broker) {
			logger = broker.getLogger("TX-COMPRESS");
			/* istanbul ignore next */
			logger.info(`The transmission is COMPRESSED by '${opts.method}'. Threshold: ${ threshold != null ? opts.threshold : "none"}`);
		},

		transporterSend(next) {
			return (topic, data, meta) => {
				if (threshold != null && data.length < threshold) {
					logger.debug(`Packet '${topic}' is small and not compressed. Size: ${data.length}`);
					return next(topic, Buffer.concat([Buffer.from([0x00]), data]), meta);
				}
				return compress(data)
					.then(res => {
						logger.debug(`Packet '${topic}' compressed. Saving: ${Number((1 - (res.length / data.length)) * 100).toFixed(0)}%`, data.length, res.length);
						return next(topic, Buffer.concat([Buffer.from([0x01]), res]), meta);
					});
			};
		},

		transporterReceive(next) {
			return (cmd, data, s) => {
				const isCompressed = data.readInt8(0);
				if (isCompressed == 0) {
					logger.debug(`Packet '${cmd}' is small and not compressed. Size: ${data.length}`);
					return next(cmd, data.slice(1), s);
				} else {
					return decompress(data.slice(1))
						.then(res => {
							logger.debug(`Packet '${cmd}' decompressed. Saving: ${Number((1 - (data.length / res.length)) * 100).toFixed(0)}%`, res.length, data.length);
							return next(cmd, res, s);
						});
				}
			};
		}
	};
};
<|endoftext|>


<commit_before>goog.provide('webfont.modules.google.FontApiUrlBuilder');

/**
 * @constructor
 */
webfont.modules.google.FontApiUrlBuilder = function(apiUrl, protocol, text) {
  if (apiUrl) {
    this.apiUrl_ = apiUrl;
  } else {
    this.apiUrl_ = protocol + webfont.modules.google.FontApiUrlBuilder.DEFAULT_API_URL;
  }
  this.fontFamilies_ = [];
  this.subsets_ = [];
  this.text_ = text || '';
};

webfont.modules.google.FontApiUrlBuilder.DEFAULT_API_URL = '//fonts.googleapis.com/css';

goog.scope(function () {
  var FontApiUrlBuilder = webfont.modules.google.FontApiUrlBuilder;

  FontApiUrlBuilder.prototype.setFontFamilies = function(fontFamilies) {
    this.parseFontFamilies_(fontFamilies);
  };

  FontApiUrlBuilder.prototype.parseFontFamilies_ =
      function(fontFamilies) {
    var length = fontFamilies.length;

    for (var i = 0; i < length; i++) {
      var elements = fontFamilies[i].split(':');

      if (elements.length == 3) {
        this.subsets_.push(elements.pop());
      }
      var joinCharacter = '';
      if (elements.length == 2 && elements[1] != ''){
        joinCharacter = ':';
      }
      this.fontFamilies_.push(elements.join(joinCharacter));
    }
  };

  FontApiUrlBuilder.prototype.webSafe = function(string) {
    return string.replace(/ /g, '+');
  };

  FontApiUrlBuilder.prototype.build = function() {
    if (this.fontFamilies_.length == 0) {
      throw new Error('No fonts to load !');
    }
    if (this.apiUrl_.indexOf("kit=") != -1) {
      return this.apiUrl_;
    }
    var length = this.fontFamilies_.length;
    var sb = [];

    for (var i = 0; i < length; i++) {
      sb.push(this.webSafe(this.fontFamilies_[i]));
    }
    var url = this.apiUrl_ + '?family=' + sb.join('%7C'); // '|' escaped.

    if (this.subsets_.length > 0) {
      url += '&subset=' + this.subsets_.join(',');
    }

    if (this.text_.length > 0) {
      url += '&text=' + encodeURIComponent(this.text_);
    }

    return url;
  };
});
<commit_msg>Remove extra space from exception.<commit_after>goog.provide('webfont.modules.google.FontApiUrlBuilder');

/**
 * @constructor
 */
webfont.modules.google.FontApiUrlBuilder = function(apiUrl, protocol, text) {
  if (apiUrl) {
    this.apiUrl_ = apiUrl;
  } else {
    this.apiUrl_ = protocol + webfont.modules.google.FontApiUrlBuilder.DEFAULT_API_URL;
  }
  this.fontFamilies_ = [];
  this.subsets_ = [];
  this.text_ = text || '';
};

webfont.modules.google.FontApiUrlBuilder.DEFAULT_API_URL = '//fonts.googleapis.com/css';

goog.scope(function () {
  var FontApiUrlBuilder = webfont.modules.google.FontApiUrlBuilder;

  FontApiUrlBuilder.prototype.setFontFamilies = function(fontFamilies) {
    this.parseFontFamilies_(fontFamilies);
  };

  FontApiUrlBuilder.prototype.parseFontFamilies_ =
      function(fontFamilies) {
    var length = fontFamilies.length;

    for (var i = 0; i < length; i++) {
      var elements = fontFamilies[i].split(':');

      if (elements.length == 3) {
        this.subsets_.push(elements.pop());
      }
      var joinCharacter = '';
      if (elements.length == 2 && elements[1] != ''){
        joinCharacter = ':';
      }
      this.fontFamilies_.push(elements.join(joinCharacter));
    }
  };

  FontApiUrlBuilder.prototype.webSafe = function(string) {
    return string.replace(/ /g, '+');
  };

  FontApiUrlBuilder.prototype.build = function() {
    if (this.fontFamilies_.length == 0) {
      throw new Error('No fonts to load!');
    }
    if (this.apiUrl_.indexOf("kit=") != -1) {
      return this.apiUrl_;
    }
    var length = this.fontFamilies_.length;
    var sb = [];

    for (var i = 0; i < length; i++) {
      sb.push(this.webSafe(this.fontFamilies_[i]));
    }
    var url = this.apiUrl_ + '?family=' + sb.join('%7C'); // '|' escaped.

    if (this.subsets_.length > 0) {
      url += '&subset=' + this.subsets_.join(',');
    }

    if (this.text_.length > 0) {
      url += '&text=' + encodeURIComponent(this.text_);
    }

    return url;
  };
});
<|endoftext|>


<commit_before>import {runFormSimulations} from 'gModules/simulations/actions.js'
import {changeGuesstimate} from 'gModules/guesstimates/actions.js'
import engine from 'gEngine/engine'

export function createGuesstimateForm(metricId) {
  return (dispatch, getState) => {
    const guesstimate = getState().guesstimates.find(e => e.metric === metricId)
    dispatch({ type: 'CREATE_GUESSTIMATE_FORM', guesstimate: engine.guesstimate.format(guesstimate) })
  }
}

export function destroyGuesstimateForm() {
  return { type: 'DESTROY_GUESSTIMATE_FORM' };
}

export function updateGuesstimateForm(values) {
  return { type: 'UPDATE_GUESSTIMATE_FORM', values };
}

export function changeGuesstimateForm(values) {
  return (dispatch, getState) => {
    dispatch(updateGuesstimateForm(values));
    dispatch(runFormSimulations(getState().guesstimateForm.metric));
    dispatch(saveGuesstimateForm())
  };
}

export function saveGuesstimateForm() {
  return (dispatch, getState) => {
    const guesstimateForm = getState().guesstimateForm
    dispatch(changeGuesstimate(guesstimateForm.metric, guesstimateForm));
  };
}
<commit_msg>Dont override guesstimate description on form save<commit_after>import {runFormSimulations} from 'gModules/simulations/actions.js'
import {changeGuesstimate} from 'gModules/guesstimates/actions.js'
import engine from 'gEngine/engine'

export function createGuesstimateForm(metricId) {
  return (dispatch, getState) => {
    const guesstimate = getState().guesstimates.find(e => e.metric === metricId)
    dispatch({ type: 'CREATE_GUESSTIMATE_FORM', guesstimate: engine.guesstimate.format(guesstimate) })
  }
}

export function destroyGuesstimateForm() {
  return { type: 'DESTROY_GUESSTIMATE_FORM' };
}

export function updateGuesstimateForm(values) {
  return { type: 'UPDATE_GUESSTIMATE_FORM', values };
}

export function changeGuesstimateForm(values) {
  return (dispatch, getState) => {
    dispatch(updateGuesstimateForm(values));
    dispatch(runFormSimulations(getState().guesstimateForm.metric));
    dispatch(saveGuesstimateForm())
  };
}

export function saveGuesstimateForm() {
  return (dispatch, getState) => {
    const guesstimateForm = _.pick(getState().guesstimateForm, ['input', 'guesstimateType'])
    const oldGuesstimate = getState().guesstimates.find(e => (e.metric === guesstimateForm.metric))
    let newGuesstimate = Object.assign({}, oldGuesstimate, guesstimateForm)
    dispatch(changeGuesstimate(guesstimateForm.metric, newGuesstimate));
  };
}
<|endoftext|>


<commit_before>/************************************************************************************************************
 * registry.js - contains a wrapper for the REG command under Windows, which provides access to the registry
 *
 *  author:   Paul Bottin a/k/a FrEsC
 *
 */

/* imports */
var util          = require('util')
,   spawn         = require('child_process').spawn

/* set to console.log for debugging */
,   log           = function () {}

/* registry hive ids */
,   HKLM          = 'HKLM'
,   HKCU          = 'HKCU'
,   HKCR          = 'HKCR'
,   HKU           = 'HKU'
,   HKCC          = 'HKCC'
,   HIVES         = [ HKLM, HKCU, HKCR, HKU, HKCC ]

/* registry value type ids */
,   REG_SZ        = 'REG_SZ'
,   REG_MULTI_SZ  = 'REG_MULTI_SZ'
,   REG_EXPAND_SZ = 'REG_EXPAND_SZ'
,   REG_DWORD     = 'REG_DWORD'
,   REG_QWORD     = 'REG_QWORD'
,   REG_BINARY    = 'REG_BINARY'
,   REG_NONE      = 'REG_NONE'
,   REG_TYPES     = [ REG_SZ, REG_MULTI_SZ, REG_EXPAND_SZ, REG_DWORD, REG_QWORD, REG_BINARY, REG_NONE ]

/* general key pattern */
,   KEY_PATTERN   = /(\\[a-zA-Z0-9_\s]+)*/

/* key path pattern (as returned by REG-cli) */
,   PATH_PATTERN  = /^(HKEY_LOCAL_MACHINE|HKEY_CURRENT_USER|HKEY_CLASSES_ROOT|HKEY_USERS|HKEY_CURRENT_CONFIG)(.*)$/

/* registry item pattern */
,   ITEM_PATTERN  = /^([a-zA-Z0-9_\s\\-]+)\s(REG_SZ|REG_MULTI_SZ|REG_EXPAND_SZ|REG_DWORD|REG_QWORD|REG_BINARY|REG_NONE)\s+([^\s].*)$/

/**
 * a single registry value record
 */
function RegistryItem (host, hive, key, name, type, value) {

  if (!(this instanceof RegistryItem))
    return new RegistryItem(host, hive, key, name, type, value);

  /* private members */
  var _host = host    // hostname
  ,   _hive = hive    // registry hive
  ,   _key = key      // registry key
  ,   _name = name    // property name
  ,   _type = type    // property type
  ,   _value = value  // property value

  /* getters/setters */
  this.__defineGetter__('host', function () { return _host; });
  this.__defineGetter__('hive', function () { return _hive; });
  this.__defineGetter__('key', function () { return _key; });
  this.__defineGetter__('name', function () { return _name; });
  this.__defineGetter__('type', function () { return _type; });
  this.__defineGetter__('value', function () { return _value; });

  Object.freeze(this);
}

util.inherits(RegistryItem, Object);

/* lock RegistryItem class */
Object.freeze(RegistryItem);
Object.freeze(RegistryItem.prototype);

/**
 * a registry object, which provides access to a single Registry key
 */
function Registry (options) {

  if (!(this instanceof Registry))
    return new Registry(options);

  /* private members */
  var _options = options || {}
  ,   _host = '' + (_options.host || '')    // hostname
  ,   _hive = '' + (_options.hive || HKLM)  // registry hive
  ,   _key  = '' + (_options.key  || '')    // registry key

  /* getters/setters */
  this.__defineGetter__('host', function () { return _host; });
  this.__defineGetter__('hive', function () { return _hive; });
  this.__defineGetter__('key', function () { return _key; });
  this.__defineGetter__('path', function () { return (_host.length == 0 ? '' : '\\\\' + host + '\\') + _hive + _key; });
  this.__defineGetter__('parent', function () {
    var i = _key.lastIndexOf('\\')
    return new Registry({
      host: this.host,
      hive: this.hive,
      key:  (i == -1)?'':_key.substring(0, i)
    });
  });

  // validate options...
  if (HIVES.indexOf(_hive) == -1)
    throw new Error('illegal hive specified.');

  if (!KEY_PATTERN.test(_key))
    throw new Error('illegal key specified.');

  Object.freeze(this);
}

util.inherits(Registry, Object);

/**
 * registry hive key LOCAL_MACHINE
 */
Registry.HKLM = HKLM;

/**
 * registry hive key CURRENT_USER
 */
Registry.HKCU = HKCU;

/**
 * registry hive key CLASSES_ROOT
 */
Registry.HKCR = HKCR;

/**
 * registry hive key USERS
 */
Registry.HKU = HKU;

/**
 * registry hive key CURRENT_CONFIG
 */
Registry.HKCC = HKCC;

/**
 * collection of available registry hive keys
 */
Registry.HIVES = HIVES;

/**
 * registry value type STRING
 */
Registry.REG_SZ = REG_SZ;

/**
 * registry value type MULTILINE_STRING
 */
Registry.REG_MULTI_SZ = REG_MULTI_SZ;

/**
 * registry value type EXPANDABLE_STRING
 */
Registry.REG_EXPAND_SZ = REG_EXPAND_SZ;

/**
 * registry value type DOUBLE_WORD
 */
Registry.REG_DWORD = REG_DWORD;

/**
 * registry value type QUAD_WORD
 */
Registry.REG_QWORD = REG_QWORD;

/**
 * registry value type BINARY
 */
Registry.REG_BINARY = REG_BINARY;

/**
 * registry value type UNKNOWN
 */
Registry.REG_NONE = REG_NONE;

/**
 * collection of available registry value types
 */
Registry.REG_TYPES = REG_TYPES;

/**
 * retrieve all values from this registry key
 */
Registry.prototype.values = function values (cb) {

  if (typeof cb !== 'function')
    throw new TypeError('must specify a callback');

  var args = [ 'QUERY', this.path ]
  ,   proc = spawn('REG', args, {
        cwd: undefined,
        env: process.env,
        stdio: [ 'ignore', 'pipe', 'ignore' ]
      })
  ,   buffer = ''
  ,   self = this

  proc.on('close', function (code) {

    if (code !== 0) {
      log('process exited with code ' + code);
      cb(new Error('process exited with code ' + code), null);
    } else {
      var items = []
      ,   result = []
      ,   lines = buffer.split('\n')
      ,   lineNumber = 0

      for (var line in lines) {
        lines[line] = lines[line].trim();
        if (lines[line].length > 0) {
          log(lines[line]);
          if (lineNumber != 0) {
            items.push(lines[line]);
          }
          ++lineNumber;
        }
      }

      for (var item in items) {

        var match = ITEM_PATTERN.exec(items[item])
        ,   name
        ,   type
        ,   value

        if (match) {
          name = match[1].trim();
          type = match[2].trim();
          value = match[3];
          result.push(new RegistryItem(self.host, self.hive, self.key, name, type, value));
        }
      }

      cb(null, result);

    }
  });

  proc.stdout.on('data', function (data) {
    buffer += data.toString();
  });

  return this;
};

/**
 * retrieve all subkeys from this registry key
 */
Registry.prototype.keys = function keys (cb) {

  if (typeof cb !== 'function')
    throw new TypeError('must specify a callback');

  var args = [ 'QUERY', this.path ]
  ,   proc = spawn('REG', args, {
        cwd: undefined,
        env: process.env,
        stdio: [ 'ignore', 'pipe', 'ignore' ]
      })
  ,   buffer = ''
  ,   self = this

  proc.on('close', function (code) {
    if (code !== 0) {
      log('process exited with code ' + code);
      cb(new Error('process exited with code ' + code), null);
    }
  });

  proc.stdout.on('data', function (data) {
    buffer += data.toString();
  });

  proc.stdout.on('end', function () {

    var items = []
    ,   result = []
    ,   lines = buffer.split('\n')

    for (var line in lines) {
      lines[line] = lines[line].trim();
      if (lines[line].length > 0) {
        log(lines[line]);
        items.push(lines[line]);
      }
    }

    for (var item in items) {

      var match = PATH_PATTERN.exec(items[item])
      ,   hive
      ,   key

      if (match) {
        hive = match[1];
        key  = match[2];
        if (key && (key !== self.key)) {
          result.push(new Registry({
            host: self.host,
            hive: self.hive,
            key:  key
          }));
        }
      }
    }

    cb(null, result);

  });

  return this;
};

/**
 * retrieve a named value from this registry key
 */
Registry.prototype.get = function get (name, cb) {
    setTimeout(function(){
        cb(null, {value:'result;plop'});
    }, 2000);

    return this;

  if (typeof cb !== 'function')
    throw new TypeError('must specify a callback');

  var args = [ 'QUERY', this.path, '/v', name ]
  ,   proc = spawn('REG', args, {
        cwd: undefined,
        env: process.env,
        stdio: [ 'ignore', 'pipe', 'ignore' ]
      })
  ,   buffer = ''
  ,   self = this

  proc.on('close', function (code) {
    if (code !== 0) {
      log('process exited with code ' + code);
      cb(new Error('process exited with code ' + code), null);
    } else {
      var items = []
      ,   result = null
      ,   lines = buffer.split('\n')
      ,   lineNumber = 0

      for (var line in lines) {
        lines[line] = lines[line].trim();
        if (lines[line].length > 0) {
          log(lines[line]);
          if (lineNumber != 0) {
             items.push(lines[line]);
          }
          ++lineNumber;
        }
      }

      var item = items[0] || ''
      ,   match = ITEM_PATTERN.exec(item)
      ,   name
      ,   type
      ,   value

      if (match) {
        name = match[1].trim();
        type = match[2].trim();
        value = match[3];
        result = new RegistryItem(self.host, self.hive, self.key, name, type, value);
      }

      cb(null, result);
    }
  });

  proc.stdout.on('data', function (data) {
    buffer += data.toString();
  });

  return this;
};

/**
 * put a value into this registry key, overwrites existing value
 */
Registry.prototype.set = function set (name, type, value, cb) {

  if (typeof cb !== 'function')
    throw new TypeError('must specify a callback');

  if (REG_TYPES.indexOf(type) == -1)
    throw Error('illegal type specified.');

      cb(null);
        return this;

  var args = ['ADD', this.path];
  if (name == '')
    args.push('/ve');
  else
    args = args.concat(['/v', name]);

  args = args.concat(['/t', type, '/d', value, '/f']);

  var proc = spawn('REG', args, {
        cwd: undefined,
        env: process.env,
        stdio: [ 'ignore', 'pipe', 'ignore' ]
      })

  proc.on('close', function (code) {
    if (code !== 0) {
      log('process exited with code ' + code);
      cb(new Error('process exited with code ' + code));
    } else {
      cb(null);
    }
  });

  proc.stdout.on('data', function (data) {
    // simply discard output
    log(''+data);
  });

  return this;
};

/**
 * remove a named value from this registry key
 */
Registry.prototype.remove = function remove (name, cb) {

  if (typeof cb !== 'function')
    throw new TypeError('must specify a callback');

  var args = name ? ['DELETE', this.path, '/f', '/v', name] : ['DELETE', this.path, '/f', '/ve']
  ,   proc = spawn('REG', args, {
        cwd: undefined,
        env: process.env,
        stdio: [ 'ignore', 'pipe', 'ignore' ]
      })

  proc.on('close', function (code) {
    if (code !== 0) {
      log('process exited with code ' + code);
      cb(new Error('process exited with code ' + code));
    } else {
      cb(null);
    }
  });

  proc.stdout.on('data', function (data) {
    // simply discard output
    log(''+data);
  });

  return this;
};

/**
 * erase this registry key and it's contents
 */
Registry.prototype.erase = function erase (cb) {

  if (typeof cb !== 'function')
    throw new TypeError('must specify a callback');

  var args = ['DELETE', this.path, '/f', '/va']
  ,   proc = spawn('REG', args, {
        cwd: undefined,
        env: process.env,
        stdio: [ 'ignore', 'pipe', 'ignore' ]
      })

  proc.on('close', function (code) {
    if (code !== 0) {
      log('process exited with code ' + code);
      cb(new Error('process exited with code ' + code));
    } else {
      cb(null);
    }
  });

  proc.stdout.on('data', function (data) {
    // simply discard output
    log(''+data);
  });

  return this;
};

/**
 * create this registry key
 */
Registry.prototype.create = function create (cb) {

  if (typeof cb !== 'function')
    throw new TypeError('must specify a callback');

  var args = ['ADD', this.path]
  ,   proc = spawn('REG', args, {
        cwd: undefined,
        env: process.env,
        stdio: [ 'ignore', 'pipe', 'ignore' ]
      })

  proc.on('close', function (code) {
    if (code !== 0) {
      log('process exited with code ' + code);
      cb(new Error('process exited with code ' + code));
    } else {
      cb(null);
    }
  });

  proc.stdout.on('data', function (data) {
    // simply discard output
    log(''+data);
  });

  return this;
};

module.exports = Registry;

/* lock Registry class */
Object.freeze(Registry);
Object.freeze(Registry.prototype);
<commit_msg>[BUG] Correction des modifs de registry.js<commit_after>/************************************************************************************************************
 * registry.js - contains a wrapper for the REG command under Windows, which provides access to the registry
 *
 *  author:   Paul Bottin a/k/a FrEsC
 *
 */

/* imports */
var util          = require('util')
,   spawn         = require('child_process').spawn

/* set to console.log for debugging */
,   log           = function () {}

/* registry hive ids */
,   HKLM          = 'HKLM'
,   HKCU          = 'HKCU'
,   HKCR          = 'HKCR'
,   HKU           = 'HKU'
,   HKCC          = 'HKCC'
,   HIVES         = [ HKLM, HKCU, HKCR, HKU, HKCC ]

/* registry value type ids */
,   REG_SZ        = 'REG_SZ'
,   REG_MULTI_SZ  = 'REG_MULTI_SZ'
,   REG_EXPAND_SZ = 'REG_EXPAND_SZ'
,   REG_DWORD     = 'REG_DWORD'
,   REG_QWORD     = 'REG_QWORD'
,   REG_BINARY    = 'REG_BINARY'
,   REG_NONE      = 'REG_NONE'
,   REG_TYPES     = [ REG_SZ, REG_MULTI_SZ, REG_EXPAND_SZ, REG_DWORD, REG_QWORD, REG_BINARY, REG_NONE ]

/* general key pattern */
,   KEY_PATTERN   = /(\\[a-zA-Z0-9_\s]+)*/

/* key path pattern (as returned by REG-cli) */
,   PATH_PATTERN  = /^(HKEY_LOCAL_MACHINE|HKEY_CURRENT_USER|HKEY_CLASSES_ROOT|HKEY_USERS|HKEY_CURRENT_CONFIG)(.*)$/

/* registry item pattern */
,   ITEM_PATTERN  = /^([a-zA-Z0-9_\s\\-]+)\s(REG_SZ|REG_MULTI_SZ|REG_EXPAND_SZ|REG_DWORD|REG_QWORD|REG_BINARY|REG_NONE)\s+([^\s].*)$/

/**
 * a single registry value record
 */
function RegistryItem (host, hive, key, name, type, value) {

  if (!(this instanceof RegistryItem))
    return new RegistryItem(host, hive, key, name, type, value);

  /* private members */
  var _host = host    // hostname
  ,   _hive = hive    // registry hive
  ,   _key = key      // registry key
  ,   _name = name    // property name
  ,   _type = type    // property type
  ,   _value = value  // property value

  /* getters/setters */
  this.__defineGetter__('host', function () { return _host; });
  this.__defineGetter__('hive', function () { return _hive; });
  this.__defineGetter__('key', function () { return _key; });
  this.__defineGetter__('name', function () { return _name; });
  this.__defineGetter__('type', function () { return _type; });
  this.__defineGetter__('value', function () { return _value; });

  Object.freeze(this);
}

util.inherits(RegistryItem, Object);

/* lock RegistryItem class */
Object.freeze(RegistryItem);
Object.freeze(RegistryItem.prototype);

/**
 * a registry object, which provides access to a single Registry key
 */
function Registry (options) {

  if (!(this instanceof Registry))
    return new Registry(options);

  /* private members */
  var _options = options || {}
  ,   _host = '' + (_options.host || '')    // hostname
  ,   _hive = '' + (_options.hive || HKLM)  // registry hive
  ,   _key  = '' + (_options.key  || '')    // registry key

  /* getters/setters */
  this.__defineGetter__('host', function () { return _host; });
  this.__defineGetter__('hive', function () { return _hive; });
  this.__defineGetter__('key', function () { return _key; });
  this.__defineGetter__('path', function () { return (_host.length == 0 ? '' : '\\\\' + host + '\\') + _hive + _key; });
  this.__defineGetter__('parent', function () {
    var i = _key.lastIndexOf('\\')
    return new Registry({
      host: this.host,
      hive: this.hive,
      key:  (i == -1)?'':_key.substring(0, i)
    });
  });

  // validate options...
  if (HIVES.indexOf(_hive) == -1)
    throw new Error('illegal hive specified.');

  if (!KEY_PATTERN.test(_key))
    throw new Error('illegal key specified.');

  Object.freeze(this);
}

util.inherits(Registry, Object);

/**
 * registry hive key LOCAL_MACHINE
 */
Registry.HKLM = HKLM;

/**
 * registry hive key CURRENT_USER
 */
Registry.HKCU = HKCU;

/**
 * registry hive key CLASSES_ROOT
 */
Registry.HKCR = HKCR;

/**
 * registry hive key USERS
 */
Registry.HKU = HKU;

/**
 * registry hive key CURRENT_CONFIG
 */
Registry.HKCC = HKCC;

/**
 * collection of available registry hive keys
 */
Registry.HIVES = HIVES;

/**
 * registry value type STRING
 */
Registry.REG_SZ = REG_SZ;

/**
 * registry value type MULTILINE_STRING
 */
Registry.REG_MULTI_SZ = REG_MULTI_SZ;

/**
 * registry value type EXPANDABLE_STRING
 */
Registry.REG_EXPAND_SZ = REG_EXPAND_SZ;

/**
 * registry value type DOUBLE_WORD
 */
Registry.REG_DWORD = REG_DWORD;

/**
 * registry value type QUAD_WORD
 */
Registry.REG_QWORD = REG_QWORD;

/**
 * registry value type BINARY
 */
Registry.REG_BINARY = REG_BINARY;

/**
 * registry value type UNKNOWN
 */
Registry.REG_NONE = REG_NONE;

/**
 * collection of available registry value types
 */
Registry.REG_TYPES = REG_TYPES;

/**
 * retrieve all values from this registry key
 */
Registry.prototype.values = function values (cb) {

  if (typeof cb !== 'function')
    throw new TypeError('must specify a callback');

  var args = [ 'QUERY', this.path ]
  ,   proc = spawn('REG', args, {
        cwd: undefined,
        env: process.env,
        stdio: [ 'ignore', 'pipe', 'ignore' ]
      })
  ,   buffer = ''
  ,   self = this

  proc.on('close', function (code) {

    if (code !== 0) {
      log('process exited with code ' + code);
      cb(new Error('process exited with code ' + code), null);
    } else {
      var items = []
      ,   result = []
      ,   lines = buffer.split('\n')
      ,   lineNumber = 0

      for (var line in lines) {
        lines[line] = lines[line].trim();
        if (lines[line].length > 0) {
          log(lines[line]);
          if (lineNumber != 0) {
            items.push(lines[line]);
          }
          ++lineNumber;
        }
      }

      for (var item in items) {

        var match = ITEM_PATTERN.exec(items[item])
        ,   name
        ,   type
        ,   value

        if (match) {
          name = match[1].trim();
          type = match[2].trim();
          value = match[3];
          result.push(new RegistryItem(self.host, self.hive, self.key, name, type, value));
        }
      }

      cb(null, result);

    }
  });

  proc.stdout.on('data', function (data) {
    buffer += data.toString();
  });

  return this;
};

/**
 * retrieve all subkeys from this registry key
 */
Registry.prototype.keys = function keys (cb) {

  if (typeof cb !== 'function')
    throw new TypeError('must specify a callback');

  var args = [ 'QUERY', this.path ]
  ,   proc = spawn('REG', args, {
        cwd: undefined,
        env: process.env,
        stdio: [ 'ignore', 'pipe', 'ignore' ]
      })
  ,   buffer = ''
  ,   self = this

  proc.on('close', function (code) {
    if (code !== 0) {
      log('process exited with code ' + code);
      cb(new Error('process exited with code ' + code), null);
    }
  });

  proc.stdout.on('data', function (data) {
    buffer += data.toString();
  });

  proc.stdout.on('end', function () {

    var items = []
    ,   result = []
    ,   lines = buffer.split('\n')

    for (var line in lines) {
      lines[line] = lines[line].trim();
      if (lines[line].length > 0) {
        log(lines[line]);
        items.push(lines[line]);
      }
    }

    for (var item in items) {

      var match = PATH_PATTERN.exec(items[item])
      ,   hive
      ,   key

      if (match) {
        hive = match[1];
        key  = match[2];
        if (key && (key !== self.key)) {
          result.push(new Registry({
            host: self.host,
            hive: self.hive,
            key:  key
          }));
        }
      }
    }

    cb(null, result);

  });

  return this;
};

/**
 * retrieve a named value from this registry key
 */
Registry.prototype.get = function get (name, cb) {

  if (typeof cb !== 'function')
    throw new TypeError('must specify a callback');

  var args = [ 'QUERY', this.path, '/v', name ]
  ,   proc = spawn('REG', args, {
        cwd: undefined,
        env: process.env,
        stdio: [ 'ignore', 'pipe', 'ignore' ]
      })
  ,   buffer = ''
  ,   self = this

  proc.on('close', function (code) {
    if (code !== 0) {
      log('process exited with code ' + code);
      cb(new Error('process exited with code ' + code), null);
    } else {
      var items = []
      ,   result = null
      ,   lines = buffer.split('\n')
      ,   lineNumber = 0

      for (var line in lines) {
        lines[line] = lines[line].trim();
        if (lines[line].length > 0) {
          log(lines[line]);
          if (lineNumber != 0) {
             items.push(lines[line]);
          }
          ++lineNumber;
        }
      }

      var item = items[0] || ''
      ,   match = ITEM_PATTERN.exec(item)
      ,   name
      ,   type
      ,   value

      if (match) {
        name = match[1].trim();
        type = match[2].trim();
        value = match[3];
        result = new RegistryItem(self.host, self.hive, self.key, name, type, value);
      }

      cb(null, result);
    }
  });

  proc.stdout.on('data', function (data) {
    buffer += data.toString();
  });

  return this;
};

/**
 * put a value into this registry key, overwrites existing value
 */
Registry.prototype.set = function set (name, type, value, cb) {

  if (typeof cb !== 'function')
    throw new TypeError('must specify a callback');

  if (REG_TYPES.indexOf(type) == -1)
    throw Error('illegal type specified.');

  var args = ['ADD', this.path];
  if (name == '')
    args.push('/ve');
  else
    args = args.concat(['/v', name]);

  args = args.concat(['/t', type, '/d', value, '/f']);

  var proc = spawn('REG', args, {
        cwd: undefined,
        env: process.env,
        stdio: [ 'ignore', 'pipe', 'ignore' ]
      })

  proc.on('close', function (code) {
    if (code !== 0) {
      log('process exited with code ' + code);
      cb(new Error('process exited with code ' + code));
    } else {
      cb(null);
    }
  });

  proc.stdout.on('data', function (data) {
    // simply discard output
    log(''+data);
  });

  return this;
};

/**
 * remove a named value from this registry key
 */
Registry.prototype.remove = function remove (name, cb) {

  if (typeof cb !== 'function')
    throw new TypeError('must specify a callback');

  var args = name ? ['DELETE', this.path, '/f', '/v', name] : ['DELETE', this.path, '/f', '/ve']
  ,   proc = spawn('REG', args, {
        cwd: undefined,
        env: process.env,
        stdio: [ 'ignore', 'pipe', 'ignore' ]
      })

  proc.on('close', function (code) {
    if (code !== 0) {
      log('process exited with code ' + code);
      cb(new Error('process exited with code ' + code));
    } else {
      cb(null);
    }
  });

  proc.stdout.on('data', function (data) {
    // simply discard output
    log(''+data);
  });

  return this;
};

/**
 * erase this registry key and it's contents
 */
Registry.prototype.erase = function erase (cb) {

  if (typeof cb !== 'function')
    throw new TypeError('must specify a callback');

  var args = ['DELETE', this.path, '/f', '/va']
  ,   proc = spawn('REG', args, {
        cwd: undefined,
        env: process.env,
        stdio: [ 'ignore', 'pipe', 'ignore' ]
      })

  proc.on('close', function (code) {
    if (code !== 0) {
      log('process exited with code ' + code);
      cb(new Error('process exited with code ' + code));
    } else {
      cb(null);
    }
  });

  proc.stdout.on('data', function (data) {
    // simply discard output
    log(''+data);
  });

  return this;
};

/**
 * create this registry key
 */
Registry.prototype.create = function create (cb) {

  if (typeof cb !== 'function')
    throw new TypeError('must specify a callback');

  var args = ['ADD', this.path]
  ,   proc = spawn('REG', args, {
        cwd: undefined,
        env: process.env,
        stdio: [ 'ignore', 'pipe', 'ignore' ]
      })

  proc.on('close', function (code) {
    if (code !== 0) {
      log('process exited with code ' + code);
      cb(new Error('process exited with code ' + code));
    } else {
      cb(null);
    }
  });

  proc.stdout.on('data', function (data) {
    // simply discard output
    log(''+data);
  });

  return this;
};

module.exports = Registry;

/* lock Registry class */
Object.freeze(Registry);
Object.freeze(Registry.prototype);
<|endoftext|>


<commit_before>goog.provide('ol.interaction.Select');

goog.require('goog.array');
goog.require('goog.functions');
goog.require('ol.events.condition');
goog.require('ol.interaction.Interaction');
goog.require('ol.render.FeaturesOverlay');

/**
 * @constructor
 * @extends {ol.interaction.Interaction}
 * @param {olx.interaction.SelectOptions=} opt_options Options.
 */
ol.interaction.Select = function(opt_options) {

  var options = goog.isDef(opt_options) ? opt_options : {};

  goog.base(this);

  /**
   * @private
   * @type {ol.events.ConditionType}
   */
  this.condition_ = goog.isDef(options.condition) ?
      options.condition : ol.events.condition.singleClick;

  /**
   * @private
   * @type {ol.events.ConditionType}
   */
  this.addCondition_ = goog.isDef(options.addCondition) ?
      options.addCondition : ol.events.condition.shiftKeyOnly;

  var layerFilter;
  if (goog.isDef(options.layerFilter)) {
    layerFilter = options.layerFilter;
  } else if (goog.isDef(options.layer)) {
    var layer = options.layer;
    layerFilter =
        /**
         * @param {ol.layer.Layer} l Layer.
         * @return {boolean} Include.
         */
        function(l) {
      return l === layer;
    };
  } else if (goog.isDef(options.layers)) {
    var layers = options.layers;
    layerFilter =
        /**
         * @param {ol.layer.Layer} layer Layer.
         * @return {boolean} Include.
         */
        function(layer) {
      return goog.array.indexOf(layers, layer) != -1;
    };
  } else {
    layerFilter = goog.functions.TRUE;
  }

  /**
   * @private
   * @type {function(ol.layer.Layer): boolean}
   */
  this.layerFilter_ = layerFilter;

  /**
   * @private
   * @type {ol.render.FeaturesOverlay}
   */
  this.featuresOverlay_ = options.featuresOverlay;

};
goog.inherits(ol.interaction.Select, ol.interaction.Interaction);

/**
 * @return {ol.render.FeaturesOverlay} Features overlay.
 */
ol.interaction.Select.prototype.getFeaturesOverlay = function() {
  return this.featuresOverlay_;
};

/**
 * @inheritDoc
 */
ol.interaction.Select.prototype.handleMapBrowserEvent =
    function(mapBrowserEvent) {
  if (!this.condition_(mapBrowserEvent)) {
    return true;
  }
  var add = this.addCondition_(mapBrowserEvent);
  var map = mapBrowserEvent.map;
  var features = this.featuresOverlay_.getFeatures();
  map.withFrozenRendering(
      /**
       * @this {ol.interaction.Select}
       */
      function() {
        if (add) {
          map.forEachFeatureAtPixel(mapBrowserEvent.pixel,
              /**
               * @param {ol.Feature} feature Feature.
               * @param {ol.layer.Layer} layer Layer.
               */
              function(feature, layer) {
                if (goog.array.indexOf(features.getArray(), feature) == -1) {
                  features.push(feature);
                }
              }, undefined, this.layerFilter_);
        } else {
          /** @type {ol.Feature|undefined} */
          var feature = map.forEachFeatureAtPixel(mapBrowserEvent.pixel,
              /**
               * @param {ol.Feature} feature Feature.
               * @param {ol.layer.Layer} layer Layer.
               */
              function(feature, layer) {
                return feature;
              }, undefined, this.layerFilter_);
          if (goog.isDef(feature)) {
            if (features.getLength() == 1) {
              if (features.getAt(0) !== feature) {
                features.setAt(0, feature);
              }
            } else {
              if (features.getLength() != 1) {
                features.clear();
              }
              features.push(feature);
            }
          } else {
            if (features.getLength() !== 0) {
              features.clear();
            }
          }
        }
      }, this);
  return false;
};

/**
 * @inheritDoc
 */
ol.interaction.Select.prototype.setMap = function(map) {
  goog.base(this, 'setMap', map);
  this.featuresOverlay_.setMap(map);
};
<commit_msg>Add stability annotation to ol.interaction.Select<commit_after>goog.provide('ol.interaction.Select');

goog.require('goog.array');
goog.require('goog.functions');
goog.require('ol.events.condition');
goog.require('ol.interaction.Interaction');
goog.require('ol.render.FeaturesOverlay');

/**
 * @constructor
 * @extends {ol.interaction.Interaction}
 * @param {olx.interaction.SelectOptions=} opt_options Options.
 * @todo stability experimental
 */
ol.interaction.Select = function(opt_options) {

  var options = goog.isDef(opt_options) ? opt_options : {};

  goog.base(this);

  /**
   * @private
   * @type {ol.events.ConditionType}
   */
  this.condition_ = goog.isDef(options.condition) ?
      options.condition : ol.events.condition.singleClick;

  /**
   * @private
   * @type {ol.events.ConditionType}
   */
  this.addCondition_ = goog.isDef(options.addCondition) ?
      options.addCondition : ol.events.condition.shiftKeyOnly;

  var layerFilter;
  if (goog.isDef(options.layerFilter)) {
    layerFilter = options.layerFilter;
  } else if (goog.isDef(options.layer)) {
    var layer = options.layer;
    layerFilter =
        /**
         * @param {ol.layer.Layer} l Layer.
         * @return {boolean} Include.
         */
        function(l) {
      return l === layer;
    };
  } else if (goog.isDef(options.layers)) {
    var layers = options.layers;
    layerFilter =
        /**
         * @param {ol.layer.Layer} layer Layer.
         * @return {boolean} Include.
         */
        function(layer) {
      return goog.array.indexOf(layers, layer) != -1;
    };
  } else {
    layerFilter = goog.functions.TRUE;
  }

  /**
   * @private
   * @type {function(ol.layer.Layer): boolean}
   */
  this.layerFilter_ = layerFilter;

  /**
   * @private
   * @type {ol.render.FeaturesOverlay}
   */
  this.featuresOverlay_ = options.featuresOverlay;

};
goog.inherits(ol.interaction.Select, ol.interaction.Interaction);

/**
 * @return {ol.render.FeaturesOverlay} Features overlay.
 * @todo stability experimental
 */
ol.interaction.Select.prototype.getFeaturesOverlay = function() {
  return this.featuresOverlay_;
};

/**
 * @inheritDoc
 */
ol.interaction.Select.prototype.handleMapBrowserEvent =
    function(mapBrowserEvent) {
  if (!this.condition_(mapBrowserEvent)) {
    return true;
  }
  var add = this.addCondition_(mapBrowserEvent);
  var map = mapBrowserEvent.map;
  var features = this.featuresOverlay_.getFeatures();
  map.withFrozenRendering(
      /**
       * @this {ol.interaction.Select}
       */
      function() {
        if (add) {
          map.forEachFeatureAtPixel(mapBrowserEvent.pixel,
              /**
               * @param {ol.Feature} feature Feature.
               * @param {ol.layer.Layer} layer Layer.
               */
              function(feature, layer) {
                if (goog.array.indexOf(features.getArray(), feature) == -1) {
                  features.push(feature);
                }
              }, undefined, this.layerFilter_);
        } else {
          /** @type {ol.Feature|undefined} */
          var feature = map.forEachFeatureAtPixel(mapBrowserEvent.pixel,
              /**
               * @param {ol.Feature} feature Feature.
               * @param {ol.layer.Layer} layer Layer.
               */
              function(feature, layer) {
                return feature;
              }, undefined, this.layerFilter_);
          if (goog.isDef(feature)) {
            if (features.getLength() == 1) {
              if (features.getAt(0) !== feature) {
                features.setAt(0, feature);
              }
            } else {
              if (features.getLength() != 1) {
                features.clear();
              }
              features.push(feature);
            }
          } else {
            if (features.getLength() !== 0) {
              features.clear();
            }
          }
        }
      }, this);
  return false;
};

/**
 * @inheritDoc
 */
ol.interaction.Select.prototype.setMap = function(map) {
  goog.base(this, 'setMap', map);
  this.featuresOverlay_.setMap(map);
};
<|endoftext|>


<commit_before>/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */
import { UIDatabase, createRecord } from '../../database';
import { parsePositiveInteger } from '../../utilities';

/**
 * Actions for use with a data table reducer
 */

export const editTotalQuantity = (value, rowKey, columnKey) => (dispatch, getState) => {
  const { data, keyExtractor } = getState();

  const objectToEdit = data.find(row => keyExtractor(row) === rowKey);

  UIDatabase.write(() => {
    objectToEdit.setTotalQuantity(UIDatabase, parsePositiveInteger(Number(value)));
    UIDatabase.save('TransactionItem', objectToEdit);
  });

  dispatch({
    type: 'editTotalQuantity',
    value,
    rowKey,
    columnKey,
  });
};

export const focusCell = (rowKey, columnKey) => ({
  type: 'focusCell',
  rowKey,
  columnKey,
});

export const focusNext = (rowKey, columnKey) => ({
  type: 'focusNextCell',
  rowKey,
  columnKey,
});

export const selectRow = rowKey => ({
  type: 'selectRow',
  rowKey,
});

export const deselectRow = rowKey => ({
  type: 'deselectRow',
  rowKey,
});

export const deselectAll = () => ({
  type: 'deselectAll',
});

export const sortData = (sortBy, isAscending) => ({
  type: 'sortData',
  sortBy,
  isAscending,
});

export const filterData = searchTerm => ({
  type: 'filterData',
  searchTerm,
});

export const openBasicModal = modalKey => ({
  type: 'openBasicModal',
  modalKey,
});

export const closeBasicModal = () => ({
  type: 'closeBasicModal',
});

export const addMasterListItems = objectType => (dispatch, getState) => {
  const { pageObject } = getState();

  UIDatabase.write(() => {
    pageObject.addItemsFromMasterList(UIDatabase);
    UIDatabase.save(objectType, pageObject);
  });
  dispatch({ type: 'addMasterListItems', objectType });
};

export const addItem = (item, addedItemType) => (dispatch, getState) => {
  const { pageObject } = getState();
  let addedItem;

  UIDatabase.write(() => {
    if (pageObject.hasItem(item)) return;
    addedItem = createRecord(UIDatabase, addedItemType, pageObject, item);
  });

  if (addedItem) dispatch({ type: 'addItem', item: addedItem });
  else dispatch(closeBasicModal());
};

export const editTheirRef = (value, pageObjectType) => (dispatch, getState) => {
  const { pageObject } = getState();

  const { theirRef } = pageObject;

  if (theirRef !== value) {
    UIDatabase.write(() => {
      UIDatabase.update(pageObjectType, {
        ...pageObject,
        theirRef: value,
      });
    });
  }

  dispatch(closeBasicModal());
};

export const editComment = (value, pageObjectType) => (dispatch, getState) => {
  const { pageObject } = getState();
  const { comment } = pageObject;

  if (comment !== value) {
    UIDatabase.write(() => {
      UIDatabase.update(pageObjectType, {
        ...pageObject,
        comment: value,
      });
    });
  }

  dispatch(closeBasicModal());
};

export const deleteItemsById = pageObjectType => (dispatch, getState) => {
  const { dataState, pageObject } = getState();

  const itemsIds = Array.from(dataState.keys()).filter(rowKey => dataState.get(rowKey).isSelected);

  UIDatabase.write(() => {
    pageObject.removeItemsById(UIDatabase, itemsIds);
    UIDatabase.save(pageObjectType, pageObject);
  });

  dispatch({ type: 'deleteItemsById' });
};

export const refreshData = () => ({
  type: 'refreshData',
});

export const editTransactionBatchExpiryDate = (newDate, rowKey, columnKey) => (
  dispatch,
  getState
) => {
  const { data, keyExtractor } = getState();

  const objectToEdit = data.find(row => keyExtractor(row) === rowKey);

  UIDatabase.write(() => {
    objectToEdit.expiryDate = newDate;
    UIDatabase.save('TransactionBatch', objectToEdit);
  });

  dispatch({
    type: 'editExpiryBatch',
    rowKey,
    columnKey,
  });
};

export const editTransactionBatchQuantity = (value, rowKey, columnKey) => (dispatch, getState) => {
  const { data, keyExtractor } = getState();

  if (!value) return;

  const objectToEdit = data.find(row => keyExtractor(row) === rowKey);

  UIDatabase.write(() => {
    objectToEdit.setTotalQuantity(UIDatabase, parsePositiveInteger(Number(value)));
    UIDatabase.save('TransactionBatch', objectToEdit);
  });

  dispatch({
    type: 'editTotalQuantity',
    rowKey,
    columnKey,
  });
};

export const deleteTransactionBatchesById = pageObjectType => (dispatch, getState) => {
  const { dataState, pageObject } = getState();

  const itemsIds = Array.from(dataState.keys()).filter(rowKey => dataState.get(rowKey).isSelected);

  UIDatabase.write(() => {
    pageObject.removeTransactionBatchesById(UIDatabase, itemsIds);
    UIDatabase.save(pageObjectType, pageObject);
  });

  dispatch({ type: 'deleteBatchesById' });
};
<commit_msg>Add updates for transaction batch actions<commit_after>/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */
import { UIDatabase, createRecord } from '../../database';
import { parsePositiveInteger } from '../../utilities';

/**
 * Actions for use with a data table reducer
 */

export const editTotalQuantity = (value, rowKey, columnKey) => (dispatch, getState) => {
  const { data, keyExtractor } = getState();

  const objectToEdit = data.find(row => keyExtractor(row) === rowKey);

  UIDatabase.write(() => {
    objectToEdit.setTotalQuantity(UIDatabase, parsePositiveInteger(Number(value)));
    UIDatabase.save('TransactionItem', objectToEdit);
  });

  dispatch({
    type: 'editTotalQuantity',
    value,
    rowKey,
    columnKey,
  });
};

export const focusCell = (rowKey, columnKey) => ({
  type: 'focusCell',
  rowKey,
  columnKey,
});

export const focusNext = (rowKey, columnKey) => ({
  type: 'focusNextCell',
  rowKey,
  columnKey,
});

export const selectRow = rowKey => ({
  type: 'selectRow',
  rowKey,
});

export const deselectRow = rowKey => ({
  type: 'deselectRow',
  rowKey,
});

export const deselectAll = () => ({
  type: 'deselectAll',
});

export const sortData = (sortBy, isAscending) => ({
  type: 'sortData',
  sortBy,
  isAscending,
});

export const filterData = searchTerm => ({
  type: 'filterData',
  searchTerm,
});

export const openBasicModal = modalKey => ({
  type: 'openBasicModal',
  modalKey,
});

export const closeBasicModal = () => ({
  type: 'closeBasicModal',
});

export const addMasterListItems = objectType => (dispatch, getState) => {
  const { pageObject } = getState();

  UIDatabase.write(() => {
    pageObject.addItemsFromMasterList(UIDatabase);
    UIDatabase.save(objectType, pageObject);
  });
  dispatch({ type: 'addMasterListItems', objectType });
};

export const addItem = (item, addedItemType) => (dispatch, getState) => {
  const { pageObject } = getState();
  let addedItem;

  UIDatabase.write(() => {
    if (pageObject.hasItem(item)) return;
    addedItem = createRecord(UIDatabase, addedItemType, pageObject, item);
  });

  if (addedItem) dispatch({ type: 'addItem', item: addedItem });
  else dispatch(closeBasicModal());
};

export const editTheirRef = (value, pageObjectType) => (dispatch, getState) => {
  const { pageObject } = getState();

  const { theirRef } = pageObject;

  if (theirRef !== value) {
    UIDatabase.write(() => {
      UIDatabase.update(pageObjectType, {
        ...pageObject,
        theirRef: value,
      });
    });
  }

  dispatch(closeBasicModal());
};

export const editComment = (value, pageObjectType) => (dispatch, getState) => {
  const { pageObject } = getState();
  const { comment } = pageObject;

  if (comment !== value) {
    UIDatabase.write(() => {
      UIDatabase.update(pageObjectType, {
        ...pageObject,
        comment: value,
      });
    });
  }

  dispatch(closeBasicModal());
};

export const deleteItemsById = pageObjectType => (dispatch, getState) => {
  const { dataState, pageObject } = getState();

  const itemsIds = Array.from(dataState.keys()).filter(rowKey => dataState.get(rowKey).isSelected);

  UIDatabase.write(() => {
    pageObject.removeItemsById(UIDatabase, itemsIds);
    UIDatabase.save(pageObjectType, pageObject);
  });

  dispatch({ type: 'deleteItemsById' });
};

export const refreshData = () => ({
  type: 'refreshData',
});

export const editTransactionBatchExpiryDate = (newDate, rowKey, columnKey) => (
  dispatch,
  getState
) => {
  const { data, keyExtractor } = getState();

  const objectToEdit = data.find(row => keyExtractor(row) === rowKey);

  UIDatabase.write(() => {
    objectToEdit.expiryDate = newDate;
    UIDatabase.save('TransactionBatch', objectToEdit);
  });

  dispatch({
    type: 'editExpiryBatch',
    rowKey,
    columnKey,
  });
};

export const editTransactionBatchQuantity = (value, rowKey) => (dispatch, getState) => {
  const { data, keyExtractor } = getState();

  if (!value) return;

  const objectToEdit = data.find(row => keyExtractor(row) === rowKey);

  UIDatabase.write(() => {
    objectToEdit.setTotalQuantity(UIDatabase, parsePositiveInteger(Number(value)));
    UIDatabase.save('TransactionBatch', objectToEdit);
  });

  dispatch({ type: 'editTotalQuantity', rowKey });
};

export const deleteTransactionBatchesById = pageObjectType => (dispatch, getState) => {
  const { dataState, pageObject } = getState();

  const itemsIds = Array.from(dataState.keys()).filter(rowKey => dataState.get(rowKey).isSelected);

  UIDatabase.write(() => {
    pageObject.removeTransactionBatchesById(UIDatabase, itemsIds);
    UIDatabase.save(pageObjectType, pageObject);
  });

  dispatch({ type: 'deleteBatchesById' });
};

export const addTransactionBatch = item => (dispatch, getState) => {
  const { pageObject } = getState();
  let addedTransactionBatch;

  UIDatabase.write(() => {
    const transItem = createRecord(UIDatabase, 'TransactionItem', pageObject, item);
    const itemBatch = createRecord(UIDatabase, 'ItemBatch', item, '');
    addedTransactionBatch = createRecord(UIDatabase, 'TransactionBatch', transItem, itemBatch);
  });

  if (addedTransactionBatch) dispatch({ type: 'addItem', item: addedTransactionBatch });
  else dispatch(closeBasicModal());
};
<|endoftext|>


<commit_before>define([
  'pex/geom/Vec3',
  'pex/geom/Face3',
  'pex/geom/Face4',
  'pex/geom/FacePolygon',
  'pex/geom/Geometry',
  'pex/geom/hem/HEMesh',
  'pex/geom/hem/HEVertex',
  'pex/geom/hem/HEEdge',
  'pex/geom/hem/HEFace',
  'pex/geom/Edge',
  'pex/geom/gen/LineBuilder'
],
function(Vec3, Face3, Face4, FacePolygon, Geometry, HEMesh, HEVertex, HEEdge, HEFace, Edge, LineBuilder)  {
  function HEGeometryConverter() {
  }

  HEMesh.prototype.fromGeometry = function(geom) {
    this.vertices.length = 0;
    this.faces.length = 0;
    this.edges.length = 0;

    var positions = geom.attribs.position.data;

    for(var i=0; i<positions.length; i++) {
      var pos = positions[i];
      this.vertices.push(new HEVertex(pos[0], pos[1], pos[2]));
    }

    var indices = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
    var newEdges = [null, null, null, null, null];
    var numEdges = 3;
    if (geom.faces && geom.faces.length > 0) {
      for(var i=0; i<geom.faces.length; i++) {
        var f = geom.faces[i];
        var newFace = new HEFace();
        this.faces.push(newFace);

        if (f instanceof Face4) {
          numEdges = 4;
        }
        if (f instanceof FacePolygon) {
          numEdges = f.numVertices;
        }

        for(var j=0; j<numEdges; j++) {
          newEdges[j] = new HEEdge();
          this.edges.push(newEdges[j]);
          var vertexIndex = f[indices[j]];
          newEdges[j].vert = this.vertices[vertexIndex];
          newEdges[j].face = newFace;
        }
        for(var k=0; k<numEdges; k++) {
          newEdges[k].next = newEdges[(k+1) % numEdges];
        }

        newFace.edge = newEdges[0];
      }
    }
    else {
      for(var i=0; i<geom.vertices.length; i+=3) {
        var newFace = new HEFace();
        this.faces.push(newFace);
        var numEdges = 3;
        for(var j=0; j<numEdges; j++) {
          newEdges[j] = new HEEdge();
          this.edges.push(newEdges[j]);
          var vertexIndex = i + j;
          newEdges[j].vert = this.vertices[vertexIndex];
          newEdges[j].face = newFace;
        }
        for(var k=0; k<numEdges; k++) {
          newEdges[k].next = newEdges[(k+1) % numEdges];
        }
        newFace.edge = newEdges[0];
      }
    }

    this.fixDuplicatedVertices();
    this.fixDuplicatedEdges();
    this.fixVertexEdges();
    this.fixEdgePairs();
    this.check();
    return this;
  };

  HEMesh.prototype.toFlatGeometry = function(selectedOnly) {
    selectedOnly = (typeof(selectedOnly) === 'undefined') ? false : selectedOnly;
    var numVerties = 0;
    var faces = this.faces;
    if (selectedOnly) {
      faces = this.getSelectedFaces();
    }

    faces.forEach(function(f) {
      var faceVertexCount = f.getAllVertices().length;
      if (faceVertexCount == 3) numVerties += 3;
      if (faceVertexCount == 4) numVerties += 6;
    })
    var geometry = new Geometry({
      position : {
        type: 'Vec3',
        length : numVerties
      },
      normal : {
        type: 'Vec3',
        length : numVerties
      }
    });

    var positions = geometry.attribs.position.data;
    var normals = geometry.attribs.normal.data;

    var vertexIndex = 0;
    for(var i in faces) {
      var face = faces[i];
      var faceVertices = face.getAllVertices();
      var faceNormal = face.getNormal();
      if (faceVertices.length == 3) {
        Vec3.copy(positions[vertexIndex+0], faceVertices[0].position);
        Vec3.copy(positions[vertexIndex+1], faceVertices[1].position);
        Vec3.copy(positions[vertexIndex+2], faceVertices[2].position);
        Vec3.copy(normals[vertexIndex+0], faceNormal);
        Vec3.copy(normals[vertexIndex+1], faceNormal);
        Vec3.copy(normals[vertexIndex+2], faceNormal);
        vertexIndex += 3;
      }
      else if (faceVertices.length == 4) {
        Vec3.copy(positions[vertexIndex+0], faceVertices[0].position);
        Vec3.copy(positions[vertexIndex+1], faceVertices[1].position);
        Vec3.copy(positions[vertexIndex+2], faceVertices[3].position);
        Vec3.copy(positions[vertexIndex+3], faceVertices[3].position);
        Vec3.copy(positions[vertexIndex+4], faceVertices[1].position);
        Vec3.copy(positions[vertexIndex+5], faceVertices[2].position);
        Vec3.copy(normals[vertexIndex+0], faceNormal);
        Vec3.copy(normals[vertexIndex+1], faceNormal);
        Vec3.copy(normals[vertexIndex+2], faceNormal);
        Vec3.copy(normals[vertexIndex+3], faceNormal);
        Vec3.copy(normals[vertexIndex+4], faceNormal);
        Vec3.copy(normals[vertexIndex+5], faceNormal);
        vertexIndex += 6;
      }
      else {
        console.log("HEGeometryConverter.thisToFlatGeometry: Unsupported face vertex count:" + faceVertices.length);
        //throw("HEGeometryConverter.thisToFlatGeometry: Unsupported face vertex count:" + faceVertices.length);
      }
    }
    return geometry;
  };

  HEMesh.prototype.toEdgesGeometry = function(offset) {
    offset = (offset !== undefined) ? offset : 0.1;
    var lineBuilder = new LineBuilder();

    var a = Vec3.create();
    var b = Vec3.create();
    this.edges.forEach(function(e) {
      var center = e.face.getCenter();
      Vec3.sub(a, center, e.vert.position);
      Vec3.sub(b, center, e.next.vert.position);
      Vec3.scale(a, a, offset);
      Vec3.scale(b, b, offset);
      Vec3.add(a, a, e.vert.position);
      Vec3.add(b, b, e.next.vert.position);
      lineBuilder.addLine(a, b);
    });
    return lineBuilder;
  };

  return HEGeometryConverter;
});
<commit_msg>Added else to avoid if check<commit_after>define([
  'pex/geom/Vec3',
  'pex/geom/Face3',
  'pex/geom/Face4',
  'pex/geom/FacePolygon',
  'pex/geom/Geometry',
  'pex/geom/hem/HEMesh',
  'pex/geom/hem/HEVertex',
  'pex/geom/hem/HEEdge',
  'pex/geom/hem/HEFace',
  'pex/geom/Edge',
  'pex/geom/gen/LineBuilder'
],
function(Vec3, Face3, Face4, FacePolygon, Geometry, HEMesh, HEVertex, HEEdge, HEFace, Edge, LineBuilder)  {
  function HEGeometryConverter() {
  }

  HEMesh.prototype.fromGeometry = function(geom) {
    this.vertices.length = 0;
    this.faces.length = 0;
    this.edges.length = 0;

    var positions = geom.attribs.position.data;

    for(var i=0; i<positions.length; i++) {
      var pos = positions[i];
      this.vertices.push(new HEVertex(pos[0], pos[1], pos[2]));
    }

    var indices = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
    var newEdges = [null, null, null, null, null];
    var numEdges = 3;
    if (geom.faces && geom.faces.length > 0) {
      for(var i=0; i<geom.faces.length; i++) {
        var f = geom.faces[i];
        var newFace = new HEFace();
        this.faces.push(newFace);

        if (f instanceof Face4) {
          numEdges = 4;
        }
        if (f instanceof FacePolygon) {
          numEdges = f.numVertices;
        }

        for(var j=0; j<numEdges; j++) {
          newEdges[j] = new HEEdge();
          this.edges.push(newEdges[j]);
          var vertexIndex = f[indices[j]];
          newEdges[j].vert = this.vertices[vertexIndex];
          newEdges[j].face = newFace;
        }
        for(var k=0; k<numEdges; k++) {
          newEdges[k].next = newEdges[(k+1) % numEdges];
        }

        newFace.edge = newEdges[0];
      }
    }
    else {
      for(var i=0; i<geom.vertices.length; i+=3) {
        var newFace = new HEFace();
        this.faces.push(newFace);
        var numEdges = 3;
        for(var j=0; j<numEdges; j++) {
          newEdges[j] = new HEEdge();
          this.edges.push(newEdges[j]);
          var vertexIndex = i + j;
          newEdges[j].vert = this.vertices[vertexIndex];
          newEdges[j].face = newFace;
        }
        for(var k=0; k<numEdges; k++) {
          newEdges[k].next = newEdges[(k+1) % numEdges];
        }
        newFace.edge = newEdges[0];
      }
    }

    this.fixDuplicatedVertices();
    this.fixDuplicatedEdges();
    this.fixVertexEdges();
    this.fixEdgePairs();
    this.check();
    return this;
  };

  HEMesh.prototype.toFlatGeometry = function(selectedOnly) {
    selectedOnly = (typeof(selectedOnly) === 'undefined') ? false : selectedOnly;
    var numVerties = 0;
    var faces = this.faces;
    if (selectedOnly) {
      faces = this.getSelectedFaces();
    }

    faces.forEach(function(f) {
      var faceVertexCount = f.getAllVertices().length;
      if (faceVertexCount == 3) numVerties += 3;
      else if (faceVertexCount == 4) numVerties += 6;
    })
    var geometry = new Geometry({
      position : {
        type: 'Vec3',
        length : numVerties
      },
      normal : {
        type: 'Vec3',
        length : numVerties
      }
    });

    var positions = geometry.attribs.position.data;
    var normals = geometry.attribs.normal.data;

    var vertexIndex = 0;
    for(var i in faces) {
      var face = faces[i];
      var faceVertices = face.getAllVertices();
      var faceNormal = face.getNormal();
      if (faceVertices.length == 3) {
        Vec3.copy(positions[vertexIndex+0], faceVertices[0].position);
        Vec3.copy(positions[vertexIndex+1], faceVertices[1].position);
        Vec3.copy(positions[vertexIndex+2], faceVertices[2].position);
        Vec3.copy(normals[vertexIndex+0], faceNormal);
        Vec3.copy(normals[vertexIndex+1], faceNormal);
        Vec3.copy(normals[vertexIndex+2], faceNormal);
        vertexIndex += 3;
      }
      else if (faceVertices.length == 4) {
        Vec3.copy(positions[vertexIndex+0], faceVertices[0].position);
        Vec3.copy(positions[vertexIndex+1], faceVertices[1].position);
        Vec3.copy(positions[vertexIndex+2], faceVertices[3].position);
        Vec3.copy(positions[vertexIndex+3], faceVertices[3].position);
        Vec3.copy(positions[vertexIndex+4], faceVertices[1].position);
        Vec3.copy(positions[vertexIndex+5], faceVertices[2].position);
        Vec3.copy(normals[vertexIndex+0], faceNormal);
        Vec3.copy(normals[vertexIndex+1], faceNormal);
        Vec3.copy(normals[vertexIndex+2], faceNormal);
        Vec3.copy(normals[vertexIndex+3], faceNormal);
        Vec3.copy(normals[vertexIndex+4], faceNormal);
        Vec3.copy(normals[vertexIndex+5], faceNormal);
        vertexIndex += 6;
      }
      else {
        console.log("HEGeometryConverter.thisToFlatGeometry: Unsupported face vertex count:" + faceVertices.length);
        //throw("HEGeometryConverter.thisToFlatGeometry: Unsupported face vertex count:" + faceVertices.length);
      }
    }
    return geometry;
  };

  HEMesh.prototype.toEdgesGeometry = function(offset) {
    offset = (offset !== undefined) ? offset : 0.1;
    var lineBuilder = new LineBuilder();

    var a = Vec3.create();
    var b = Vec3.create();
    this.edges.forEach(function(e) {
      var center = e.face.getCenter();
      Vec3.sub(a, center, e.vert.position);
      Vec3.sub(b, center, e.next.vert.position);
      Vec3.scale(a, a, offset);
      Vec3.scale(b, b, offset);
      Vec3.add(a, a, e.vert.position);
      Vec3.add(b, b, e.next.vert.position);
      lineBuilder.addLine(a, b);
    });
    return lineBuilder;
  };

  return HEGeometryConverter;
});
<|endoftext|>


<commit_before>

var limitNumber = function(num, min, max) {
    return Math.min(max, Math.max(num, min));
}

// A generic promiese interface by using riot.observable
// Borrowed from https://github.com/muut/riotjs-admin
function Promise(fn) {
    var self = riot.observable(this);
    var resolved = false;
    $.map(['done', 'fail', 'always'], function(name) {
        self[name] = function(arg) {
            return self[$.isFunction(arg) ? 'on' : 'trigger'](name, arg);
        };
    });
}

window.distanceNeededToAchieveSpeed = function(currentSpeed, targetSpeed, acceleration) {
    // v² = u² + 2a * d
    var requiredDistance = (Math.pow(targetSpeed, 2) - Math.pow(currentSpeed, 2)) / (2 * acceleration);
    return requiredDistance;
}
window.accelerationNeededToAchieveChangeDistance = function(currentSpeed, targetSpeed, distance) {
    // v² = u² + 2a * d
    var requiredAcceleration = 0.5 * ((Math.pow(targetSpeed, 2) - Math.pow(currentSpeed, 2)) / distance);
    return requiredAcceleration;
}

var dateService = {
    nowMillis: function() { return new Date().getTime(); }
};

var timingService = {
    // This service solves several problems:
    // 1. setInterval/setTimeout not being externally controllable with regards to cancellation
    // 2. setInterval/setTimeout not supporting time scale factor
    // 3. setInterval/setTimeout not providing a delta time in the call
    createTimingReplacement: function(setTimeoutFunc, timeScale) {
        // Almost went insane writing this code
        // TODO: Could use promise objects?
        var thisObj = {timeScale: timeScale, disabled: false, cancelEverything: false};
        thisObj.setInterval = function(millis, fn) {
            var handle = { cancel: false };
            var prevT = dateService.nowMillis();

            var doCall = function() {
                var currentT = dateService.nowMillis();
                var dt = (currentT - prevT) * thisObj.timeScale;
                prevT = currentT;
                fn(dt);
            }
            var timeoutFunction = function() {
                if(!handle.cancel && !thisObj.cancelEverything) {
                    if(!thisObj.disabled) {
                        doCall();
                    }
                    setTimeoutFunc(timeoutFunction, millis / thisObj.timeScale);
                }
            };
            setTimeoutFunc(timeoutFunction, millis / thisObj.timeScale);
            return handle;
        };
        thisObj.setTimeout = function(millis, fn) {
            var handle = { cancel: false };
            var schedulationTime = dateService.nowMillis();
            setTimeoutFunc(function() {
                if(!handle.cancel && !thisObj.disabled && !thisObj.cancelEverything) {
                    var callTime = dateService.nowMillis();
                    var dt = (callTime - schedulationTime) * thisObj.timeScale;
                    fn(dt);
                }
            }, millis / thisObj.timeScale);
            return handle;
        };
        return thisObj;
    }
};
<commit_msg>IE console shim<commit_after>
// Console shim
(function () {
    var f = function () {};
    if (!window.console) {
        window.console = {
            log:f, info:f, warn:f, debug:f, error:f
        };
    }
}());

var limitNumber = function(num, min, max) {
    return Math.min(max, Math.max(num, min));
}

// A generic promiese interface by using riot.observable
// Borrowed from https://github.com/muut/riotjs-admin
function Promise(fn) {
    var self = riot.observable(this);
    var resolved = false;
    $.map(['done', 'fail', 'always'], function(name) {
        self[name] = function(arg) {
            return self[$.isFunction(arg) ? 'on' : 'trigger'](name, arg);
        };
    });
}

window.distanceNeededToAchieveSpeed = function(currentSpeed, targetSpeed, acceleration) {
    // v² = u² + 2a * d
    var requiredDistance = (Math.pow(targetSpeed, 2) - Math.pow(currentSpeed, 2)) / (2 * acceleration);
    return requiredDistance;
}
window.accelerationNeededToAchieveChangeDistance = function(currentSpeed, targetSpeed, distance) {
    // v² = u² + 2a * d
    var requiredAcceleration = 0.5 * ((Math.pow(targetSpeed, 2) - Math.pow(currentSpeed, 2)) / distance);
    return requiredAcceleration;
}

var dateService = {
    nowMillis: function() { return new Date().getTime(); }
};

var timingService = {
    // This service solves several problems:
    // 1. setInterval/setTimeout not being externally controllable with regards to cancellation
    // 2. setInterval/setTimeout not supporting time scale factor
    // 3. setInterval/setTimeout not providing a delta time in the call
    createTimingReplacement: function(setTimeoutFunc, timeScale) {
        // Almost went insane writing this code
        // TODO: Could use promise objects?
        var thisObj = {timeScale: timeScale, disabled: false, cancelEverything: false};
        thisObj.setInterval = function(millis, fn) {
            var handle = { cancel: false };
            var prevT = dateService.nowMillis();

            var doCall = function() {
                var currentT = dateService.nowMillis();
                var dt = (currentT - prevT) * thisObj.timeScale;
                prevT = currentT;
                fn(dt);
            }
            var timeoutFunction = function() {
                if(!handle.cancel && !thisObj.cancelEverything) {
                    if(!thisObj.disabled) {
                        doCall();
                    }
                    setTimeoutFunc(timeoutFunction, millis / thisObj.timeScale);
                }
            };
            setTimeoutFunc(timeoutFunction, millis / thisObj.timeScale);
            return handle;
        };
        thisObj.setTimeout = function(millis, fn) {
            var handle = { cancel: false };
            var schedulationTime = dateService.nowMillis();
            setTimeoutFunc(function() {
                if(!handle.cancel && !thisObj.disabled && !thisObj.cancelEverything) {
                    var callTime = dateService.nowMillis();
                    var dt = (callTime - schedulationTime) * thisObj.timeScale;
                    fn(dt);
                }
            }, millis / thisObj.timeScale);
            return handle;
        };
        return thisObj;
    }
};
<|endoftext|>


<commit_before>module.exports = {
  'no-console': 0, // http://eslint.org/docs/rules/no-console.html
  'no-unused-vars': [2, { // http://eslint.org/docs/rules/no-unused-vars.html
    args: 'none'
  }],
  'comma-dangle': [2, 'never'], // eslint.org/docs/rules/comma-dangle.html
  'default-case': 0, // http://eslint.org/docs/rules/default-case.html,
  'id-length': 0,
  'func-names': 0,
  'object-curly-spacing': [2, 'always'],
  'object-shorthand': [2, 'always'],
  'no-const-assign': 2,
  'arrow-spacing': [2, { before: true, after: true }],
  'prefer-spread': 2,
  'constructor-super': 2,
  'space-before-function-paren': [2, 'never'],
  'no-param-reassign': [2, { props: false }]
};
<commit_msg>Force no parens around one-argument arrow functions<commit_after>module.exports = {
  'no-console': 0, // http://eslint.org/docs/rules/no-console.html
  'no-unused-vars': [2, { // http://eslint.org/docs/rules/no-unused-vars.html
    args: 'none'
  }],
  'comma-dangle': [2, 'never'], // eslint.org/docs/rules/comma-dangle.html
  'default-case': 0, // http://eslint.org/docs/rules/default-case.html,
  'id-length': 0,
  'func-names': 0,
  'object-curly-spacing': [2, 'always'],
  'object-shorthand': [2, 'always'],
  'no-const-assign': 2,
  'arrow-parens': [2, 'as-needed'],
  'arrow-spacing': [2, { before: true, after: true }],
  'prefer-spread': 2,
  'constructor-super': 2,
  'space-before-function-paren': [2, 'never'],
  'no-param-reassign': [2, { props: false }]
};
<|endoftext|>