<commit_before>(function (obj) {
    'use strict';
    // Layer blending functionality
    // Based on http://dev.w3.org/fxtf/compositing-1/

    // Draw a layer on top of another using the given blending mode
    // src - RGBA data of top layer
    // dst - RGBA data of bottom layer
    // opacity - top layer opacity
    // filter - compositing function to use
    function applyBlending(src, dst, opacity, filter) {
        // calculate alpha blending of filter
        // Cs/Cd - source/destination color
        // As/Ad - source/destination alpha
        function blend(Cs, Cd, As, Ad) {
            return As * (1 - Ad) * Cs + As * Ad * filter(Cs, Cd) + (1 - As) * Ad * Cd;
        }

        for (var i = 0, n = dst.length; i < n; i += 4)
        {
            var srcA = (src[i+3] / 255) * opacity;
            if (srcA === 0) {
                continue;
            }

            var dstA = dst[i+3] / 255;

            var blendAlpha = srcA + dstA - dstA * srcA;

            dst[i  ] = blend(src[i  ] / 255, dst[i  ] / 255, srcA, dstA) / blendAlpha * 255; // r
            dst[i+1] = blend(src[i+1] / 255, dst[i+1] / 255, srcA, dstA) / blendAlpha * 255; // g
            dst[i+2] = blend(src[i+2] / 255, dst[i+2] / 255, srcA, dstA) / blendAlpha * 255; // b
            dst[i+3] = blendAlpha * 255; // a
        }
    }

    // Implementations of blending filters

    function sourceOverFilter(src, dst) {
        return src;
    }

    function multiplyFilter(src, dst) {
        var mlt = src * dst;
        return Math.min(mlt, 1);
    }

    function screenFilter(src, dst) {
        var screenf = dst + src - (dst * src);
        return Math.max(screenf, 0);
    }

    function overlayFilter(src, dst) {
        return hardLightFilter(dst, src);
    }

    function dodgeFilter(src, dst) {
        if (dst === 0) {
            return 0;
        }

        if (src === 1) {
            return 1;
        }

        var dodge = dst  / (1 - src);
        return Math.min(dodge, 1);
    }

    function burnFilter(src, dst) {
        if (dst === 1) {
            return 1;
        }

        if (src === 0) {
            return 0;
        }

        var burn = 1 - ((1 - dst) / src);
        return Math.max(burn, 0);
    }

    function darkenFilter(src, dst) {
        return Math.min(src, dst);
    }

    function lightenFilter(src, dst) {
        return Math.max(src, dst);
    }

    function plusFilter(src, dst) {
        return Math.max(src + dst, 1);
    }

    function hardLightFilter(src, dst) {
        if (src < 0.5) {
            return multiplyFilter(2 * src, dst);
        } else {
            return screenFilter((2 * src) - 1, dst);
        }
    }

    function softLightFilter(src, dst) {
        if (src <= 0.5) {
            return dst - ((1 - (2 * src)) * dst * (1 - dst));
        }
        else {
            var d;

            if (dst <= 0.25) {
                d = (((16 * dst) - 12) * dst + 4) * dst;
            } else {
                d = Math.sqrt(dst);
            }

            return dst + ((2 * src) - 1) * (d - dst);
        }
    }

    function differenceFilter(src, dst) {
        return Math.abs(src - dst);
    }

    ora.blending = {
        normal: sourceOverFilter,
        multiply: multiplyFilter,
        screen: screenFilter,
        overlay: overlayFilter,
        dodge: dodgeFilter,
        burn: burnFilter,
        darken: darkenFilter,
        lighten: lightenFilter,
        plus: plusFilter,
        difference: differenceFilter,
        hardLight: hardLightFilter,
        softLight: softLightFilter,

        'svg:src-over': sourceOverFilter,
        'svg:multiply': multiplyFilter,
        'svg:screen': screenFilter,
        'svg:overlay': overlayFilter,
        'svg:color-dodge': dodgeFilter,
        'svg:color-burn': burnFilter,
        'svg:darken': darkenFilter,
        'svg:lighten': lightenFilter,
        'svg:plus': plusFilter,
        'svg:difference': differenceFilter,
        'svg:hard-light': hardLightFilter,
        'svg:soft-light': softLightFilter,

        //'svg:color'
        //'svg:luminosity'
        //'svg:hue'
        //'svg:saturation'

        blend: applyBlending
    };

})();<commit_msg>Swapped order of src/dst checks in dodge<commit_after>(function (obj) {
    'use strict';
    // Layer blending functionality
    // Based on http://dev.w3.org/fxtf/compositing-1/

    // Draw a layer on top of another using the given blending mode
    // src - RGBA data of top layer
    // dst - RGBA data of bottom layer
    // opacity - top layer opacity
    // filter - compositing function to use
    function applyBlending(src, dst, opacity, filter) {
        // calculate alpha blending of filter
        // Cs/Cd - source/destination color
        // As/Ad - source/destination alpha
        function blend(Cs, Cd, As, Ad) {
            return As * (1 - Ad) * Cs + As * Ad * filter(Cs, Cd) + (1 - As) * Ad * Cd;
        }

        for (var i = 0, n = dst.length; i < n; i += 4)
        {
            var srcA = (src[i+3] / 255) * opacity;
            if (srcA === 0) {
                continue;
            }

            var dstA = dst[i+3] / 255;

            var blendAlpha = srcA + dstA - dstA * srcA;

            dst[i  ] = blend(src[i  ] / 255, dst[i  ] / 255, srcA, dstA) / blendAlpha * 255; // r
            dst[i+1] = blend(src[i+1] / 255, dst[i+1] / 255, srcA, dstA) / blendAlpha * 255; // g
            dst[i+2] = blend(src[i+2] / 255, dst[i+2] / 255, srcA, dstA) / blendAlpha * 255; // b
            dst[i+3] = blendAlpha * 255; // a
        }
    }

    // Implementations of blending filters

    function sourceOverFilter(src, dst) {
        return src;
    }

    function multiplyFilter(src, dst) {
        var mlt = src * dst;
        return Math.min(mlt, 1);
    }

    function screenFilter(src, dst) {
        var screenf = dst + src - (dst * src);
        return Math.max(screenf, 0);
    }

    function overlayFilter(src, dst) {
        return hardLightFilter(dst, src);
    }

    function dodgeFilter(src, dst) {
        if (src === 1) {
            return 1;
        }

        if (dst === 0) {
            return 0;
        }

        var dodge = dst  / (1 - src);
        return Math.min(dodge, 1);
    }

    function burnFilter(src, dst) {
        if (dst === 1) {
            return 1;
        }

        if (src === 0) {
            return 0;
        }

        var burn = 1 - ((1 - dst) / src);
        return Math.max(burn, 0);
    }

    function darkenFilter(src, dst) {
        return Math.min(src, dst);
    }

    function lightenFilter(src, dst) {
        return Math.max(src, dst);
    }

    function plusFilter(src, dst) {
        return Math.max(src + dst, 1);
    }

    function hardLightFilter(src, dst) {
        if (src < 0.5) {
            return multiplyFilter(2 * src, dst);
        } else {
            return screenFilter((2 * src) - 1, dst);
        }
    }

    function softLightFilter(src, dst) {
        if (src <= 0.5) {
            return dst - ((1 - (2 * src)) * dst * (1 - dst));
        }
        else {
            var d;

            if (dst <= 0.25) {
                d = (((16 * dst) - 12) * dst + 4) * dst;
            } else {
                d = Math.sqrt(dst);
            }

            return dst + ((2 * src) - 1) * (d - dst);
        }
    }

    function differenceFilter(src, dst) {
        return Math.abs(src - dst);
    }

    ora.blending = {
        normal: sourceOverFilter,
        multiply: multiplyFilter,
        screen: screenFilter,
        overlay: overlayFilter,
        dodge: dodgeFilter,
        burn: burnFilter,
        darken: darkenFilter,
        lighten: lightenFilter,
        plus: plusFilter,
        difference: differenceFilter,
        hardLight: hardLightFilter,
        softLight: softLightFilter,

        'svg:src-over': sourceOverFilter,
        'svg:multiply': multiplyFilter,
        'svg:screen': screenFilter,
        'svg:overlay': overlayFilter,
        'svg:color-dodge': dodgeFilter,
        'svg:color-burn': burnFilter,
        'svg:darken': darkenFilter,
        'svg:lighten': lightenFilter,
        'svg:plus': plusFilter,
        'svg:difference': differenceFilter,
        'svg:hard-light': hardLightFilter,
        'svg:soft-light': softLightFilter,

        //'svg:color'
        //'svg:luminosity'
        //'svg:hue'
        //'svg:saturation'

        blend: applyBlending
    };

})();<|endoftext|>


<commit_before>/*
jquery-prettyselect - v1.4.1
Carlo 'kj'
2015-08-05
*/
(function(){var a;null==window.MutationObserver&&(a=function(){function a(a){this.callBack=a}return a.prototype.observe=function(a){return this.element=a,this.interval=setInterval(function(a){return function(){var b;return b=a.element.innerHTML,b!==a.oldHtml?(a.oldHtml=b,a.callBack.apply(null)):void 0}}(this),200)},a.prototype.disconnect=function(){return clearInterval(this.interval)},a}(),window.MutationObserver=a)}).call(this),function(){var a=[].slice;!function(b){var c;return c=function(){function a(a,c){var d,e,f;this.options=b.extend({},this.defaults,c),this.options.optionsSelector=this.options.onlyValuedOptions?this._.optionsSelector.onlyWithValue:this._.optionsSelector.withoutValue,this.$select=b(a).hide().wrap("
"),this.$label=b("
").html(this._.getLabel(this.$select)),d=this.$select.find(this.options.optionsSelector),f=this._.populate(d),this.$drop=b("
"+f+"
"),this.closeDrop(),this.$wrap=this.$select.parents("."+this.options.wrapClass).attr("data-prettyselect-elements",d.length).append(this.$label).append(this.$drop).on("click","li",function(a){return function(c){var d,e;if(!a.isDisabled()&&(e=unescape(b(c.currentTarget).attr("data-value")),d=a.$select.val(),d!==e))return a.$select.val(e).trigger("change")}}(this)),this.$select.on("change",function(a){return function(){var b;return b=a.$select.val().replace("'","\\'"),a.$label.html(a.$select.find("option[value = '"+b+"']").html())}}(this)),this.$label.on("click",function(a){return function(c){return a.isDropOpen()||a.isDisabled()?void 0:(c.stopPropagation(),a.showDrop(),b("html").one("click",function(){return a.closeDrop()}))}}(this)),e=window.MutationObserver,this.observer=new e(function(a){return function(){return d=a.$select.find(a.options.optionsSelector),a.$wrap.attr("data-prettyselect-elements",d.length),a.$drop.html(a._.populate(d)),0===a.$select.find("[selected]").length?a.$label.html(a._.getLabel(a.$select)):void 0}}(this)),this.observer.observe(this.$select[0],{subtree:!0,attributes:!0,attributeOldValue:!1,attributeFilter:["class"],childList:!0})}return a.prototype.defaults={wrapClass:"prettyselect-wrap",labelClass:"prettyselect-label",dropClass:"prettyselect-drop",disabledClass:"prettyselect-disabled",onlyValuedOptions:!1},a.prototype._={populate:function(a){return a.map(function(){var a,c,d;return d=escape(b(this).attr("value")),c=b(this).attr("class"),a="undefined"!=typeof c?"class='"+escape(c)+"'":"","
"+b(this).html()+"
"}).toArray().join("")},getLabel:function(a){var b;return(b=a.find("option[data-placeholder]")).length>0?b.text():a.find("option:selected").text()},optionsSelector:{onlyWithValue:'option[value][value!=""]:not([data-placeholder])',withoutValue:"option:not([data-placeholder])"}},a.prototype.destroy=function(){return this.observer.disconnect(),this.$label.detach(),this.$drop.detach(),this.$select.show().unwrap(this.options.wrapClass).removeData("PrettySelect")},a.prototype.isDisabled=function(){return"disabled"===this.$select.attr("disabled")},a.prototype.disable=function(){return this.$select.attr("disabled","disabled"),this.$wrap.addClass(this.options.disabledClass)},a.prototype.enable=function(){return this.$select.removeAttr("disabled","disabled"),this.$wrap.removeClass(this.options.disabledClass)},a.prototype.closeDrop=function(){return this.$drop.css("display","none")},a.prototype.showDrop=function(){return this.$drop.css("display","block")},a.prototype.isDropOpen=function(){return"block"===this.$drop.css("display")},a}(),b.fn.prettyselect=function(){var d,e;return e=arguments[0],d=2<=arguments.length?a.call(arguments,1):[],this.each(function(){var a,f;return a=b(this),f=a.data("PrettySelect"),f||a.data("PrettySelect",f=new c(this,e)),"string"==typeof e?f[e].apply(f,d):void 0})}}(window.jQuery||window.Zepto)}.call(this);<commit_msg>upversion<commit_after>/*
jquery-prettyselect - v1.4.2
Carlo 'kj'
2015-08-05
*/
(function(){var a;null==window.MutationObserver&&(a=function(){function a(a){this.callBack=a}return a.prototype.observe=function(a){return this.element=a,this.interval=setInterval(function(a){return function(){var b;return b=a.element.innerHTML,b!==a.oldHtml?(a.oldHtml=b,a.callBack.apply(null)):void 0}}(this),200)},a.prototype.disconnect=function(){return clearInterval(this.interval)},a}(),window.MutationObserver=a)}).call(this),function(){var a=[].slice;!function(b){var c;return c=function(){function a(a,c){var d,e,f;this.options=b.extend({},this.defaults,c),this.options.optionsSelector=this.options.onlyValuedOptions?this._.optionsSelector.onlyWithValue:this._.optionsSelector.withoutValue,this.$select=b(a).hide().wrap("
"),this.$label=b("
").html(this._.getLabel(this.$select)),d=this.$select.find(this.options.optionsSelector),f=this._.populate(d),this.$drop=b("
"+f+"
"),this.closeDrop(),this.$wrap=this.$select.parents("."+this.options.wrapClass).attr("data-prettyselect-elements",d.length).append(this.$label).append(this.$drop).on("click","li",function(a){return function(c){var d,e;if(!a.isDisabled()&&(e=unescape(b(c.currentTarget).attr("data-value")),d=a.$select.val(),d!==e))return a.$select.val(e).trigger("change")}}(this)),this.$select.on("change",function(a){return function(){var b;return b=a.$select.val().replace("'","\\'"),a.$label.html(a.$select.find("option[value = '"+b+"']").html())}}(this)),this.$label.on("click",function(a){return function(c){return a.isDropOpen()||a.isDisabled()?void 0:(c.stopPropagation(),a.showDrop(),b("html").one("click",function(){return a.closeDrop()}))}}(this)),e=window.MutationObserver,this.observer=new e(function(a){return function(){return d=a.$select.find(a.options.optionsSelector),a.$wrap.attr("data-prettyselect-elements",d.length),a.$drop.html(a._.populate(d)),0===a.$select.find("[selected]").length?a.$label.html(a._.getLabel(a.$select)):void 0}}(this)),this.observer.observe(this.$select[0],{subtree:!0,attributes:!0,attributeOldValue:!1,attributeFilter:["class"],childList:!0})}return a.prototype.defaults={wrapClass:"prettyselect-wrap",labelClass:"prettyselect-label",dropClass:"prettyselect-drop",disabledClass:"prettyselect-disabled",onlyValuedOptions:!1},a.prototype._={populate:function(a){return a.map(function(){var a,c,d;return d=escape(b(this).attr("value")),c=b(this).attr("class"),a="undefined"!=typeof c?"class='"+escape(c)+"'":"","
"+b(this).html()+"
"}).toArray().join("")},getLabel:function(a){var b;return(b=a.find("option[data-placeholder]")).length>0?b.text():a.find("option:selected").text()},optionsSelector:{onlyWithValue:'option[value][value!=""]:not([data-placeholder])',withoutValue:"option:not([data-placeholder])"}},a.prototype.destroy=function(){return this.observer.disconnect(),this.$label.detach(),this.$drop.detach(),this.$select.show().unwrap(this.options.wrapClass).removeData("PrettySelect")},a.prototype.isDisabled=function(){return"disabled"===this.$select.attr("disabled")},a.prototype.disable=function(){return this.$select.attr("disabled","disabled"),this.$wrap.addClass(this.options.disabledClass)},a.prototype.enable=function(){return this.$select.removeAttr("disabled","disabled"),this.$wrap.removeClass(this.options.disabledClass)},a.prototype.closeDrop=function(){return this.$drop.css("display","none")},a.prototype.showDrop=function(){return this.$drop.css("display","block")},a.prototype.isDropOpen=function(){return"block"===this.$drop.css("display")},a}(),b.fn.prettyselect=function(){var d,e;return e=arguments[0],d=2<=arguments.length?a.call(arguments,1):[],this.each(function(){var a,f;return a=b(this),f=a.data("PrettySelect"),f||a.data("PrettySelect",f=new c(this,e)),"string"==typeof e?f[e].apply(f,d):void 0})}}(window.jQuery||window.Zepto)}.call(this);<|endoftext|>


<commit_before>/*
 *  jQuery SimpleImageHover - v0.1
 *  SimpleImageHover jQuery plugin.
 *  http://jqueryboilerplate.com
 *
 *  Made by Robert Pragai
 *  Under MIT License
 */
/*
 *  jQuery SimpleImageHover - v0.1
 *  A minimalistic image hover jquery plugin.
 *  http://abasys.hu/hoverImage
 *
 *  Made by Robert Pragai
 *  Under MIT License
 */
;(function ( $, window, document, undefined ) {

    $.fn.SimpleImageHover = function(options) {
		var defaults = {
		    originalpane: "hoverimage_pane",
		    ratio: 2,
		    placement: "outside",
		},
		options = options || {};

	    var pluginName = "SimpleImageHover",
	    opts = $.extend( {}, defaults, options );

		if (opts.placement == "outside" && $("#"+opts.originalpane).length ==0)
			$("body").append("

");

	    if (opts.placement == "outside") {

	    	return this.each(function() {
	    		var el = $(this);

		 		var origpane = $("#"+opts.originalpane);
				var img = $("#"+opts.originalpane+" img");

		 		el.mousemove(function(e){
					var elem = $(this);
					origpane.offset({ left:e.pageX+5, top:e.pageY+5 });
				});

				el.hover(function(e){
					img.attr("src",el.attr("src"));
					img.height(el.height()*opts.ratio).width(el.width()*opts.ratio);
					origpane.height(el.height()*opts.ratio).width(el.width()*opts.ratio);
					origpane.show();
				},function(e){
					origpane.hide();
				});
			});
		}
		else if (opts.placement == "inside") {
	    	return this.each(function(index) {
	    		var el = $(this);
	    		el.data({width:el.width(),height:el.height()});
				el.hover(function() {
						el.css("z-index", 1);
						el.animate({
							height: el.height()*opts.ratio,
							width: el.width()*opts.ratio,
							left: "-="+(opts.width-el.data("width"))/2,
							top: "-="+(opts.height-el.data("height"))/2
		            	}, "fast");
			        }, function() {
						el.css("z-index", 0);
						el.animate({
							height: el.data("height"),
							width: el.data("width"),
							left: "+="+(opts.width-el.data("width"))/2,
							top: "+="+(opts.height-el.data("height"))/2
			            }, "slow");
				    });
			});
		}
    }

})( jQuery, window, document );
<commit_msg>type fix<commit_after>/*
 *  jQuery SimpleImageHover - v0.1
 *  SimpleImageHover jQuery plugin.
 *  http://jqueryboilerplate.com
 *
 *  Made by Robert Pragai
 *  Under MIT License
 */
/*
 *  jQuery SimpleImageHover - v0.1
 *  A minimalistic image hover jquery plugin.
 *  http://abasys.hu/hoverImage
 *
 *  Made by Robert Pragai
 *  Under MIT License
 */
;(function ( $, window, document, undefined ) {

    $.fn.SimpleImageHover = function(options) {
		var defaults = {
		    originalpane: "hoverimage_pane",
		    ratio: 2,
		    placement: "outside",
		},
		options = options || {};

	    var pluginName = "SimpleImageHover",
	    opts = $.extend( {}, defaults, options );

		if (opts.placement == "outside" && $("#"+opts.originalpane).length ==0)
			$("body").append("

");

	    if (opts.placement == "outside") {

	    	return this.each(function() {
	    		var el = $(this);

		 		var origpane = $("#"+opts.originalpane);
				var img = $("#"+opts.originalpane+" img");

		 		el.mousemove(function(e){
					var elem = $(this);
					origpane.offset({ left:e.pageX+5, top:e.pageY+5 });
				});

				el.hover(function(e){
					img.attr("src",el.attr("src"));
					img.height(el.height()*opts.ratio).width(el.width()*opts.ratio);
					origpane.height(el.height()*opts.ratio).width(el.width()*opts.ratio);
					origpane.show();
				},function(e){
					origpane.hide();
				});
			});
		}
		else if (opts.placement == "inside") {
	    	return this.each(function(index) {
	    		var el = $(this);
	    		el.data({width:el.width(),height:el.height()});
				el.hover(function() {
						el.css("z-index", 1);
						el.animate({
							height: el.height()*opts.ratio,
							width: el.width()*opts.ratio,
							left: "-="+(opts.width-el.data("width"))/2,
							top: "-="+(opts.height-el.data("height"))/2
		            	}, "fast");
			        }, function() {
						el.css("z-index", 0);
						el.animate({
							height: el.data("height"),
							width: el.data("width"),
							left: "+="+(opts.width-el.data("width"))/2,
							top: "+="+(opts.height-el.data("height"))/2
			            }, "slow");
				    });
			});
		}
    }

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


<commit_before>(function () {
    var r = new RegExp("(^|(.*?\\/))(include-leaflet\.js)(\\?|$)"),
        s = document.getElementsByTagName('script'), targetScript;
    for (var i = 0; i < s.length; i++) {
        var src = s[i].getAttribute('src');
        if (src) {
            var m = src.match(r);
            if (m) {
                targetScript = s[i];
                break;
            }
        }
    }

    function inputScript(url) {
        var script = '<script type="text/javascript" src="' + url + '"><' + '/script>';
        document.writeln(script);
    }

    function inputCSS(url) {
        var css = '<link rel="stylesheet" href="' + url + '">';
        document.writeln(css);
    }

    function inArray(arr, item) {
        for (i in arr) {
            if (arr[i] == item) {
                return true;
            }
        }
        return false;
    }

    function supportES6() {
        var code = "'use strict'; class Foo {}; class Bar extends Foo {};";
        try {
            (new Function(code))();
        } catch (err) {
            return false;
        }
        if (!Array.from) {
            return false;
        }
        return true;
    }

    //加载类库资源文件
    function load() {
        var includes = (targetScript.getAttribute('include') || "").split(",");
        var excludes = (targetScript.getAttribute('exclude') || "").split(",");
        if (!inArray(excludes, 'leaflet')) {
            inputCSS("https://cdn.bootcss.com/leaflet/1.3.1/leaflet.css");
            inputScript("https://cdn.bootcss.com/leaflet/1.3.1/leaflet.js");
        }
        if (inArray(includes, 'mapv')) {
            inputScript("http://mapv.baidu.com/build/mapv.min.js");
        }
        if (inArray(includes, 'turf')) {
            inputScript("https://cdn.bootcss.com/Turf.js/5.1.6/turf.js");
        }
        if (inArray(includes, 'echarts')) {
            inputScript("https://cdn.bootcss.com/echarts/4.1.0/echarts.min.js");
        }
        if (inArray(includes, 'd3')) {
            inputScript("http://iclient.supermap.io/web/libs/d3/5.5.0/d3.min.js");
        }
        if (inArray(includes, 'd3-hexbin')) {
            inputScript("https://d3js.org/d3-hexbin.v0.2.min.js");
        }
        if (inArray(includes, 'd3Layer')) {
            inputScript("http://iclient.supermap.io/libs/leaflet/plugins/leaflet.d3Layer/leaflet-d3Layer.min.js");
        }
        if (inArray(includes, 'elasticsearch')) {
            inputScript("http://cdn.bootcss.com/elasticsearch/15.0.0/elasticsearch.min.js");
        }
        if (inArray(includes, 'deck')) {
            inputScript("http://iclient.supermap.io/web/libs/deck.gl/5.1.3/deck.gl.js");
        }
        if (!inArray(excludes, 'iclient9-leaflet') && !inArray(includes, 'iclient9-plot-leaflet')) {
            if (supportES6()) {
                inputScript("../../dist/leaflet/iclient9-leaflet-es6.js");
            } else {
                inputScript("../../dist/leaflet/iclient9-leaflet.js");
            }
        }
        if (inArray(includes, 'iclient9-leaflet-css')) {
            inputCSS("../../dist/leaflet/iclient9-leaflet.min.css");
        }
        if (inArray(includes, 'iclient9-plot-leaflet')) {
            inputScript("../../dist/leaflet/iclient9-leaflet.min.js");
            inputScript("../../dist/leaflet/iclient9-plot-leaflet.min.js");
        }
        if (inArray(includes, 'leaflet.heat')) {
            inputScript("http://cdn.bootcss.com/leaflet.heat/0.2.0/leaflet-heat.js");
        }
        if (inArray(includes, 'osmbuildings')) {
            inputScript("http://iclient.supermap.io/web/libs/osmbuildings/OSMBuildings-Leaflet.js");
        }
        if (inArray(includes, 'leaflet.markercluster')) {
            inputCSS("https://cdn.bootcss.com/leaflet.markercluster/1.3.0/MarkerCluster.Default.css");
            inputCSS("https://cdn.bootcss.com/leaflet.markercluster/1.3.0/MarkerCluster.css");
            inputScript("https://cdn.bootcss.com/leaflet.markercluster/1.3.0/leaflet.markercluster.js");
        }
        if (inArray(includes, 'leaflet-icon-pulse')) {
            inputCSS("http://iclient.supermap.io/libs/leaflet/plugins/leaflet-icon-pulse/L.Icon.Pulse.css");
            inputScript("http://iclient.supermap.io/libs/leaflet/plugins/leaflet-icon-pulse/L.Icon.Pulse.js");
        }
        if (inArray(includes, 'leaflet.draw')) {
            inputCSS("http://iclient.supermap.io/web/libs/leaflet/plugins/leaflet.draw/1.0.2/leaflet.draw.css");
            inputScript("http://cdn.bootcss.com/leaflet.draw/1.0.2/leaflet.draw.js");
        }
        if (inArray(includes, 'leaflet.pm')) {
            inputCSS("http://iclient.supermap.io/web/libs/leaflet/plugins/leaflet.pm/0.25.0/leaflet.pm.css");
            inputScript("http://iclient.supermap.io/web/libs/leaflet/plugins/leaflet.pm/0.25.0/leaflet.pm.min.js");
        }
        if (inArray(includes, 'leaflet.miniMap')) {
            inputCSS("http://iclient.supermap.io/web/libs/leaflet/plugins/leaflet-miniMap/3.6.1/dist/Control.MiniMap.min.css");
            inputScript("http://iclient.supermap.io/web/libs/leaflet/plugins/leaflet-miniMap/3.6.1/dist/Control.MiniMap.min.js");
        }
        if (inArray(includes, 'leaflet.sidebyside')) {
            inputScript("http://iclient.supermap.io/libs/leaflet/plugins/leaflet-side-by-side/leaflet-side-by-side.min.js");
        }
    }

    load();
    window.isLocal = false;
    window.server = document.location.toString().match(/file:\/\//) ? "http://localhost:8090" : document.location.protocol + "//" + document.location.host;
})();
<commit_msg>修改引用方式<commit_after>(function () {
    var r = new RegExp("(^|(.*?\\/))(include-leaflet\.js)(\\?|$)"),
        s = document.getElementsByTagName('script'), targetScript;
    for (var i = 0; i < s.length; i++) {
        var src = s[i].getAttribute('src');
        if (src) {
            var m = src.match(r);
            if (m) {
                targetScript = s[i];
                break;
            }
        }
    }

    function inputScript(url) {
        var script = '<script type="text/javascript" src="' + url + '"><' + '/script>';
        document.writeln(script);
    }

    function inputCSS(url) {
        var css = '<link rel="stylesheet" href="' + url + '">';
        document.writeln(css);
    }

    function inArray(arr, item) {
        for (i in arr) {
            if (arr[i] == item) {
                return true;
            }
        }
        return false;
    }

    function supportES6() {
        var code = "'use strict'; class Foo {}; class Bar extends Foo {};";
        try {
            (new Function(code))();
        } catch (err) {
            return false;
        }
        if (!Array.from) {
            return false;
        }
        return true;
    }

    //加载类库资源文件
    function load() {
        var includes = (targetScript.getAttribute('include') || "").split(",");
        var excludes = (targetScript.getAttribute('exclude') || "").split(",");
        if (!inArray(excludes, 'leaflet')) {
            inputCSS("https://cdn.bootcss.com/leaflet/1.3.1/leaflet.css");
            inputScript("https://cdn.bootcss.com/leaflet/1.3.1/leaflet.js");
        }
        if (inArray(includes, 'mapv')) {
            inputScript("http://mapv.baidu.com/build/mapv.min.js");
        }
        if (inArray(includes, 'turf')) {
            inputScript("https://cdn.bootcss.com/Turf.js/5.1.6/turf.js");
        }
        if (inArray(includes, 'echarts')) {
            inputScript("https://cdn.bootcss.com/echarts/4.1.0/echarts.min.js");
        }
        if (inArray(includes, 'd3')) {
            inputScript("http://iclient.supermap.io/web/libs/d3/5.5.0/d3.min.js");
        }
        if (inArray(includes, 'd3-hexbin')) {
            inputScript("https://d3js.org/d3-hexbin.v0.2.min.js");
        }
        if (inArray(includes, 'd3Layer')) {
            inputScript("http://iclient.supermap.io/libs/leaflet/plugins/leaflet.d3Layer/leaflet-d3Layer.min.js");
        }
        if (inArray(includes, 'elasticsearch')) {
            inputScript("http://cdn.bootcss.com/elasticsearch/15.0.0/elasticsearch.min.js");
        }
        if (inArray(includes, 'deck')) {
            inputScript("http://iclient.supermap.io/web/libs/deck.gl/5.1.3/deck.gl.js");
        }
        if (!inArray(excludes, 'iclient9-leaflet')) {
            if (supportES6() && !inArray(includes, 'iclient9-plot-leaflet')) {
                inputScript("../../dist/leaflet/iclient9-leaflet-es6.js");
            } else {
                inputScript("../../dist/leaflet/iclient9-leaflet.js");
            }
        }
        if (inArray(includes, 'iclient9-leaflet-css')) {
            inputCSS("../../dist/leaflet/iclient9-leaflet.min.css");
        }
        if (inArray(includes, 'iclient9-plot-leaflet')) {
            inputScript("../../dist/leaflet/iclient9-plot-leaflet.min.js");
        }
        if (inArray(includes, 'leaflet.heat')) {
            inputScript("http://cdn.bootcss.com/leaflet.heat/0.2.0/leaflet-heat.js");
        }
        if (inArray(includes, 'osmbuildings')) {
            inputScript("http://iclient.supermap.io/web/libs/osmbuildings/OSMBuildings-Leaflet.js");
        }
        if (inArray(includes, 'leaflet.markercluster')) {
            inputCSS("https://cdn.bootcss.com/leaflet.markercluster/1.3.0/MarkerCluster.Default.css");
            inputCSS("https://cdn.bootcss.com/leaflet.markercluster/1.3.0/MarkerCluster.css");
            inputScript("https://cdn.bootcss.com/leaflet.markercluster/1.3.0/leaflet.markercluster.js");
        }
        if (inArray(includes, 'leaflet-icon-pulse')) {
            inputCSS("http://iclient.supermap.io/libs/leaflet/plugins/leaflet-icon-pulse/L.Icon.Pulse.css");
            inputScript("http://iclient.supermap.io/libs/leaflet/plugins/leaflet-icon-pulse/L.Icon.Pulse.js");
        }
        if (inArray(includes, 'leaflet.draw')) {
            inputCSS("http://iclient.supermap.io/web/libs/leaflet/plugins/leaflet.draw/1.0.2/leaflet.draw.css");
            inputScript("http://cdn.bootcss.com/leaflet.draw/1.0.2/leaflet.draw.js");
        }
        if (inArray(includes, 'leaflet.pm')) {
            inputCSS("http://iclient.supermap.io/web/libs/leaflet/plugins/leaflet.pm/0.25.0/leaflet.pm.css");
            inputScript("http://iclient.supermap.io/web/libs/leaflet/plugins/leaflet.pm/0.25.0/leaflet.pm.min.js");
        }
        if (inArray(includes, 'leaflet.miniMap')) {
            inputCSS("http://iclient.supermap.io/web/libs/leaflet/plugins/leaflet-miniMap/3.6.1/dist/Control.MiniMap.min.css");
            inputScript("http://iclient.supermap.io/web/libs/leaflet/plugins/leaflet-miniMap/3.6.1/dist/Control.MiniMap.min.js");
        }
        if (inArray(includes, 'leaflet.sidebyside')) {
            inputScript("http://iclient.supermap.io/libs/leaflet/plugins/leaflet-side-by-side/leaflet-side-by-side.min.js");
        }
    }

    load();
    window.isLocal = false;
    window.server = document.location.toString().match(/file:\/\//) ? "http://localhost:8090" : document.location.protocol + "//" + document.location.host;
})();
<|endoftext|>


<commit_before>var system = require('system');
var args = system.args;
var url = args[1];

var page = require('webpage').create();
page.viewportSize = {
  width: 800,
  height: 600,
};
page.clipRect = {
  top: 0,
  left: 0,
  width: 800,
  height: 600
};
page.open(url, function() {
  console.log(page.renderBase64('png'));
  phantom.exit();
});
<commit_msg>Nicer page renderer<commit_after>// See dnstwist.py's validate_domain().
function validateUrlArg(url) {
  if (url.length > 255 || url.length === 0) {
    return false;
  }

  if (url[url.length - 1] === '.') {
    url = url.slice(0, -1);
  }

  var urlValidation = /^http:\/\/([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/;
  return urlValidation.test(url);
}

try {

  var page = require('webpage').create();
  page.viewportSize = { width: 800, height: 600 };
  page.clipRect = { top: 0, left: 0, width: 800, height: 600 };

  var system = require('system');
  var args = system.args;
  if (args.length !== 2) {
    phantom.exit();
  }

  var url = args[1];

  if (validateUrlArg(url) !== true) {
    phantom.exit();
  }

  page.open(url, function() {
    console.log(page.renderBase64('png'));
    phantom.exit();
  });

}
catch (err) {
  phantom.exit();
}
<|endoftext|>


<commit_before>import React, { Component } from 'react';

import AsyncSelect from '../../src/Async';
import { colourOptions } from '../data';

type State = {
  inputValue: string,
};

const filterColors = (inputValue: string) => {
  if (inputValue) {
    return colourOptions.filter(i =>
        i.label.toLowerCase().includes(inputValue.toLowerCase())
      );
  }
};

const promiseOptions = inputValue =>
  new Promise(resolve => {
    setTimeout(() => {
      resolve(filterColors(inputValue));
    }, 1000);
  });

export default class WithPromises extends Component<*, State> {
  state = { inputValue: '' };
  handleInputChange = (newValue: string) => {
    const inputValue = newValue.replace(/\W/g, '');
    this.setState({ inputValue });
    return inputValue;
  };
  render() {
    return (
      <AsyncSelect cacheOptions defaultOptions={colourOptions} loadOptions={promiseOptions} />
    );
  }
}
<commit_msg>Forgotten use case<commit_after>import React, { Component } from 'react';

import AsyncSelect from '../../src/Async';
import { colourOptions } from '../data';

type State = {
  inputValue: string,
};

const filterColors = (inputValue: string) => {
  if (inputValue) {
    return colourOptions.filter(i =>
        i.label.toLowerCase().includes(inputValue.toLowerCase())
      );
  }
  return colourOptions;
};

const promiseOptions = inputValue =>
  new Promise(resolve => {
    setTimeout(() => {
      resolve(filterColors(inputValue));
    }, 1000);
  });

export default class WithPromises extends Component<*, State> {
  state = { inputValue: '' };
  handleInputChange = (newValue: string) => {
    const inputValue = newValue.replace(/\W/g, '');
    this.setState({ inputValue });
    return inputValue;
  };
  render() {
    return (
      <AsyncSelect cacheOptions defaultOptions={colourOptions} loadOptions={promiseOptions} />
    );
  }
}
<|endoftext|>


<commit_before>import {Box, Breadcrumb, Button, Flex, Grid, Heading, Link, TabNav, Text} from '@primer/components'
import {Container, Head, Header, Sidebar} from '@primer/gatsby-theme-doctocat'
import Code from '@primer/gatsby-theme-doctocat/src/components/code'
import {H2, H3} from '@primer/gatsby-theme-doctocat/src/components/heading'
import Paragraph from '@primer/gatsby-theme-doctocat/src/components/paragraph'
import blobStream from 'blob-stream'
import copy from 'copy-to-clipboard'
import download from 'downloadjs'
import {Link as GatsbyLink} from 'gatsby'
import {pascalCase} from 'pascal-case'
import PDFDocument from 'pdfkit/js/pdfkit.standalone'
import React from 'react'
import svgToPdf from 'svg-to-pdfkit'
import Icon from '../components/icon'
import IconViewer from '../components/icon-viewer'
import UIExamples16 from '../components/ui-examples-16'
import UIExamples24 from '../components/ui-examples-24'

export default function IconPage({pageContext}) {
  const icon = {
    name: pageContext.name,
    keywords: pageContext.keywords,
    width: pageContext.width,
    height: pageContext.height,
    path: pageContext.svgPath
  }
  const svg = getSvg(icon)
  const [pdf, setPdf] = React.useState(null)

  React.useEffect(
    () => {
      getPdf(icon).then(blob => setPdf(blob))
    },
    [pageContext]
  )

  const [copied, setCopied] = React.useState(false)

  React.useEffect(
    () => {
      const timeout = setTimeout(() => {
        if (copied) setCopied(false)
      }, 1000)

      return () => clearTimeout(timeout)
    },
    [copied]
  )

  return (
    <Flex flexDirection="column" minHeight="100vh">

      <Flex flex="1 1 auto" flexDirection="row" css={{zIndex: 0}}>
        <Box display={['none', null, null, 'block']}>
          <Sidebar />
        </Box>
        <Container>
          <Breadcrumb>
            <Breadcrumb.Item as={GatsbyLink} to="/">
              Octicons
            </Breadcrumb.Item>
            <Breadcrumb.Item as={GatsbyLink} to={`/${icon.name}-${icon.height}`} selected>
              {icon.name}
            </Breadcrumb.Item>
          </Breadcrumb>
          <Heading as="h1" mt={2} mb={3}>
            {icon.name}
          </Heading>
          <TabNav mb={4}>
            {pageContext.heights.map(height => (
              <TabNav.Link
                key={height}
                as={GatsbyLink}
                to={`/${icon.name}-${height}`}
                selected={height === icon.height}
              >
                {height}
                px
              </TabNav.Link>
            ))}
          </TabNav>

          <IconViewer>
            <Icon width={icon.width} height={icon.height} path={icon.path} />
          </IconViewer>

          <Grid mt={3} gridGap={3} gridTemplateColumns={[null, 'repeat(3, 1fr)']}>
            <Button
              onClick={() => {
                copy(svg)
                setCopied(true)
              }}
            >
              {copied ? 'Copied' : 'Copy SVG'}
            </Button>
            <Button onClick={() => download(svg, `${pageContext.name}.svg`, 'image/svg+xml')}>Download SVG</Button>
            <Button disabled={!pdf} onClick={() => download(pdf, `${pageContext.name}.pdf`, 'application/pdf')}>
              Download PDF
            </Button>
          </Grid>

Usage

          <Paragraph>
            You can use the{' '}
            <Link to="https://primer.style/view-components/components/octicon">
              Octicon View Component
            </Link>
            ,{' '}
            <Link as={GatsbyLink} to="/packages/jekyll">
              Jekyll helper
            </Link>
            , or{' '}
            <Link as={GatsbyLink} to="/packages/react">
              React package
            </Link>{' '}
            to include Octicons on your site. Below are code examples for each:
          </Paragraph>

Octicon View Component

          {`<%= render(Primer::OcticonComponent.new(:"${pageContext.name}")) %>`}

Jekyll

          {`{% octicon ${pageContext.name} height:${icon.height} %}`}

React

          {`<${pascalCase(pageContext.name)}Icon size={${icon.height}} />`}

UI examples

          <UIExamples
            size={icon.height}
            icon={props => <Icon width={icon.width} height={icon.height} path={icon.path} {...props} />}
          />
        </Container>
      </Flex>
    </Flex>
  )
}

function UIExamples({size, icon}) {
  switch (size) {
    case 16:
      return <UIExamples16 icon={icon} />
    case 24:
      return <UIExamples24 icon={icon} />
    default:
      return <Text>No examples available</Text>
  }
}

function getSvg(icon) {
  // eslint-disable-next-line github/unescaped-html-literal
  return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${icon.width} ${icon.height}" width="${
    icon.width
  }" height="${icon.height}">${icon.path}</svg>`
}

function getPdf(icon) {
  const svg = getSvg(icon)
  return new Promise(resolve => {
    const doc = new PDFDocument({size: [icon.width, icon.height]})
    const stream = doc.pipe(blobStream())
    svgToPdf(doc, svg, 0, 0, {assumePt: true})
    doc.end()
    stream.on('finish', function() {
      resolve(stream.toBlob('application/pdf'))
    })
  })
}
<commit_msg>Update icon-page.js<commit_after>import {Box, Breadcrumb, Button, Flex, Grid, Heading, Link, TabNav, Text} from '@primer/components'
import {Container, Head, Header, Sidebar} from '@primer/gatsby-theme-doctocat'
import Code from '@primer/gatsby-theme-doctocat/src/components/code'
import {H2, H3} from '@primer/gatsby-theme-doctocat/src/components/heading'
import Paragraph from '@primer/gatsby-theme-doctocat/src/components/paragraph'
import blobStream from 'blob-stream'
import copy from 'copy-to-clipboard'
import download from 'downloadjs'
import {Link as GatsbyLink} from 'gatsby'
import {pascalCase} from 'pascal-case'
import PDFDocument from 'pdfkit/js/pdfkit.standalone'
import React from 'react'
import svgToPdf from 'svg-to-pdfkit'
import Icon from '../components/icon'
import IconViewer from '../components/icon-viewer'
import UIExamples16 from '../components/ui-examples-16'
import UIExamples24 from '../components/ui-examples-24'

export default function IconPage({pageContext}) {
  const icon = {
    name: pageContext.name,
    keywords: pageContext.keywords,
    width: pageContext.width,
    height: pageContext.height,
    path: pageContext.svgPath
  }
  const svg = getSvg(icon)
  const [pdf, setPdf] = React.useState(null)

  React.useEffect(
    () => {
      getPdf(icon).then(blob => setPdf(blob))
    },
    [pageContext]
  )

  const [copied, setCopied] = React.useState(false)

  React.useEffect(
    () => {
      const timeout = setTimeout(() => {
        if (copied) setCopied(false)
      }, 1000)

      return () => clearTimeout(timeout)
    },
    [copied]
  )

  return (
    <Flex flexDirection="column" minHeight="100vh">

      <Flex flex="1 1 auto" flexDirection="row" css={{zIndex: 0}}>
        <Box display={['none', null, null, 'block']}>
          <Sidebar />
        </Box>
        <Container>
          <Breadcrumb>
            <Breadcrumb.Item as={GatsbyLink} to="/">
              Octicons
            </Breadcrumb.Item>
            <Breadcrumb.Item as={GatsbyLink} to={`/${icon.name}-${icon.height}`} selected>
              {icon.name}
            </Breadcrumb.Item>
          </Breadcrumb>
          <Heading as="h1" mt={2} mb={3}>
            {icon.name}
          </Heading>
          <TabNav mb={4}>
            {pageContext.heights.map(height => (
              <TabNav.Link
                key={height}
                as={GatsbyLink}
                to={`/${icon.name}-${height}`}
                selected={height === icon.height}
              >
                {height}
                px
              </TabNav.Link>
            ))}
          </TabNav>

          <IconViewer>
            <Icon width={icon.width} height={icon.height} path={icon.path} />
          </IconViewer>

          <Grid mt={3} gridGap={3} gridTemplateColumns={[null, 'repeat(3, 1fr)']}>
            <Button
              onClick={() => {
                copy(svg)
                setCopied(true)
              }}
            >
              {copied ? 'Copied' : 'Copy SVG'}
            </Button>
            <Button onClick={() => download(svg, `${pageContext.name}.svg`, 'image/svg+xml')}>Download SVG</Button>
            <Button disabled={!pdf} onClick={() => download(pdf, `${pageContext.name}.pdf`, 'application/pdf')}>
              Download PDF
            </Button>
          </Grid>

Usage

          <Paragraph>
            You can use the{' '}

              View Component

            ,{' '}
            <Link as={GatsbyLink} to="/packages/jekyll">
              Jekyll helper
            </Link>
            , or{' '}
            <Link as={GatsbyLink} to="/packages/react">
              React package
            </Link>{' '}
            to include Octicons on your site. Below are code examples for each:
          </Paragraph>

Octicon View Component

          {`<%= render(Primer::OcticonComponent.new(:"${pageContext.name}")) %>`}

Jekyll

          {`{% octicon ${pageContext.name} height:${icon.height} %}`}

React

          {`<${pascalCase(pageContext.name)}Icon size={${icon.height}} />`}

UI examples

          <UIExamples
            size={icon.height}
            icon={props => <Icon width={icon.width} height={icon.height} path={icon.path} {...props} />}
          />
        </Container>
      </Flex>
    </Flex>
  )
}

function UIExamples({size, icon}) {
  switch (size) {
    case 16:
      return <UIExamples16 icon={icon} />
    case 24:
      return <UIExamples24 icon={icon} />
    default:
      return <Text>No examples available</Text>
  }
}

function getSvg(icon) {
  // eslint-disable-next-line github/unescaped-html-literal
  return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${icon.width} ${icon.height}" width="${
    icon.width
  }" height="${icon.height}">${icon.path}</svg>`
}

function getPdf(icon) {
  const svg = getSvg(icon)
  return new Promise(resolve => {
    const doc = new PDFDocument({size: [icon.width, icon.height]})
    const stream = doc.pipe(blobStream())
    svgToPdf(doc, svg, 0, 0, {assumePt: true})
    doc.end()
    stream.on('finish', function() {
      resolve(stream.toBlob('application/pdf'))
    })
  })
}
<|endoftext|>


<commit_before>Meteor.publish('registrants', function () {
    return Registrants.find();
});

Meteor.publish('myRegistrants', function () {
    // Check if the user is signed in
    if (this.userId) {
        // return registrations created by this user
        return Registrants.find({'createdById': this.userId});
    }
});
<commit_msg>Added 'my registrants' count. Comments.<commit_after>Meteor.publish('registrants', function () {
    return Registrants.find();
});

// Registrations for a given user
Meteor.publish('myRegistrants', function () {
    // Check if the user is signed in
    if (this.userId) {
        // return registrations created by this user
        return Registrants.find({'createdById': this.userId});
    }
});

// Count of registrations for a given user
Meteor.publish('myRegistrantCount', function() {
    Counts.publish(this, 'myRegistrantCount', Registrants.find({'createdById': this.userId}));
});
<|endoftext|>


<commit_before>(function(window) {
  window.chai.should();
  window.expect = window.chai.expect;
  window.assert = window.chai.assert;
})(window);<commit_msg>Add should global as well.<commit_after>(function(window) {
  window.should = window.chai.should();
  window.expect = window.chai.expect;
  window.assert = window.chai.assert;
})(window);<|endoftext|>


<commit_before>'use strict';

const _ = require('lodash');
const pgp = require('pg-promise');
const baseSql = require('./base-sql');
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const TwitterStrategy = require('passport-twitter').Strategy;
const FacebookStrategy = require('passport-facebook').Strategy;
const GitHubStrategy = require('passport-github').Strategy;
const defaultCategories = require('./default-categories');

// I can delete this once I refactor to use async/await
/* eslint max-nested-callbacks:off */

// This is copy+pasted from Fortune's source, for now
function createId() {
  // eslint-disable-next-line
  return Date.now() + '-' + ('00000000' + Math.floor(Math.random() * Math.pow(2, 32)).toString(16)).slice(-8);
}

function findUser(db, idType, id) {
  return db.one(`SELECT * FROM profile WHERE ${pgp.as.name(idType)}=$[id]`, {id});
}

module.exports = function(db) {
  function generateCallback(service) {
    return function(req, accessToken, refreshToken, profile, done) {
      const id = profile.id;
      const idField = `${service}_id`;
      const tokenField = `${service}_token`;

      // If ther user is already logged in, then we add this service to their
      // account.
      if (req.isAuthenticated()) {
        const {user} = req;
        const query = baseSql.update('profile', [idField, tokenField, 'name']);

        db.one(query, {
          [tokenField]: accessToken,
          [idField]: id,
          // Add a name if there isn't already one
          name: user.name || profile.displayName,
          id: user.id
        })
          .then(
            (result) => done(null, result),
            () => done(null, false)
          );
      }

      // This handles if the user is not logged in
      else {
        // Start by trying to find the user by their service's ID
        findUser(db, idField, id)
          .then(
            // This handles the situation where the user has already logged in
            // with this social account before.
            result => {
              // If we have a user by the serviceID, but no token, then that
              // means that this account has been disconnected. We reconnect it,
              // then log them back in.
              if (!result[tokenField]) {
                const query = baseSql.update('profile', [tokenField, 'name']);
                db.one(query, {
                  [tokenField]: accessToken,
                  name: result.name || profile.displayName,
                  id: result.id
                })
                  .then(
                    (result) => done(null, result),
                    () => done(null, false)
                  );
              }
              // This means we have an account, and a token, so this is a
              // existing and already-connected account.
              else {
                done(null, result);
              }
            },
            // Let's handle errors with that search for the user...
            err => {
              const queryErrorCode = pgp.errors.queryResultErrorCode;
              const errorKey = _.findKey(queryErrorCode, c => c === err.code);

              // This means the user does not exist. We create a new user.
              if (errorKey === 'noData') {
                const query = baseSql.create({
                  tableName: 'profile',
                  attrs: {
                    [tokenField]: accessToken,
                    [idField]: id,
                    name: profile.displayName,
                    id: createId()
                  },
                  db
                });

                db.one(query)
                  .then(
                    async (result) => {
                      // Attempt to create some default categories. If it errors,
                      // then that's OK. We can add in better error handling
                      // later.
                      // eslint-disable-next-line
                      await db.tx(t => {
                        const queries = defaultCategories.map(category => t.one(baseSql.create({
                          tableName: 'category',
                          attrs: {
                            label: category.label,
                            emoji: category.emoji,
                            user: result.id,
                            id: createId()
                          },
                          db
                        })));
                        return t.batch(queries);
                      }).catch(r => r);

                      done(null, result);
                    },
                    () => done(null, false)
                  );
              }
              // This handles generic query errors. Maybe the DB is down, or
              // something.
              else {
                return done(null, false);
              }
            }
          );
      }
    };
  }

  // These should be configurable via env variables
  const appUrlBase = process.env.APP_DOMAIN ? process.env.APP_DOMAIN : 'http://localhost:5000';

  const googleStrategy = new GoogleStrategy({
    clientID: process.env.GOOGLE_CLIENT_ID,
    clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    callbackURL: `${appUrlBase}/auth/google/callback`,
    passReqToCallback: true
  }, generateCallback('google'));

  const twitterStrategy = new TwitterStrategy({
    consumerKey: process.env.TWITTER_CLIENT_ID,
    consumerSecret: process.env.TWITTER_CLIENT_SECRET,
    callbackURL: `${appUrlBase}/auth/twitter/callback`,
    passReqToCallback: true
  }, generateCallback('twitter'));

  const facebookStrategy = new FacebookStrategy({
    clientID: process.env.FACEBOOK_CLIENT_ID,
    clientSecret: process.env.FACEBOOK_CLIENT_SECRET,
    callbackURL: `${appUrlBase}/auth/facebook/callback`,
    passReqToCallback: true
  }, generateCallback('facebook'));

  const gitHubStrategy = new GitHubStrategy({
    clientID: process.env.GITHUB_CLIENT_ID,
    clientSecret: process.env.GITHUB_CLIENT_SECRET,
    callbackURL: `${appUrlBase}/auth/github/callback`,
    passReqToCallback: true
  }, generateCallback('github'));

  passport.use('google', googleStrategy);
  passport.use('twitter', twitterStrategy);
  passport.use('facebook', facebookStrategy);
  passport.use('github', gitHubStrategy);

  passport.serializeUser((user, done) => {
    done(null, user.id);
  });

  // Retrieves a user account from the DB
  passport.deserializeUser((id, done) => {
    const profileFields = [
      'id', 'name', 'email',
      'facebook_token', 'github_token', 'twitter_token', 'google_token'
    ];
    const readQuery = baseSql.read('profile', profileFields, {
      singular: true
    });
    db.one(readQuery, {id})
      .then(
        (result) => done(null, result),
        () => done(null, false)
      );
  });
};
<commit_msg>Update ID generation code used for initial categories<commit_after>'use strict';

const _ = require('lodash');
const pgp = require('pg-promise');
const passport = require('passport');
const uuid = require('uuid/v4');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const TwitterStrategy = require('passport-twitter').Strategy;
const FacebookStrategy = require('passport-facebook').Strategy;
const GitHubStrategy = require('passport-github').Strategy;
const defaultCategories = require('./default-categories');
const baseSql = require('./base-sql');

// I can delete this once I refactor to use async/await
/* eslint max-nested-callbacks:off */

function findUser(db, idType, id) {
  return db.one(`SELECT * FROM profile WHERE ${pgp.as.name(idType)}=$[id]`, {id});
}

module.exports = function(db) {
  function generateCallback(service) {
    return function(req, accessToken, refreshToken, profile, done) {
      const id = profile.id;
      const idField = `${service}_id`;
      const tokenField = `${service}_token`;

      // If ther user is already logged in, then we add this service to their
      // account.
      if (req.isAuthenticated()) {
        const {user} = req;
        const query = baseSql.update('profile', [idField, tokenField, 'name']);

        db.one(query, {
          [tokenField]: accessToken,
          [idField]: id,
          // Add a name if there isn't already one
          name: user.name || profile.displayName,
          id: user.id
        })
          .then(
            (result) => done(null, result),
            () => done(null, false)
          );
      }

      // This handles if the user is not logged in
      else {
        // Start by trying to find the user by their service's ID
        findUser(db, idField, id)
          .then(
            // This handles the situation where the user has already logged in
            // with this social account before.
            result => {
              // If we have a user by the serviceID, but no token, then that
              // means that this account has been disconnected. We reconnect it,
              // then log them back in.
              if (!result[tokenField]) {
                const query = baseSql.update('profile', [tokenField, 'name']);
                db.one(query, {
                  [tokenField]: accessToken,
                  name: result.name || profile.displayName,
                  id: result.id
                })
                  .then(
                    (result) => done(null, result),
                    () => done(null, false)
                  );
              }
              // This means we have an account, and a token, so this is a
              // existing and already-connected account.
              else {
                done(null, result);
              }
            },
            // Let's handle errors with that search for the user...
            err => {
              const queryErrorCode = pgp.errors.queryResultErrorCode;
              const errorKey = _.findKey(queryErrorCode, c => c === err.code);

              // This means the user does not exist. We create a new user.
              if (errorKey === 'noData') {
                const query = baseSql.create({
                  tableName: 'profile',
                  attrs: {
                    [tokenField]: accessToken,
                    [idField]: id,
                    name: profile.displayName,
                    id: uuid()
                  },
                  db
                });

                db.one(query)
                  .then(
                    async (result) => {
                      // Attempt to create some default categories. If it errors,
                      // then that's OK. We can add in better error handling
                      // later.
                      // eslint-disable-next-line
                      await db.tx(t => {
                        const queries = defaultCategories.map(category => t.one(baseSql.create({
                          tableName: 'category',
                          attrs: {
                            label: category.label,
                            emoji: category.emoji,
                            user: result.id,
                            id: uuid()
                          },
                          db
                        })));
                        return t.batch(queries);
                      }).catch(r => r);

                      done(null, result);
                    },
                    () => done(null, false)
                  );
              }
              // This handles generic query errors. Maybe the DB is down, or
              // something.
              else {
                return done(null, false);
              }
            }
          );
      }
    };
  }

  // These should be configurable via env variables
  const appUrlBase = process.env.APP_DOMAIN ? process.env.APP_DOMAIN : 'http://localhost:5000';

  const googleStrategy = new GoogleStrategy({
    clientID: process.env.GOOGLE_CLIENT_ID,
    clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    callbackURL: `${appUrlBase}/auth/google/callback`,
    passReqToCallback: true
  }, generateCallback('google'));

  const twitterStrategy = new TwitterStrategy({
    consumerKey: process.env.TWITTER_CLIENT_ID,
    consumerSecret: process.env.TWITTER_CLIENT_SECRET,
    callbackURL: `${appUrlBase}/auth/twitter/callback`,
    passReqToCallback: true
  }, generateCallback('twitter'));

  const facebookStrategy = new FacebookStrategy({
    clientID: process.env.FACEBOOK_CLIENT_ID,
    clientSecret: process.env.FACEBOOK_CLIENT_SECRET,
    callbackURL: `${appUrlBase}/auth/facebook/callback`,
    passReqToCallback: true
  }, generateCallback('facebook'));

  const gitHubStrategy = new GitHubStrategy({
    clientID: process.env.GITHUB_CLIENT_ID,
    clientSecret: process.env.GITHUB_CLIENT_SECRET,
    callbackURL: `${appUrlBase}/auth/github/callback`,
    passReqToCallback: true
  }, generateCallback('github'));

  passport.use('google', googleStrategy);
  passport.use('twitter', twitterStrategy);
  passport.use('facebook', facebookStrategy);
  passport.use('github', gitHubStrategy);

  passport.serializeUser((user, done) => {
    done(null, user.id);
  });

  // Retrieves a user account from the DB
  passport.deserializeUser((id, done) => {
    const profileFields = [
      'id', 'name', 'email',
      'facebook_token', 'github_token', 'twitter_token', 'google_token'
    ];
    const readQuery = baseSql.read('profile', profileFields, {
      singular: true
    });
    db.one(readQuery, {id})
      .then(
        (result) => done(null, result),
        () => done(null, false)
      );
  });
};
<|endoftext|>


<commit_before>#! /usr/bin/env node

var http = require( 'http' ),
    chalk = require( 'chalk' ),
    fs = require( 'fs' ),
    readline = require( 'readline' ),
    jsdom = require( 'jsdom' ),
    fileType = require( 'file-type' ),
    addTeam = {
        rl : false,
        state: 0,
        teamData : {},
        gosugamersBaseUrl : 'http://www.gosugamers.net/counterstrike/rankings?tunranked=0&tunranked=1&tname=',
        ensureExists: function( path, mask, callback ) {
            if( typeof mask == 'function' ) { // allow the `mask` parameter to be optional
                callback = mask;
                mask = 0777;
            }

            fs.mkdir( path, mask, function( error ) {
                if( error ) {
                    if( error.code == 'EEXIST' ) {
                        callback( null ); // ignore the error if the folder already exists
                    } else {
                        callback( error ); // something else went wrong
                    }
                } else {
                    callback( null ); // successfully created folder
                }
            });
        },
        setGosugamers : function( index, callback ){
            'use strict';

            jsdom.env(
                addTeam.gosugamersBaseUrl + addTeam.teamData.name,
                [ 'http://code.jquery.com/jquery.js' ],
                function( errors, window ) {
                    addTeam.teamData.gosugamers = {
                        id: window.$( '.ranking-link' ).eq( index ).data( 'id' ),
                        name: window.$( '.ranking-link' ).eq( index ).find( 'h4' ).text().trim()
                    };

                    if( typeof callback === 'function' ){
                        callback.call();
                    }
                }
            );
        },
        searchGosugamers : function(){
            'use strict';

            jsdom.env(
                addTeam.gosugamersBaseUrl + addTeam.teamData.name,
                [ 'http://code.jquery.com/jquery.js' ],
                function( errors, window ) {
                    if( errors ){
                        console.log( errors );
                    }
                    var $teams = window.$( '.ranking-link' );

                    window.$.each( $teams, function( index, element ){
                        console.log( parseInt( index + 1, 10 ) + ': ' + $teams.eq( index ).find( 'h4' ).text().trim() );
                    });

                    addTeam.rl.question( 'Select the correct team ', function( answer ) {
                        addTeam.setGosugamers( parseInt( answer - 1, 10 ), addTeam.finish );
                    });
                }
            );
        },
        changeData : function(){
            console.log( '1: Name' );
            console.log( '2: CSGOLounge' );
            console.log( '3: Gosugamers' );

            addTeam.rl.question( 'What do you want to change? ', function( answer ) {
                switch( answer ){
                    case '1':
                        addTeam.setTeamName();
                        break;
                    case '2':
                        addTeam.csGoLoungeName();
                        break;
                    case '3':
                        addTeam.searchGosugamers();
                        break;
                    default:
                        addTeam.finish();
                        break;
                }
            });
        },
        writeData : function(){
            fs.writeFile( 'teams/' + addTeam.teamData.name + '/data.json', JSON.stringify( addTeam.teamData, null, 4 ), function( error ){
                if( error ){
                    console.log( error );
                } else {
                    console.log( 'Team data written successfully' );
                    addTeam.setTeamName();
                }
            });
        },
        finish: function(){
            console.log( JSON.stringify( addTeam.teamData, null, 4 ) );
            addTeam.rl.question( 'Is this correct? (Y/N) ', function( answer ) {
                switch( answer ){
                    case 'n':
                    case 'N':
                        addTeam.changeData();
                        break;
                    case 'y':
                    case 'Y':
                        addTeam.writeData();
                        break;
                }
            });
        },
        csGoLoungeName: function(){
            addTeam.rl.question( 'What is the name of the team on CSGOLounge? ', function( answer ) {
                if( answer.length > 0 ){
                    addTeam.teamData.csgolounge = {
                        'name': answer
                    };
                }

                addTeam.finish();
            });
        },
        addLogo : function(){
            var writeTarget = 'teams/' + addTeam.teamData.name + '/logo',
                writeStream = fs.createWriteStream( writeTarget ),
                request,
                extension;

            addTeam.rl.question( 'URL to the logo? ', function( url ) {
                request = http.get( url, function( response ) {

                    response.once( 'data', function( chunk ) {
                        extension = fileType( chunk ).ext;
                    });

                    response.on( 'end', function() {
                        fs.rename( writeTarget, writeTarget + '.' + extension, function( error ) {
                            if( error ) {
                                console.log( 'ERROR: ' + error );
                            }
                        });
                    });

                    response.pipe( writeStream );
                });

                addTeam.csGoLoungeName();
            });
        },
        createTeam : function( teamName ){
            'use strict';

            addTeam.teamData.name = teamName;
            addTeam.setGosugamers( 0 );
            addTeam.ensureExists( 'teams/' + addTeam.teamData.name, function( error ) {
                if( error ){
                    console.log( error );
                } else {
                    addTeam.addLogo();
                }
            });
        },
        setupReadLine : function(){
            if( addTeam.rl === false ) {
                addTeam.rl = readline.createInterface({
                    input: process.stdin,
                    output: process.stdout
                }),

                addTeam.rl.on( 'SIGINT', function() {
                    if( addTeam.state !== 0 ){
                        addTeam.rl.close();
                        addTeam.rl = false;
                        addTeam.start();
                    } else {
                        console.log();
                        process.exit();
                    }
                });
            }
        },
        setTeamName : function(){
            addTeam.rl.question( 'What is the name of the team? ', function( answer ) {
                addTeam.createTeam( answer );
            });
        },
        start : function(){
            'use strict';

            addTeam.setupReadLine();
            addTeam.setTeamName();
        }
    };

addTeam.start();
<commit_msg>Add support for custom search phrases to gosugamers and don't add empty gosugamers properties in data.son<commit_after>#! /usr/bin/env node

var http = require( 'http' ),
    chalk = require( 'chalk' ),
    fs = require( 'fs' ),
    readline = require( 'readline' ),
    jsdom = require( 'jsdom' ),
    fileType = require( 'file-type' ),
    addTeam = {
        rl : false,
        state: 0,
        teamData : {},
        gosugamersBaseUrl : 'http://www.gosugamers.net/counterstrike/rankings?tunranked=0&tunranked=1&tname=',
        ensureExists: function( path, mask, callback ) {
            if( typeof mask == 'function' ) { // allow the `mask` parameter to be optional
                callback = mask;
                mask = 0777;
            }

            fs.mkdir( path, mask, function( error ) {
                if( error ) {
                    if( error.code == 'EEXIST' ) {
                        callback( null ); // ignore the error if the folder already exists
                    } else {
                        callback( error ); // something else went wrong
                    }
                } else {
                    callback( null ); // successfully created folder
                }
            });
        },
        setGosugamers : function( searchPhrase, index, callback ){
            'use strict';

            jsdom.env(
                addTeam.gosugamersBaseUrl + searchPhrase,
                [ 'http://code.jquery.com/jquery.js' ],
                function( errors, window ) {
                    if( window.$( '.ranking-link' ).eq( index ).length > 0 ){
                        addTeam.teamData.gosugamers = {
                            id: window.$( '.ranking-link' ).eq( index ).data( 'id' ),
                            name: window.$( '.ranking-link' ).eq( index ).find( 'h4' ).text().trim()
                        };
                    }

                    if( typeof callback === 'function' ){
                        callback.call();
                    }
                }
            );
        },
        searchGosugamers : function( searchPhrase ){
            'use strict';

            jsdom.env(
                addTeam.gosugamersBaseUrl + searchPhrase,
                [ 'http://code.jquery.com/jquery.js' ],
                function( errors, window ) {
                    if( errors ){
                        console.log( errors );
                    }
                    var $teams = window.$( '.ranking-link' );

                    if( $teams.length <= 0 ){
                        console.log( 'Could not find any teams matching "' + searchPhrase + '". ' );
                        addTeam.rl.question( 'Please enter another search term or enter to cancel ', function( answer ) {
                            if( answer.length <= 0 ){
                                addTeam.finish();
                            } else {
                                addTeam.searchGosugamers( answer );
                            }
                        });
                    } else {
                        window.$.each( $teams, function( index, element ){
                            console.log( parseInt( index + 1, 10 ) + ': ' + $teams.eq( index ).find( 'h4' ).text().trim() );
                        });

                        addTeam.rl.question( 'Select the correct team, if none match, enter 0. To cancel, press Enter ', function( answer ) {
                            if( answer.length <= 0 ){
                                addTeam.finish();
                            } else if( answer === '0' ){
                                addTeam.rl.question( 'Please enter a search term ', function( answer ) {
                                    addTeam.searchGosugamers( answer );
                                });
                            } else {
                                addTeam.setGosugamers( searchPhrase, parseInt( answer - 1, 10 ), addTeam.finish );
                            }
                        });
                    }
                }
            );
        },
        changeData : function(){
            console.log( '1: Name' );
            console.log( '2: CSGOLounge' );
            console.log( '3: Gosugamers' );

            addTeam.rl.question( 'What do you want to change? ', function( answer ) {
                switch( answer ){
                    case '1':
                        addTeam.setTeamName();
                        break;
                    case '2':
                        addTeam.csGoLoungeName();
                        break;
                    case '3':
                        addTeam.searchGosugamers( addTeam.teamData.name );
                        break;
                    default:
                        addTeam.finish();
                        break;
                }
            });
        },
        writeData : function(){
            fs.writeFile( 'teams/' + addTeam.teamData.name + '/data.json', JSON.stringify( addTeam.teamData, null, 4 ), function( error ){
                if( error ){
                    console.log( error );
                } else {
                    console.log( 'Team data written successfully' );
                    addTeam.setTeamName();
                }
            });
        },
        finish: function(){
            console.log( JSON.stringify( addTeam.teamData, null, 4 ) );
            addTeam.rl.question( 'Is this correct? (Y/N) ', function( answer ) {
                switch( answer ){
                    case 'n':
                    case 'N':
                        addTeam.changeData();
                        break;
                    case 'y':
                    case 'Y':
                        addTeam.writeData();
                        break;
                }
            });
        },
        csGoLoungeName: function(){
            addTeam.rl.question( 'What is the name of the team on CSGOLounge? ', function( answer ) {
                if( answer.length > 0 ){
                    addTeam.teamData.csgolounge = {
                        'name': answer
                    };
                }

                addTeam.finish();
            });
        },
        addLogo : function(){
            var writeTarget = 'teams/' + addTeam.teamData.name + '/logo',
                writeStream = fs.createWriteStream( writeTarget ),
                request,
                extension;

            addTeam.rl.question( 'URL to the logo? ', function( url ) {
                request = http.get( url, function( response ) {

                    response.once( 'data', function( chunk ) {
                        extension = fileType( chunk ).ext;
                    });

                    response.on( 'end', function() {
                        fs.rename( writeTarget, writeTarget + '.' + extension, function( error ) {
                            if( error ) {
                                console.log( 'ERROR: ' + error );
                            }
                        });
                    });

                    response.pipe( writeStream );
                });

                addTeam.csGoLoungeName();
            });
        },
        createTeam : function( teamName ){
            'use strict';

            addTeam.teamData.name = teamName;
            addTeam.setGosugamers( addTeam.teamData.name, 0 );
            addTeam.ensureExists( 'teams/' + addTeam.teamData.name, function( error ) {
                if( error ){
                    console.log( error );
                } else {
                    addTeam.addLogo();
                }
            });
        },
        setupReadLine : function(){
            if( addTeam.rl === false ) {
                addTeam.rl = readline.createInterface({
                    input: process.stdin,
                    output: process.stdout
                }),

                addTeam.rl.on( 'SIGINT', function() {
                    if( addTeam.state !== 0 ){
                        addTeam.rl.close();
                        addTeam.rl = false;
                        addTeam.start();
                    } else {
                        console.log();
                        process.exit();
                    }
                });
            }
        },
        setTeamName : function(){
            addTeam.rl.question( 'What is the name of the team? ', function( answer ) {
                addTeam.createTeam( answer );
            });
        },
        start : function(){
            'use strict';

            addTeam.setupReadLine();
            addTeam.setTeamName();
        }
    };

addTeam.start();
<|endoftext|>


<commit_before>exports.BattleScripts = {
	init: function() {
		for (var i in this.data.Pokedex) {
			var tier = '';
			var adjustment = 0;
			// mega evolutions get the same stat boost as their base forme
			if (this.data.FormatsData[i]) tier = this.data.FormatsData[i].tier || this.data.FormatsData[toId(this.getTemplate(i).baseSpecies)].tier;
			switch (tier) {
			case 'BL':
			case 'UU':
				adjustment = 5;
				break;
			case 'BL2':
			case 'RU':
				adjustment = 10;
				break;
			case 'BL3':
			case 'NU':
			case 'NFE':
			case 'LC':
				adjustment = 15;
			}

			if (adjustment) {
				for (var j in this.data.Pokedex[i].baseStats) {
					this.modData('Pokedex', i).baseStats[j] = this.clampIntRange(this.data.Pokedex[i].baseStats[j] + adjustment, 1, 255);
				}
			}
		}
	}
};
<commit_msg>Tiershift: Fix 'LC Uber' Pokemon being unchanged<commit_after>exports.BattleScripts = {
	init: function() {
		for (var i in this.data.Pokedex) {
			var tier = '';
			var adjustment = 0;
			// mega evolutions get the same stat boost as their base forme
			if (this.data.FormatsData[i]) tier = this.data.FormatsData[i].tier || this.data.FormatsData[toId(this.getTemplate(i).baseSpecies)].tier;
			switch (tier) {
			case 'BL':
			case 'UU':
				adjustment = 5;
				break;
			case 'BL2':
			case 'RU':
				adjustment = 10;
				break;
			case 'BL3':
			case 'NU':
			case 'NFE':
			case 'LC Uber':
			case 'LC':
				adjustment = 15;
			}

			if (adjustment) {
				for (var j in this.data.Pokedex[i].baseStats) {
					this.modData('Pokedex', i).baseStats[j] = this.clampIntRange(this.data.Pokedex[i].baseStats[j] + adjustment, 1, 255);
				}
			}
		}
	}
};
<|endoftext|>


<commit_before>var RelationFacade = require(__base + 'facades/RelationFacade');
var PhraseFacade = require(__base + 'facades/PhraseFacade');

var hasCalled = false;

/**
 * selectQuestions(userId, page, resultsPerPage, minDiff, minAns, callback)
 *
 * @description :: Selects the phrases to show to the user.
 * Starts from a bunch of Relations (from page 1 and at least 1 resultsPerPage),
 * then verifies that there is at least 1 phrase to show to that user,
 * if not goes to the next page, if there is at least 1 phrase, puts it in a callback.
 * Returns database error if no phrases are left for any Relation.
 *
 * Exported version hides recursion and takes less arguments. See module.export.
 */
function selectQuestions(userId, page, resultsPerPage, minDiff, minAns, callback) {
    hasCalled = false;
    // takes a paged list of Relations
    RelationFacade.pagedList(page, resultsPerPage, function (err, relations) {
        if(err){
            // If there are no relations left ends the stack of recursion with an error.
            // This means that no phrases are left for that user to evaluate.
            callback(err, null);
        }
        else {
            // For each Relation obtained check if there are phrases to show.
            relations.every(function (relation, index, relationsRef) {
                // Phrases to show will be stored in this array, reinitialized for each Relation.
                var phrasesForUser = [];
                // Gets all the phrases by Relation.Name.
                PhraseFacade.listByRelationNameAndUserNotPresent(relation.Name, userId, function (err, phrases) {
                    // For each Phrase checks if it has consensus and if the given user has already evalued it.
                     if(err){
                         // If there are no phrases in DB for this relation
                         callback(err, null);
                    }
                    else {
                    phrases.every(function (phrase, i, phrasesRef) {
                        hasConsensus(minDiff, minAns, phrase, function (phraseHasConsensus) {
                            // debug
                            /*
                            console.log('Answers: ' + phrase.Answers + ' phraseHasConsensus: '  + phraseHasConsensus + ' user id index: ' +
                            phrase.Users.indexOf(userId) + ' utenti per frase: ' + phrase.Users +
                            ' user id ' + userId);
                            */
                            // If user has not evalued it AND Phrase doesn't have consensus, adds it to phrasesForUser
                            if (!phraseHasConsensus)
                                phrasesForUser.push(phrase);
                            // If this is the last iteration of the inner loop and we have results then
                            // calls the callback and ends the recursion.
                            if (i == phrasesRef.length - 1 && phrasesForUser.length != 0) {
                                if (!hasCalled) {
                                    callback(0, phrasesForUser);
                                    hasCalled = true;
                                }
                                return false;
                            }
                            // If this is the last iteration of both loops then recursively call selectQuestions on next page
                            if (i == phrasesRef.length - 1 && index == relationsRef.length - 1 && phrasesForUser.length == 0)
                                selectQuestions(userId, ++page, resultsPerPage, callback);
                            relationsRef = []; // reset array to free space
                            phrasesRef = []; // reset array to free space
                            return false;
                        });
                        // else continue looping on phrases
                        return true;
                    });
                }
                });
                // If phrasesForUser has obtained stuff from at least 1 phrase then exit the loop on relations
                if (phrasesForUser.length != 0) return false;
                // else continue looping on relations
                else return true;
            });
        }
    });
}

function hasConsensus_old(answers, callback) {
    var count = 0;
    if(answers.length <= 1){
        callback(false);
        return;
    }
    answers.forEach(function(answer, i, answersRef){
            count = answer ? count+1: count;
            if(i == answersRef.length - 1){
                zeros = answersRef.length - count;
                outcome = zeros != count && answersRef.length > 0;
                callback(outcome);
            }
        });
}

/**
 * hasConsensus(minDiff, minAns, phrase, callback)
 *
 * @description :: Returns true if there is consensus between answers for that phrase,
 * false otherwise.
 * Takes minDiff (minimum difference between answers) and minAns (minimum number of answers)
 * as parameters to check the consensus.
 *
 * 2 exported version available: 1 with initialized parameters, 1 with open parameters.
 */
function hasConsensus(minDiff, minAns, phrase, callback) {
    if(phrase.Answers.length <= 1)
        callback(false);
    else{
    diff = Math.abs(phrase.PositiveAnswerCount - phrase.NegativeAnswerCount);
    outcome = diff >= minDiff && (phrase.PositiveAnswerCount >= minAns || phrase.NegativeAnswerCount >= minAns);
    callback(outcome);
    }
}

module.exports = {
    selectQuestionsForUser: function (userId, callback) { selectQuestions(userId, 1, 1, 1, 2, callback); },
    selectQuestionsForUserBuffered: function (userId, bufferSize, minDiff, minAns, callback) { selectQuestions(userId, 1, bufferSize, minDiff, minAns, callback); },
    hasConsensus: function (phrase, callback) { hasConsensus(1, 2, phrase, callback); },
    hasConsensus: function (minDiff, minAns, phrase, callback) { hasConsensus(minDiff, minAns, phrase, callback); }
};<commit_msg>fix in module exports<commit_after>var RelationFacade = require(__base + 'facades/RelationFacade');
var PhraseFacade = require(__base + 'facades/PhraseFacade');

var hasCalled = false;

/**
 * selectQuestions(userId, page, resultsPerPage, minDiff, minAns, callback)
 *
 * @description :: Selects the phrases to show to the user.
 * Starts from a bunch of Relations (from page 1 and at least 1 resultsPerPage),
 * then verifies that there is at least 1 phrase to show to that user,
 * if not goes to the next page, if there is at least 1 phrase, puts it in a callback.
 * Returns database error if no phrases are left for any Relation.
 *
 * Exported version hides recursion and takes less arguments. See module.export.
 */
function selectQuestions(userId, page, resultsPerPage, minDiff, minAns, callback) {
    hasCalled = false;
    // takes a paged list of Relations
    RelationFacade.pagedList(page, resultsPerPage, function (err, relations) {
        if(err){
            // If there are no relations left ends the stack of recursion with an error.
            // This means that no phrases are left for that user to evaluate.
            callback(err, null);
        }
        else {
            // For each Relation obtained check if there are phrases to show.
            relations.every(function (relation, index, relationsRef) {
                // Phrases to show will be stored in this array, reinitialized for each Relation.
                var phrasesForUser = [];
                // Gets all the phrases by Relation.Name.
                PhraseFacade.listByRelationNameAndUserNotPresent(relation.Name, userId, function (err, phrases) {
                    // For each Phrase checks if it has consensus and if the given user has already evalued it.
                     if(err){
                         // If there are no phrases in DB for this relation
                         callback(err, null);
                    }
                    else {
                    phrases.every(function (phrase, i, phrasesRef) {
                        hasConsensus(minDiff, minAns, phrase, function (phraseHasConsensus) {
                            // debug
                            /*
                            console.log('Answers: ' + phrase.Answers + ' phraseHasConsensus: '  + phraseHasConsensus + ' user id index: ' +
                            phrase.Users.indexOf(userId) + ' utenti per frase: ' + phrase.Users +
                            ' user id ' + userId);
                            */
                            // If user has not evalued it AND Phrase doesn't have consensus, adds it to phrasesForUser
                            if (!phraseHasConsensus)
                                phrasesForUser.push(phrase);
                            // If this is the last iteration of the inner loop and we have results then
                            // calls the callback and ends the recursion.
                            if (i == phrasesRef.length - 1 && phrasesForUser.length != 0) {
                                if (!hasCalled) {
                                    callback(0, phrasesForUser);
                                    hasCalled = true;
                                }
                                return false;
                            }
                            // If this is the last iteration of both loops then recursively call selectQuestions on next page
                            if (i == phrasesRef.length - 1 && index == relationsRef.length - 1 && phrasesForUser.length == 0)
                                selectQuestions(userId, ++page, resultsPerPage, callback);
                            relationsRef = []; // reset array to free space
                            phrasesRef = []; // reset array to free space
                            return false;
                        });
                        // else continue looping on phrases
                        return true;
                    });
                }
                });
                // If phrasesForUser has obtained stuff from at least 1 phrase then exit the loop on relations
                if (phrasesForUser.length != 0) return false;
                // else continue looping on relations
                else return true;
            });
        }
    });
}

function hasConsensus_old(answers, callback) {
    var count = 0;
    if(answers.length <= 1){
        callback(false);
        return;
    }
    answers.forEach(function(answer, i, answersRef){
            count = answer ? count+1: count;
            if(i == answersRef.length - 1){
                zeros = answersRef.length - count;
                outcome = zeros != count && answersRef.length > 0;
                callback(outcome);
            }
        });
}

/**
 * hasConsensus(minDiff, minAns, phrase, callback)
 *
 * @description :: Returns true if there is consensus between answers for that phrase,
 * false otherwise.
 * Takes minDiff (minimum difference between answers) and minAns (minimum number of answers)
 * as parameters to check the consensus.
 *
 * 2 exported version available: 1 with initialized parameters, 1 with open parameters.
 */
function hasConsensus(minDiff, minAns, phrase, callback) {
    if(phrase.Answers.length <= 1)
        callback(false);
    else{
    diff = Math.abs(phrase.PositiveAnswerCount - phrase.NegativeAnswerCount);
    outcome = diff >= minDiff && (phrase.PositiveAnswerCount >= minAns || phrase.NegativeAnswerCount >= minAns);
    callback(outcome);
    }
}

module.exports = {
    selectQuestionsForUser: function (userId, callback) { selectQuestions(userId, 1, 1, 1, 2, callback); },
    selectQuestionsForUserBuffered: function (userId, bufferSize, callback) { selectQuestions(userId, 1, bufferSize, 1, 2, callback); },
    selectQuestionsForUserBufferedOpt: function (userId, bufferSize,  minDiff, minAns, callback) { selectQuestions(userId, 1, bufferSize, minDiff, minAns, callback); },
    hasConsensus: function (phrase, callback) { hasConsensus(1, 2, phrase, callback); },
    hasConsensus: function (minDiff, minAns, phrase, callback) { hasConsensus(minDiff, minAns, phrase, callback); }
};<|endoftext|>


<commit_before>var is = require('../is');

function arrInvoker(arr) {
  return function() {
    // Special case when length is two, for performance
    arr.length === 2 ? arr[0](arr[1]) : arr[0].apply(undefined, arr.splice(1));
  };
}

function fnInvoker(o) {
  return function(ev) { o.fn(ev); };
}

function updateEventListeners(oldVnode, vnode) {
  var name, cur, old, elm = vnode.elm,
      oldOn = oldVnode.data.on || {}, on = vnode.data.on;
  if (!on) return;
  for (name in on) {
    cur = on[name];
    old = oldOn[name];
    if (old === undefined) {
      if (is.array(cur)) {
        elm.addEventListener(name, arrInvoker(cur));
      } else {
        cur = {fn: cur};
        on[name] = cur;
        elm.addEventListener(name, fnInvoker(cur));
      }
    } else if (is.array(old)) {
      // Deliberately modify old array since it's captured in closure created with `arrInvoker`
      old.length = cur.length;
      for (var i = 0; i < old.length; ++i) old[i] = cur[i];
      on[name]  = old;
    } else {
      old.fn = cur;
      on[name] = old;
    }
  }
}

module.exports = {create: updateEventListeners, update: updateEventListeners};
<commit_msg>Do not mutate event listener parameter array<commit_after>var is = require('../is');

function arrInvoker(arr) {
  return function() {
    // Special case when length is two, for performance
    arr.length === 2 ? arr[0](arr[1]) : arr[0].apply(undefined, arr.slice(1));
  };
}

function fnInvoker(o) {
  return function(ev) { o.fn(ev); };
}

function updateEventListeners(oldVnode, vnode) {
  var name, cur, old, elm = vnode.elm,
      oldOn = oldVnode.data.on || {}, on = vnode.data.on;
  if (!on) return;
  for (name in on) {
    cur = on[name];
    old = oldOn[name];
    if (old === undefined) {
      if (is.array(cur)) {
        elm.addEventListener(name, arrInvoker(cur));
      } else {
        cur = {fn: cur};
        on[name] = cur;
        elm.addEventListener(name, fnInvoker(cur));
      }
    } else if (is.array(old)) {
      // Deliberately modify old array since it's captured in closure created with `arrInvoker`
      old.length = cur.length;
      for (var i = 0; i < old.length; ++i) old[i] = cur[i];
      on[name]  = old;
    } else {
      old.fn = cur;
      on[name] = old;
    }
  }
}

module.exports = {create: updateEventListeners, update: updateEventListeners};
<|endoftext|>