<commit_before>(function (old) {
    /**
     * Cool extension that provide possibility to call $(element).attr()
     * to get an object with all element's attributes with values
     */
    $.fn.attr = function () {
        if (arguments.length === 0) {
            if (this.length === 0) {
                return null;
            }

            var obj = {};
            $.each(this[0].attributes, function () {
                if (this.specified) {
                    obj[this.name] = this.value;
                }
            });
            return obj;
        }

        return old.apply(this, arguments);
    };
})($.fn.attr);

(function () {
    /**
     * Transform element into String
     * @returns {string|null} transformed DOM object as string like
     * "#id.class1.class2[attr1=value1,attr2=value2]"
     */
    $.fn.stringSelector = function () {
        if (this.length === 0) {
            return null;
        }

        var attributes = this.attr();

        if (attributes.id) {
            return "#" + attributes.id;

        } else {
            var elementAsString = "";

            if (attributes["class"]) {
                elementAsString += "." + attributes["class"].split(" ").join(".");
                delete attributes["class"];
            }

            delete attributes.style;

            var otherAttributes = Object.keys(attributes)
                .map(function (key) {
                    return "[" + key + "='" + attributes[key] + "']";
                });

            if (otherAttributes.length) {
                elementAsString += otherAttributes.join("");
            }

            return (elementAsString)
                ? elementAsString
                : this.selector;
        }
    };
}(jQuery));

(function ($) {
    /**
     * Reloads currently selected element
     * @returns {null} if no element selected
     */
    $.fn.reload = function () {
        if (this.length === 0) {
            return null;
        }

        var elementAsStr = this.stringSelector(),
            reloadString = location.href + " " + elementAsStr + ">*",
            $reloadMe = $(elementAsStr);

        if ((arguments.length === 1) && (typeof arguments[0] === "function")) {
            $reloadMe.load(reloadString, arguments[0]);

        } else {
            $reloadMe.load(reloadString);
        }
    };
}(jQuery));

/**
 * Ensure that this addon still used
 */
(function ($) {
    var dataKey = "data-multiselect";

    $.fn.multiselect = function () {

        if (!this.length) {
            return this;
        }

        this.filter("select[multiple]").each(function (pos, item) {
            var $element = $(item),
                $div = $("
").addClass("multiselect-adapter"),
                $options = $element.children("option");

            $options.each(function (pos, item) {
                var $wrapper = $("
").addClass("field"),
                    $item = $(item),
                    $checkbox = $("<input>")
                        .attr({
                            type: "checkbox",
                            name: $element.attr("name"),
                            ignored: "true"
                        })
                        .val($item.val())
                        .prop("checked", $item.is(":selected"))
                        .change(function () {
                            if ($checkbox.is(":checked")) {
                                $item.attr("selected", true)
                            } else {
                                $item.removeAttr("selected");
                            }
                        }),
                    $label = $("").text($item.text());

                $.each(item.attributes, function () {
                    // this.attributes is not a plain object, but an array
                    // of attribute nodes, which contain both the name and value
                    if (this.specified) {
                        $label.attr(this.name, this.value);
                    }
                });

                $wrapper.append($checkbox).append($label);
                $div.append($wrapper);
            });

            $div.insertAfter($element.next().is("label") ? $element.next() : $element);
            $element.hide().change(function () {
                var selected = $element.val(),
                    $checkboxes = $div.find("checkbox");

                $checkboxes.prop("checked", false);

                $.each(selected, function (post, item) {
                    $checkboxes.filter("[value=" + item + "]").prop("checked", true);
                });
            }).data(dataKey, $div);

        });
    };
})(jQuery);

/**
 * Detect Element Resize Plugin for jQuery
 *
 * https://github.com/sdecima/javascript-detect-element-resize
 * Sebastian Decima
 *
 * version: 0.5.3
 **/
(function ($) {
    var attachEvent = document.attachEvent,
        stylesCreated = false;

    var jQuery_resize = $.fn.resize;

    $.fn.resize = function (callback) {
        return this.each(function () {
            if (this == window)
                jQuery_resize.call(jQuery(this), callback);
            else
                addResizeListener(this, callback);
        });
    };

    $.fn.removeResize = function (callback) {
        return this.each(function () {
            removeResizeListener(this, callback);
        });
    };

    if (!attachEvent) {
        var requestFrame = (function () {
            var raf = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame ||
                function (fn) {
                    return window.setTimeout(fn, 20);
                };
            return function (fn) {
                return raf(fn);
            };
        })();

        var cancelFrame = (function () {
            var cancel = window.cancelAnimationFrame || window.mozCancelAnimationFrame || window.webkitCancelAnimationFrame ||
                window.clearTimeout;
            return function (id) {
                return cancel(id);
            };
        })();

        function resetTriggers(element) {
            var triggers = element.__resizeTriggers__,
                expand = triggers.firstElementChild,
                contract = triggers.lastElementChild,
                expandChild = expand.firstElementChild;
            contract.scrollLeft = contract.scrollWidth;
            contract.scrollTop = contract.scrollHeight;
            expandChild.style.width = expand.offsetWidth + 1 + 'px';
            expandChild.style.height = expand.offsetHeight + 1 + 'px';
            expand.scrollLeft = expand.scrollWidth;
            expand.scrollTop = expand.scrollHeight;
        }

        function checkTriggers(element) {
            return element.offsetWidth != element.__resizeLast__.width ||
                element.offsetHeight != element.__resizeLast__.height;
        }

        function scrollListener(e) {
            var element = this;
            resetTriggers(this);
            if (this.__resizeRAF__) cancelFrame(this.__resizeRAF__);
            this.__resizeRAF__ = requestFrame(function () {
                if (checkTriggers(element)) {
                    element.__resizeLast__.width = element.offsetWidth;
                    element.__resizeLast__.height = element.offsetHeight;
                    element.__resizeListeners__.forEach(function (fn) {
                        fn.call(element, e);
                    });
                }
            });
        }

        /* Detect CSS Animations support to detect element display/re-attach */
        var animation = false,
            animationstring = 'animation',
            keyframeprefix = '',
            animationstartevent = 'animationstart',
            domPrefixes = 'Webkit Moz O ms'.split(' '),
            startEvents = 'webkitAnimationStart animationstart oAnimationStart MSAnimationStart'.split(' '),
            pfx = '';
        {
            var elm = document.createElement('fakeelement');
            if (elm.style.animationName !== undefined) {
                animation = true;
            }

            if (animation === false) {
                for (var i = 0; i < domPrefixes.length; i++) {
                    if (elm.style[domPrefixes[i] + 'AnimationName'] !== undefined) {
                        pfx = domPrefixes[i];
                        animationstring = pfx + 'Animation';
                        keyframeprefix = '-' + pfx.toLowerCase() + '-';
                        animationstartevent = startEvents[i];
                        animation = true;
                        break;
                    }
                }
            }
        }

        var animationName = 'resizeanim';
        var animationKeyframes = '@' + keyframeprefix + 'keyframes ' + animationName + ' { from { opacity: 0; } to { opacity: 0; } } ';
        var animationStyle = keyframeprefix + 'animation: 1ms ' + animationName + '; ';
    }

    function createStyles() {
        if (!stylesCreated) {
            //opacity:0 works around a chrome bug https://code.google.com/p/chromium/issues/detail?id=286360
            var css = (animationKeyframes ? animationKeyframes : '') +
                    '.resize-triggers { ' + (animationStyle ? animationStyle : '') + 'visibility: hidden; opacity: 0; } ' +
                    '.resize-triggers, .resize-triggers > div, .contract-trigger:before { content: \" \"; display: block; position: absolute; top: 0; left: 0; height: 100%; width: 100%; overflow: hidden; } .resize-triggers > div { background: #eee; overflow: auto; } .contract-trigger:before { width: 200%; height: 200%; }',
                head = document.head || document.getElementsByTagName('head')[0],
                style = document.createElement('style');

            style.type = 'text/css';
            if (style.styleSheet) {
                style.styleSheet.cssText = css;
            } else {
                style.appendChild(document.createTextNode(css));
            }

            head.appendChild(style);
            stylesCreated = true;
        }
    }

    window.addResizeListener = function (element, fn) {
        if (attachEvent) element.attachEvent('onresize', fn);
        else {
            if (!element.__resizeTriggers__) {
                if (getComputedStyle(element).position == 'static') element.style.position = 'relative';
                createStyles();
                element.__resizeLast__ = {};
                element.__resizeListeners__ = [];
                (element.__resizeTriggers__ = document.createElement('div')).className = 'resize-triggers';
                element.__resizeTriggers__.innerHTML = '

' +
                    '

';
                element.appendChild(element.__resizeTriggers__);
                resetTriggers(element);
                element.addEventListener('scroll', scrollListener, true);

                /* Listen for a css animation to detect element display/re-attach */
                animationstartevent && element.__resizeTriggers__.addEventListener(animationstartevent, function (e) {
                    if (e.animationName == animationName)
                        resetTriggers(element);
                });
            }
            element.__resizeListeners__.push(fn);
        }
    };

    window.removeResizeListener = function (element, fn) {
        if (attachEvent) element.detachEvent('onresize', fn);
        else {
            element.__resizeListeners__.splice(element.__resizeListeners__.indexOf(fn), 1);
            if (!element.__resizeListeners__.length) {
                element.removeEventListener('scroll', scrollListener);
                element.__resizeTriggers__ = !element.removeChild(element.__resizeTriggers__);
            }
        }
    }
}(jQuery));

/*
 * Date Format 1.2.3
 * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
 * MIT license
 *
 * Includes enhancements by Scott Trenda <scott.trenda.net>
 * and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 *
 * See more at http://blog.stevenlevithan.com/archives/date-time-format
 */
var dateFormat = function () {
    var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
        timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
        timezoneClip = /[^-+\dA-Z]/g,
        pad = function (val, len) {
            val = String(val);
            len = len || 2;
            while (val.length < len) val = "0" + val;
            return val;
        };

    // Regexes and supporting functions are cached through closure
    return function (date, mask, utc) {
        var dF = dateFormat;

        // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
        if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
            mask = date;
            date = undefined;
        }

        // Passing date through Date applies Date.parse, if necessary
        date = date ? new Date(date) : new Date;
        if (isNaN(date)) throw SyntaxError("invalid date");

        mask = String(dF.masks[mask] || mask || dF.masks["default"]);

        // Allow setting the utc argument via the mask
        if (mask.slice(0, 4) == "UTC:") {
            mask = mask.slice(4);
            utc = true;
        }

        var _ = utc ? "getUTC" : "get",
            d = date[_ + "Date"](),
            D = date[_ + "Day"](),
            m = date[_ + "Month"](),
            y = date[_ + "FullYear"](),
            H = date[_ + "Hours"](),
            M = date[_ + "Minutes"](),
            s = date[_ + "Seconds"](),
            L = date[_ + "Milliseconds"](),
            o = utc ? 0 : date.getTimezoneOffset(),
            flags = {
                d: d,
                dd: pad(d),
                ddd: dF.i18n.dayNames[D],
                dddd: dF.i18n.dayNames[D + 7],
                m: m + 1,
                mm: pad(m + 1),
                mmm: dF.i18n.monthNames[m],
                mmmm: dF.i18n.monthNames[m + 12],
                yy: String(y).slice(2),
                yyyy: y,
                h: H % 12 || 12,
                hh: pad(H % 12 || 12),
                H: H,
                HH: pad(H),
                M: M,
                MM: pad(M),
                s: s,
                ss: pad(s),
                l: pad(L, 3),
                L: pad(L > 99 ? Math.round(L / 10) : L),
                t: H < 12 ? "a" : "p",
                tt: H < 12 ? "am" : "pm",
                T: H < 12 ? "A" : "P",
                TT: H < 12 ? "AM" : "PM",
                Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
                o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
                S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
            };

        return mask.replace(token, function ($0) {
            return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
        });
    };
}();

// Some common format strings
dateFormat.masks = {
    "default": "ddd mmm dd yyyy HH:MM:ss",
    shortDate: "m/d/yy",
    mediumDate: "mmm d, yyyy",
    longDate: "mmmm d, yyyy",
    fullDate: "dddd, mmmm d, yyyy",
    shortTime: "h:MM TT",
    mediumTime: "h:MM:ss TT",
    longTime: "h:MM:ss TT Z",
    isoDate: "yyyy-mm-dd",
    isoTime: "HH:MM:ss",
    isoDateTime: "yyyy-mm-dd'T'HH:MM:ss",
    isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
    dayNames: [
        "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
        "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
    ],
    monthNames: [
        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
        "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
    ]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
    return dateFormat(this, mask, utc);
};<commit_msg>IMCMS-187 - Image editor fixes: - Added String.prototype.startsWith polyfill for old browsers support.<commit_after>if (!String.prototype.startsWith) {
    Object.defineProperty(String.prototype, 'startsWith', {
        enumerable: false,
        configurable: false,
        writable: false,
        value: function(searchString, position) {
            position = position || 0;
            return this.lastIndexOf(searchString, position) === position;
        }
    });
}

(function (old) {
    /**
     * Cool extension that provide possibility to call $(element).attr()
     * to get an object with all element's attributes with values
     */
    $.fn.attr = function () {
        if (arguments.length === 0) {
            if (this.length === 0) {
                return null;
            }

            var obj = {};
            $.each(this[0].attributes, function () {
                if (this.specified) {
                    obj[this.name] = this.value;
                }
            });
            return obj;
        }

        return old.apply(this, arguments);
    };
})($.fn.attr);

(function () {
    /**
     * Transform element into String
     * @returns {string|null} transformed DOM object as string like
     * "#id.class1.class2[attr1=value1,attr2=value2]"
     */
    $.fn.stringSelector = function () {
        if (this.length === 0) {
            return null;
        }

        var attributes = this.attr();

        if (attributes.id) {
            return "#" + attributes.id;

        } else {
            var elementAsString = "";

            if (attributes["class"]) {
                elementAsString += "." + attributes["class"].split(" ").join(".");
                delete attributes["class"];
            }

            delete attributes.style;

            var otherAttributes = Object.keys(attributes)
                .map(function (key) {
                    return "[" + key + "='" + attributes[key] + "']";
                });

            if (otherAttributes.length) {
                elementAsString += otherAttributes.join("");
            }

            return (elementAsString)
                ? elementAsString
                : this.selector;
        }
    };
}(jQuery));

(function ($) {
    /**
     * Reloads currently selected element
     * @returns {null} if no element selected
     */
    $.fn.reload = function () {
        if (this.length === 0) {
            return null;
        }

        var elementAsStr = this.stringSelector(),
            reloadString = location.href + " " + elementAsStr + ">*",
            $reloadMe = $(elementAsStr);

        if ((arguments.length === 1) && (typeof arguments[0] === "function")) {
            $reloadMe.load(reloadString, arguments[0]);

        } else {
            $reloadMe.load(reloadString);
        }
    };
}(jQuery));

/**
 * Ensure that this addon still used
 */
(function ($) {
    var dataKey = "data-multiselect";

    $.fn.multiselect = function () {

        if (!this.length) {
            return this;
        }

        this.filter("select[multiple]").each(function (pos, item) {
            var $element = $(item),
                $div = $("
").addClass("multiselect-adapter"),
                $options = $element.children("option");

            $options.each(function (pos, item) {
                var $wrapper = $("
").addClass("field"),
                    $item = $(item),
                    $checkbox = $("<input>")
                        .attr({
                            type: "checkbox",
                            name: $element.attr("name"),
                            ignored: "true"
                        })
                        .val($item.val())
                        .prop("checked", $item.is(":selected"))
                        .change(function () {
                            if ($checkbox.is(":checked")) {
                                $item.attr("selected", true)
                            } else {
                                $item.removeAttr("selected");
                            }
                        }),
                    $label = $("").text($item.text());

                $.each(item.attributes, function () {
                    // this.attributes is not a plain object, but an array
                    // of attribute nodes, which contain both the name and value
                    if (this.specified) {
                        $label.attr(this.name, this.value);
                    }
                });

                $wrapper.append($checkbox).append($label);
                $div.append($wrapper);
            });

            $div.insertAfter($element.next().is("label") ? $element.next() : $element);
            $element.hide().change(function () {
                var selected = $element.val(),
                    $checkboxes = $div.find("checkbox");

                $checkboxes.prop("checked", false);

                $.each(selected, function (post, item) {
                    $checkboxes.filter("[value=" + item + "]").prop("checked", true);
                });
            }).data(dataKey, $div);

        });
    };
})(jQuery);

/**
 * Detect Element Resize Plugin for jQuery
 *
 * https://github.com/sdecima/javascript-detect-element-resize
 * Sebastian Decima
 *
 * version: 0.5.3
 **/
(function ($) {
    var attachEvent = document.attachEvent,
        stylesCreated = false;

    var jQuery_resize = $.fn.resize;

    $.fn.resize = function (callback) {
        return this.each(function () {
            if (this == window)
                jQuery_resize.call(jQuery(this), callback);
            else
                addResizeListener(this, callback);
        });
    };

    $.fn.removeResize = function (callback) {
        return this.each(function () {
            removeResizeListener(this, callback);
        });
    };

    if (!attachEvent) {
        var requestFrame = (function () {
            var raf = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame ||
                function (fn) {
                    return window.setTimeout(fn, 20);
                };
            return function (fn) {
                return raf(fn);
            };
        })();

        var cancelFrame = (function () {
            var cancel = window.cancelAnimationFrame || window.mozCancelAnimationFrame || window.webkitCancelAnimationFrame ||
                window.clearTimeout;
            return function (id) {
                return cancel(id);
            };
        })();

        function resetTriggers(element) {
            var triggers = element.__resizeTriggers__,
                expand = triggers.firstElementChild,
                contract = triggers.lastElementChild,
                expandChild = expand.firstElementChild;
            contract.scrollLeft = contract.scrollWidth;
            contract.scrollTop = contract.scrollHeight;
            expandChild.style.width = expand.offsetWidth + 1 + 'px';
            expandChild.style.height = expand.offsetHeight + 1 + 'px';
            expand.scrollLeft = expand.scrollWidth;
            expand.scrollTop = expand.scrollHeight;
        }

        function checkTriggers(element) {
            return element.offsetWidth != element.__resizeLast__.width ||
                element.offsetHeight != element.__resizeLast__.height;
        }

        function scrollListener(e) {
            var element = this;
            resetTriggers(this);
            if (this.__resizeRAF__) cancelFrame(this.__resizeRAF__);
            this.__resizeRAF__ = requestFrame(function () {
                if (checkTriggers(element)) {
                    element.__resizeLast__.width = element.offsetWidth;
                    element.__resizeLast__.height = element.offsetHeight;
                    element.__resizeListeners__.forEach(function (fn) {
                        fn.call(element, e);
                    });
                }
            });
        }

        /* Detect CSS Animations support to detect element display/re-attach */
        var animation = false,
            animationstring = 'animation',
            keyframeprefix = '',
            animationstartevent = 'animationstart',
            domPrefixes = 'Webkit Moz O ms'.split(' '),
            startEvents = 'webkitAnimationStart animationstart oAnimationStart MSAnimationStart'.split(' '),
            pfx = '';
        {
            var elm = document.createElement('fakeelement');
            if (elm.style.animationName !== undefined) {
                animation = true;
            }

            if (animation === false) {
                for (var i = 0; i < domPrefixes.length; i++) {
                    if (elm.style[domPrefixes[i] + 'AnimationName'] !== undefined) {
                        pfx = domPrefixes[i];
                        animationstring = pfx + 'Animation';
                        keyframeprefix = '-' + pfx.toLowerCase() + '-';
                        animationstartevent = startEvents[i];
                        animation = true;
                        break;
                    }
                }
            }
        }

        var animationName = 'resizeanim';
        var animationKeyframes = '@' + keyframeprefix + 'keyframes ' + animationName + ' { from { opacity: 0; } to { opacity: 0; } } ';
        var animationStyle = keyframeprefix + 'animation: 1ms ' + animationName + '; ';
    }

    function createStyles() {
        if (!stylesCreated) {
            //opacity:0 works around a chrome bug https://code.google.com/p/chromium/issues/detail?id=286360
            var css = (animationKeyframes ? animationKeyframes : '') +
                    '.resize-triggers { ' + (animationStyle ? animationStyle : '') + 'visibility: hidden; opacity: 0; } ' +
                    '.resize-triggers, .resize-triggers > div, .contract-trigger:before { content: \" \"; display: block; position: absolute; top: 0; left: 0; height: 100%; width: 100%; overflow: hidden; } .resize-triggers > div { background: #eee; overflow: auto; } .contract-trigger:before { width: 200%; height: 200%; }',
                head = document.head || document.getElementsByTagName('head')[0],
                style = document.createElement('style');

            style.type = 'text/css';
            if (style.styleSheet) {
                style.styleSheet.cssText = css;
            } else {
                style.appendChild(document.createTextNode(css));
            }

            head.appendChild(style);
            stylesCreated = true;
        }
    }

    window.addResizeListener = function (element, fn) {
        if (attachEvent) element.attachEvent('onresize', fn);
        else {
            if (!element.__resizeTriggers__) {
                if (getComputedStyle(element).position == 'static') element.style.position = 'relative';
                createStyles();
                element.__resizeLast__ = {};
                element.__resizeListeners__ = [];
                (element.__resizeTriggers__ = document.createElement('div')).className = 'resize-triggers';
                element.__resizeTriggers__.innerHTML = '

' +
                    '

';
                element.appendChild(element.__resizeTriggers__);
                resetTriggers(element);
                element.addEventListener('scroll', scrollListener, true);

                /* Listen for a css animation to detect element display/re-attach */
                animationstartevent && element.__resizeTriggers__.addEventListener(animationstartevent, function (e) {
                    if (e.animationName == animationName)
                        resetTriggers(element);
                });
            }
            element.__resizeListeners__.push(fn);
        }
    };

    window.removeResizeListener = function (element, fn) {
        if (attachEvent) element.detachEvent('onresize', fn);
        else {
            element.__resizeListeners__.splice(element.__resizeListeners__.indexOf(fn), 1);
            if (!element.__resizeListeners__.length) {
                element.removeEventListener('scroll', scrollListener);
                element.__resizeTriggers__ = !element.removeChild(element.__resizeTriggers__);
            }
        }
    }
}(jQuery));

/*
 * Date Format 1.2.3
 * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
 * MIT license
 *
 * Includes enhancements by Scott Trenda <scott.trenda.net>
 * and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 *
 * See more at http://blog.stevenlevithan.com/archives/date-time-format
 */
var dateFormat = function () {
    var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
        timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
        timezoneClip = /[^-+\dA-Z]/g,
        pad = function (val, len) {
            val = String(val);
            len = len || 2;
            while (val.length < len) val = "0" + val;
            return val;
        };

    // Regexes and supporting functions are cached through closure
    return function (date, mask, utc) {
        var dF = dateFormat;

        // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
        if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
            mask = date;
            date = undefined;
        }

        // Passing date through Date applies Date.parse, if necessary
        date = date ? new Date(date) : new Date;
        if (isNaN(date)) throw SyntaxError("invalid date");

        mask = String(dF.masks[mask] || mask || dF.masks["default"]);

        // Allow setting the utc argument via the mask
        if (mask.slice(0, 4) == "UTC:") {
            mask = mask.slice(4);
            utc = true;
        }

        var _ = utc ? "getUTC" : "get",
            d = date[_ + "Date"](),
            D = date[_ + "Day"](),
            m = date[_ + "Month"](),
            y = date[_ + "FullYear"](),
            H = date[_ + "Hours"](),
            M = date[_ + "Minutes"](),
            s = date[_ + "Seconds"](),
            L = date[_ + "Milliseconds"](),
            o = utc ? 0 : date.getTimezoneOffset(),
            flags = {
                d: d,
                dd: pad(d),
                ddd: dF.i18n.dayNames[D],
                dddd: dF.i18n.dayNames[D + 7],
                m: m + 1,
                mm: pad(m + 1),
                mmm: dF.i18n.monthNames[m],
                mmmm: dF.i18n.monthNames[m + 12],
                yy: String(y).slice(2),
                yyyy: y,
                h: H % 12 || 12,
                hh: pad(H % 12 || 12),
                H: H,
                HH: pad(H),
                M: M,
                MM: pad(M),
                s: s,
                ss: pad(s),
                l: pad(L, 3),
                L: pad(L > 99 ? Math.round(L / 10) : L),
                t: H < 12 ? "a" : "p",
                tt: H < 12 ? "am" : "pm",
                T: H < 12 ? "A" : "P",
                TT: H < 12 ? "AM" : "PM",
                Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
                o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
                S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
            };

        return mask.replace(token, function ($0) {
            return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
        });
    };
}();

// Some common format strings
dateFormat.masks = {
    "default": "ddd mmm dd yyyy HH:MM:ss",
    shortDate: "m/d/yy",
    mediumDate: "mmm d, yyyy",
    longDate: "mmmm d, yyyy",
    fullDate: "dddd, mmmm d, yyyy",
    shortTime: "h:MM TT",
    mediumTime: "h:MM:ss TT",
    longTime: "h:MM:ss TT Z",
    isoDate: "yyyy-mm-dd",
    isoTime: "HH:MM:ss",
    isoDateTime: "yyyy-mm-dd'T'HH:MM:ss",
    isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
    dayNames: [
        "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
        "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
    ],
    monthNames: [
        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
        "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
    ]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
    return dateFormat(this, mask, utc);
};<|endoftext|>


<commit_before>"use strict";

const
    fs = require("fs"),
    tools = require("../res/tools.js"),
    osPathSeparator = require("path").sep,
    isWindows = tools.isWindows,
    toArray = arrayLike => [].slice.call(arrayLike),
    sep = path => osPathSeparator === "/" ? path : path.replace(/\//g, osPathSeparator),

    // Node supports / on any host
    platoCmd = "node node_modules/plato/bin/plato -l .jshintrc -t GPF-JS -d tmp/plato",
    jsdocCmd = "node node_modules/jsdoc/jsdoc -d tmp/jsdoc --verbose -a all -c doc/private.json",
    buildLintingDocCmd = "node doc/linting",
    checkdocCmd = `node doc/validate http://localhost:${configuration.serve.httpPort}/tmp/doc/public/index.html`,

    config = (cmd, ...options) => {
        let objectCmd;
        if (typeof cmd === "string" || typeof cmd === "function") {
            objectCmd = {
                cmd: cmd
            };
        } else {
            objectCmd = cmd;
        }
        return Object.assign.apply(Object, [objectCmd].concat(options));
    },

    silent = {
        stdout: false,
        stderr: false
    },
    showErrors = {
        stdout: false,
        stderr: true
    },
    verbose = {
        stdout: true,
        stderr: true
    },
    failIfNot0 = {
        exitCode: 0
    },

    testConfig = (name, rawCommand, parameters) => {
        let command;
        if (isWindows && rawCommand.indexOf(" ") !== -1) {
            command = `"${rawCommand}"`;
        } else {
            command = rawCommand;
        }
        command += ` ${parameters}`;
        const cmd = suffix => function () {
            let parameter;
            if (arguments.length) {
                parameter = toArray(arguments).join(" ") + " ";
            } else {
                parameter = "";
            }
            return command + " " + parameter + suffix;
        };
        module.exports[`test${name}`] = config(cmd(""), silent, failIfNot0);
        module.exports[`test${name}Verbose`] = config(cmd("-debugger"), verbose, failIfNot0);
        module.exports[`test${name}Coverage`] = config(cmd("-coverage"), verbose, failIfNot0);
        module.exports[`test${name}Debug`] = config(cmd("-debug"), silent, failIfNot0);
        module.exports[`test${name}Release`] = config(cmd("-release"), silent, failIfNot0);
        module.exports[`test${name}Legacy`] = config(version => `${command} legacy/${version}`, silent, failIfNot0);
        module.exports[`test${name}Flavor`] = config(flavor => `${command} flavor:${flavor}`, silent, failIfNot0);
    };

let phantomJsBin = "/usr/local/phantomjs/bin/phantomjs"; // If already installed
if (!fs.existsSync(phantomJsBin)) {
    // Assume it is installed with the phantomjs-prebuilt package
    phantomJsBin = sep("node_modules/phantomjs-prebuilt/lib/phantom/bin/phantomjs");
}

// Custom command lines
module.exports = {
    buildDebug: config({cmd: "node make.js debug", cwd: "make"}, silent, failIfNot0),
    buildRelease: config({cmd: "node make.js release", cwd: "make"}, silent, failIfNot0),
    plato: config(() => `${platoCmd} ${configuration.files.src.join(" ")}`, verbose),
    metrics: config((...args) => `node make/metrics.js ${args.join(" ")}`, showErrors, failIfNot0),
    globals: config("node make/globals.js", showErrors, failIfNot0),
    version: config("node make/version.js", silent, failIfNot0),
    detectSelenium: config("node test/host/selenium/detect.js", verbose, failIfNot0),
    jsdoc: config((...args) => `${jsdocCmd} ${args.join(" ")}`, verbose, failIfNot0),
    fixUglify: config(name => `node make/fix_uglify.js ${name}`, verbose, failIfNot0),
    buildLintingDoc: config(buildLintingDocCmd, showErrors, failIfNot0),
    checkDoc: config(checkdocCmd, verbose, failIfNot0)
};

// Flavor builds
Object.keys(configuration.files.flavors).forEach(flavor => {
    module.exports[`build${tools.capitalize(flavor)}`] = config({
        cmd: `node make.js flavor/${flavor}`,
        cwd: "make"
    }, silent, failIfNot0);
});

// Test configurations
testConfig("Node", "node", "test/host/nodejs.js");
testConfig("Phantom", phantomJsBin, sep("--web-security=false test/host/phantomjs.js"));
testConfig("Wscript", "cscript.exe", `/D /E:JScript ${sep("test/host/cscript.js")}`);
testConfig("Nodewscript", "node", "test/host/node_cscript.js");
testConfig("Rhino", "java", sep("-jar node_modules/rhino-1_7r5-bin/rhino1_7R5/js.jar test/host/java.js"));
testConfig("Nashorn", configuration.host.nashorn, sep("test/host/java.js  --"));

Object.keys(configuration.browsers).forEach(browserName =>{
    const
        browserConfig = configuration.browsers[browserName],
        capitalizedBrowserName = tools.capitalize(browserName);
    if (browserConfig.type === "selenium") {
        testConfig(capitalizedBrowserName, "node", `test/host/selenium.js ${browserName}`);
    } else if (browserConfig.type === "spawn") {
        testConfig(capitalizedBrowserName, "node", `test/host/browser.js ${browserName}`);
    }
});
<commit_msg>no-magic-numbers (#280)<commit_after>"use strict";

const
    fs = require("fs"),
    tools = require("../res/tools.js"),
    osPathSeparator = require("path").sep,
    isWindows = tools.isWindows,
    toArray = arrayLike => [].slice.call(arrayLike),
    sep = path => osPathSeparator === "/" ? path : path.replace(/\//g, osPathSeparator),

    // Node supports / on any host
    platoCmd = "node node_modules/plato/bin/plato -l .jshintrc -t GPF-JS -d tmp/plato",
    jsdocCmd = "node node_modules/jsdoc/jsdoc -d tmp/jsdoc --verbose -a all -c doc/private.json",
    buildLintingDocCmd = "node doc/linting",
    checkdocCmd = `node doc/validate http://localhost:${configuration.serve.httpPort}/tmp/doc/public/index.html`,

    config = (cmd, ...options) => {
        let objectCmd;
        if (typeof cmd === "string" || typeof cmd === "function") {
            objectCmd = {
                cmd: cmd
            };
        } else {
            objectCmd = cmd;
        }
        return Object.assign.apply(Object, [objectCmd].concat(options));
    },

    silent = {
        stdout: false,
        stderr: false
    },
    showErrors = {
        stdout: false,
        stderr: true
    },
    verbose = {
        stdout: true,
        stderr: true
    },
    failIfNot0 = {
        exitCode: 0
    },

    testConfig = (name, rawCommand, parameters) => {
        let command;
        if (isWindows && rawCommand.includes(" ")) {
            command = `"${rawCommand}"`;
        } else {
            command = rawCommand;
        }
        command += ` ${parameters}`;
        const cmd = suffix => function () {
            let parameter;
            if (arguments.length) {
                parameter = toArray(arguments).join(" ") + " ";
            } else {
                parameter = "";
            }
            return command + " " + parameter + suffix;
        };
        module.exports[`test${name}`] = config(cmd(""), silent, failIfNot0);
        module.exports[`test${name}Verbose`] = config(cmd("-debugger"), verbose, failIfNot0);
        module.exports[`test${name}Coverage`] = config(cmd("-coverage"), verbose, failIfNot0);
        module.exports[`test${name}Debug`] = config(cmd("-debug"), silent, failIfNot0);
        module.exports[`test${name}Release`] = config(cmd("-release"), silent, failIfNot0);
        module.exports[`test${name}Legacy`] = config(version => `${command} legacy/${version}`, silent, failIfNot0);
        module.exports[`test${name}Flavor`] = config(flavor => `${command} flavor:${flavor}`, silent, failIfNot0);
    };

let phantomJsBin = "/usr/local/phantomjs/bin/phantomjs"; // If already installed
if (!fs.existsSync(phantomJsBin)) {
    // Assume it is installed with the phantomjs-prebuilt package
    phantomJsBin = sep("node_modules/phantomjs-prebuilt/lib/phantom/bin/phantomjs");
}

// Custom command lines
module.exports = {
    buildDebug: config({cmd: "node make.js debug", cwd: "make"}, silent, failIfNot0),
    buildRelease: config({cmd: "node make.js release", cwd: "make"}, silent, failIfNot0),
    plato: config(() => `${platoCmd} ${configuration.files.src.join(" ")}`, verbose),
    metrics: config((...args) => `node make/metrics.js ${args.join(" ")}`, showErrors, failIfNot0),
    globals: config("node make/globals.js", showErrors, failIfNot0),
    version: config("node make/version.js", silent, failIfNot0),
    detectSelenium: config("node test/host/selenium/detect.js", verbose, failIfNot0),
    jsdoc: config((...args) => `${jsdocCmd} ${args.join(" ")}`, verbose, failIfNot0),
    fixUglify: config(name => `node make/fix_uglify.js ${name}`, verbose, failIfNot0),
    buildLintingDoc: config(buildLintingDocCmd, showErrors, failIfNot0),
    checkDoc: config(checkdocCmd, verbose, failIfNot0)
};

// Flavor builds
Object.keys(configuration.files.flavors).forEach(flavor => {
    module.exports[`build${tools.capitalize(flavor)}`] = config({
        cmd: `node make.js flavor/${flavor}`,
        cwd: "make"
    }, silent, failIfNot0);
});

// Test configurations
testConfig("Node", "node", "test/host/nodejs.js");
testConfig("Phantom", phantomJsBin, sep("--web-security=false test/host/phantomjs.js"));
testConfig("Wscript", "cscript.exe", `/D /E:JScript ${sep("test/host/cscript.js")}`);
testConfig("Nodewscript", "node", "test/host/node_cscript.js");
testConfig("Rhino", "java", sep("-jar node_modules/rhino-1_7r5-bin/rhino1_7R5/js.jar test/host/java.js"));
testConfig("Nashorn", configuration.host.nashorn, sep("test/host/java.js  --"));

Object.keys(configuration.browsers).forEach(browserName =>{
    const
        browserConfig = configuration.browsers[browserName],
        capitalizedBrowserName = tools.capitalize(browserName);
    if (browserConfig.type === "selenium") {
        testConfig(capitalizedBrowserName, "node", `test/host/selenium.js ${browserName}`);
    } else if (browserConfig.type === "spawn") {
        testConfig(capitalizedBrowserName, "node", `test/host/browser.js ${browserName}`);
    }
});
<|endoftext|>


<commit_before>'use strict';

// import
const _ = require('underscore');
const objectAssign = require('object-assign');
const express = require('express');
const glob = require('glob');
const path = require('path');

// default config
const defaultConfig = {
  src: './src',

  spa: {
    path: '/release',
    index: 'index.html'
  },

  port: 3000
};

// helper logic
const loadFiles = (paths) => {
  const rawFiles = paths.map(path => glob.sync(`${path}/**/*.js`));
  const files = _.uniq(_.flatten(rawFiles));

  return files.map((file) => {
    let relativePath = file;
    _.each(paths, path => relativePath = relativePath.replace(path, ''))

    const requirePath = file.startsWith(__dirname) ? file : `../../${file}`;

    return {
      absolutePath: file,
      relativePath: relativePath,

      instance: require(requirePath)
    };
  });
};

const applyConfig = (app, config) => {
  const configFuncs = loadFiles([`${__dirname}/src/config/`, `${config.src}/config/`]);

  _.each(configFuncs, f => f.instance(app));
};

const applyRoutes = (app, config) => {
  const verbs = ['get','post','put','delete'];

  const paths = [`${__dirname}/src/routes/`, `${config.src}/routes` ];
  const routes = loadFiles(paths);

  var router = express.Router();
  _.each(routes, (load) => {
    let path = load.relativePath.replace('.js', '');
    if (path.includes('index')) {
      path = path.replace('index', '');
    }

    // attach methods defined
    _.each(verbs, (verb) => {
      if (load.instance[verb]) {
        router[verb](path, load.instance[verb]);
      }
    });
  });

  app.use(router);
};

const configureSpaRoute = (app, config) => {
  if (!config.spa) {
    return;
  }

  // map to the spa app
  app.use(express.static(`${config.spa.path}`));
  app.get('*', function(req, res) {
  	res.status(200).sendFile(path.join(`${config.spa.path}/${config.spa.index}`));
  });
};

// server define
const server = {
  init: (clientConfig) => {
    const config = objectAssign(defaultConfig, clientConfig);
    const app = express();

    // load config
    applyConfig(app, config);
    applyRoutes(app, config);

    configureSpaRoute(app, config);

    // run
    app.listen(process.env.PORT || config.port);
  }
};
module.exports = server;

server.init();
<commit_msg>add support es6 export default<commit_after>'use strict';

// import
const _ = require('underscore');
const objectAssign = require('object-assign');
const express = require('express');
const glob = require('glob');
const path = require('path');

// default config
const defaultConfig = {
  src: './src',

  spa: {
    path: '/release',
    index: 'index.html'
  },

  port: 3000
};

// helper logic
const loadFiles = (paths) => {
  const rawFiles = paths.map(path => glob.sync(`${path}/**/*.js`));
  const files = _.uniq(_.flatten(rawFiles));

  return files.map((file) => {
    let relativePath = file;
    _.each(paths, path => relativePath = relativePath.replace(path, ''))

    const requirePath = file.startsWith(__dirname) ? file : `../../${file}`;

    var instance = require(requirePath);
    if (instance.default) {
      instance = instance.default;
    }

    return {
      absolutePath: file,
      relativePath: relativePath,
      instance: instance
    };
  });
};

const applyConfig = (app, config) => {
  const configFuncs = loadFiles([`${__dirname}/src/config/`, `${config.src}/config/`]);

  _.each(configFuncs, f => f.instance(app));
};

const applyRoutes = (app, config) => {
  const verbs = ['get','post','put','delete'];

  const paths = [`${__dirname}/src/routes/`, `${config.src}/routes` ];
  const routes = loadFiles(paths);

  var router = express.Router();
  _.each(routes, (load) => {
    let path = load.relativePath.replace('.js', '');
    if (path.includes('index')) {
      path = path.replace('index', '');
    }

    // attach methods defined
    _.each(verbs, (verb) => {
      if (load.instance[verb]) {
        router[verb](path, load.instance[verb]);
      }
    });
  });

  app.use(router);
};

const configureSpaRoute = (app, config) => {
  if (!config.spa) {
    return;
  }

  // map to the spa app
  app.use(express.static(`${config.spa.path}`));
  app.get('*', function(req, res) {
  	res.status(200).sendFile(path.join(`${config.spa.path}/${config.spa.index}`));
  });
};

// server define
const server = {
  init: (clientConfig) => {
    const config = objectAssign(defaultConfig, clientConfig);
    const app = express();

    // load config
    applyConfig(app, config);
    applyRoutes(app, config);

    configureSpaRoute(app, config);

    // run
    app.listen(process.env.PORT || config.port);
  }
};
module.exports = server;

server.init();
<|endoftext|>


<commit_before>/**
 * Created by roy on 15/8/14.
 */
BI.DownListCombo = BI.inherit(BI.Widget, {
    _defaultConfig: function () {
        return BI.extend(BI.DownListCombo.superclass._defaultConfig.apply(this, arguments), {
            baseCls: "bi-multilayer-down-list-combo",
            height: 24,
            items: [],
            adjustLength: 0,
            direction: "bottom",
            trigger: "click",
            container: null,
            stopPropagation: false,
            el: {}
        });
    },

    _init: function () {
        BI.DownListCombo.superclass._init.apply(this, arguments);
        var self = this, o = this.options;
        this.popupview = BI.createWidget({
            type: "bi.multi_layer_down_list_popup",
            items: o.items,
            chooseType: o.chooseType,
            value: o.value
        });

        this.popupview.on(BI.DownListPopup.EVENT_CHANGE, function (value) {
            self.fireEvent(BI.DownListCombo.EVENT_CHANGE, value);
            self.downlistcombo.hideView();
        });

        this.popupview.on(BI.DownListPopup.EVENT_SON_VALUE_CHANGE, function (value, fatherValue) {
            self.fireEvent(BI.DownListCombo.EVENT_SON_VALUE_CHANGE, value, fatherValue);
            self.downlistcombo.hideView();
        });

        this.downlistcombo = BI.createWidget({
            element: this,
            type: "bi.combo",
            trigger: o.trigger,
            isNeedAdjustWidth: false,
            container: o.container,
            adjustLength: o.adjustLength,
            direction: o.direction,
            stopPropagation: o.stopPropagation,
            el: BI.createWidget(o.el, {
                type: "bi.icon_trigger",
                extraCls: o.iconCls ? o.iconCls : "pull-down-font",
                width: o.width,
                height: o.height
            }),
            popup: {
                el: this.popupview,
                stopPropagation: o.stopPropagation,
                maxHeight: 1000
            }
        });

        this.downlistcombo.on(BI.Combo.EVENT_BEFORE_POPUPVIEW, function () {
            self.fireEvent(BI.DownListCombo.EVENT_BEFORE_POPUPVIEW);
        });
    },

    hideView: function () {
        this.downlistcombo.hideView();
    },

    showView: function (e) {
        this.downlistcombo.showView(e);
    },

    populate: function (items) {
        this.popupview.populate(items);
    },

    setValue: function (v) {
        this.popupview.setValue(v);
    },
    getValue: function () {
        return this.popupview.getValue();
    }
});
BI.DownListCombo.EVENT_CHANGE = "EVENT_CHANGE";
BI.DownListCombo.EVENT_SON_VALUE_CHANGE = "EVENT_SON_VALUE_CHANGE";
BI.DownListCombo.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW";

BI.shortcut("bi.multi_layer_down_list_combo", BI.DownListCombo);<commit_msg>Pull request #1499: 无jira任务，BI.DownListCombo重名了，改成BI.MultiLayerDownListCombo<commit_after>/**
 * Created by roy on 15/8/14.
 */
BI.MultiLayerDownListCombo = BI.inherit(BI.Widget, {
    _defaultConfig: function () {
        return BI.extend(BI.MultiLayerDownListCombo.superclass._defaultConfig.apply(this, arguments), {
            baseCls: "bi-multilayer-down-list-combo",
            height: 24,
            items: [],
            adjustLength: 0,
            direction: "bottom",
            trigger: "click",
            container: null,
            stopPropagation: false,
            el: {}
        });
    },

    _init: function () {
        BI.MultiLayerDownListCombo.superclass._init.apply(this, arguments);
        var self = this, o = this.options;
        this.popupview = BI.createWidget({
            type: "bi.multi_layer_down_list_popup",
            items: o.items,
            chooseType: o.chooseType,
            value: o.value
        });

        this.popupview.on(BI.MultiLayerDownListPopup.EVENT_CHANGE, function (value) {
            self.fireEvent(BI.MultiLayerDownListCombo.EVENT_CHANGE, value);
            self.downlistcombo.hideView();
        });

        this.popupview.on(BI.MultiLayerDownListPopup.EVENT_SON_VALUE_CHANGE, function (value, fatherValue) {
            self.fireEvent(BI.MultiLayerDownListCombo.EVENT_SON_VALUE_CHANGE, value, fatherValue);
            self.downlistcombo.hideView();
        });

        this.downlistcombo = BI.createWidget({
            element: this,
            type: "bi.combo",
            trigger: o.trigger,
            isNeedAdjustWidth: false,
            container: o.container,
            adjustLength: o.adjustLength,
            direction: o.direction,
            stopPropagation: o.stopPropagation,
            el: BI.createWidget(o.el, {
                type: "bi.icon_trigger",
                extraCls: o.iconCls ? o.iconCls : "pull-down-font",
                width: o.width,
                height: o.height
            }),
            popup: {
                el: this.popupview,
                stopPropagation: o.stopPropagation,
                maxHeight: 1000
            }
        });

        this.downlistcombo.on(BI.Combo.EVENT_BEFORE_POPUPVIEW, function () {
            self.fireEvent(BI.MultiLayerDownListCombo.EVENT_BEFORE_POPUPVIEW);
        });
    },

    hideView: function () {
        this.downlistcombo.hideView();
    },

    showView: function (e) {
        this.downlistcombo.showView(e);
    },

    populate: function (items) {
        this.popupview.populate(items);
    },

    setValue: function (v) {
        this.popupview.setValue(v);
    },
    getValue: function () {
        return this.popupview.getValue();
    }
});
BI.MultiLayerDownListCombo.EVENT_CHANGE = "EVENT_CHANGE";
BI.MultiLayerDownListCombo.EVENT_SON_VALUE_CHANGE = "EVENT_SON_VALUE_CHANGE";
BI.MultiLayerDownListCombo.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW";

BI.shortcut("bi.multi_layer_down_list_combo", BI.MultiLayerDownListCombo);<|endoftext|>


<commit_before>(function (angular) {

  'use strict';

  angular
    .module('ngResourceX', ['ngResource'])
    .provider('$resource_', $resource_);

  var forEach  = angular.forEach,
      extend   = angular.extend,
      copy     = angular.copy,
      isObject = angular.isObject,
      isString = angular.isString,
      isArray  = angular.isArray;

  /**
   * $resource utilities extension.
   * Adds extensibility and related resources to the Angular $resource module.
   * @class
   */
  function $resource_() {

    var provider = this;
    provider.$get = $get;

    //defaults holds all the configs
    provider.defaults = {
      'baseUrl': null,
      'relationPrefix': '_',
      'methods': {
        //'relationships': relationships
      },
      'statics': {
        'relate': relate,
        //'getFull': getFull,
        'relationships': relationships
      },
      'params': {},
      'actions': {
        'update': {
          'method': 'PATCH'
        },
        'get': {
          'method': 'GET'
        },
        'query': {
          'isArray': true,
          'method': 'GET'
        },
        'save': {
          'method': 'POST'
        },
        'options': {
          'method': 'OPTIONS'
        }
      }
    };

    $get.$inject = ['$resource', '$q'];
    /**
     * Provider $get function that returns the resource factory function.
     * @param $resource
     * @param $q
     * @returns {resourceFactory}
     */
    function $get($resource, $q) {

      /**
       * Wrapper for $resource. Creates a $resource and adds default methods/statics
       * @param url {string} URL of this $resource
       * @param params {Object} hash of parameters, same as $resource but modified to support ^ to map to parent properties.
       * @param actions {Object} hash of actions, see $resource documentation
       * @param options {Object} hash of options, see $resource documentation
       * @public
       * @returns {Object} $resource
       */
      function resourceFactory(url, params, actions, options) {

        var resource,
            resParams  = extend({}, copy(provider.defaults.params), params),
            resActions = extend({}, copy(provider.defaults.actions), actions);

        url = (provider.defaults.baseUrl || '') + url;

        resource = $resource(url, resParams, resActions, options);

        //Exposed methods
        resource.method = method;
        resource.static = staticMethod;

        init();

        return resource;

        ////////////////////////////////////////////////////////////

        function init() {

          //resolve our ^ parameters
          resolveParentParams(resParams, resource);
          addResponseTransformers(resActions, resource);

          //add default methods/statics
          forEach(provider.defaults.methods, function (func, key) {
            resource.method(key, func);
          });
          forEach(provider.defaults.statics, function (func, key) {
            resource.static(key, func);
          });

          resource.static('getFull', getFull);
          resource.$relationships = {};
        }

        /**
         * Does a GET but also resolves sub-resources
         * @param getParams {Object} standard $http GET params
         * @param relatedResourcesNames {string[]} names of the related resources to query for
         * @public
         * @instance
         */
        function getFull(getParams, relatedResourcesNames) {

          var deferred    = $q.defer(),
              prefix      = provider.defaults.relationPrefix,
              placeholder = extend(new this(), {
                '$promise': deferred.promise,
                '$ready': false
              });

          if (!relatedResourcesNames) {
            relatedResourcesNames = Object.keys(resource.$relationships);
          }

          deferred.promise = this.get(getParams).$promise.then(gotParentResults);

          function gotParentResults(resource) {

            //if this $resource has related resources
            if (resource.$relationships) {

              //go through the related resources we were asked to grab
              $q.all(forEach(relatedResourcesNames, function (name) {

                //run their queries and assign the prefixed results to the parent
                return resource.$relationships[name].query().$promise
                  .then(function gotRelatedResults(relatedResults) {
                    resource[prefix + name] = relatedResults;
                    return resource;
                  });
              }));
            }

          }

          return placeholder;
        }
      }

      return resourceFactory;
    }

    // DEFAULT EXTENSIONS
    ////////////////////////////////////////////////////////////

    /**
     * Adds a sub-resource to this $resource
     * @param name {string}
     * @param resource {Object}
     * @public
     * @static
     * @returns {$resource_.relate}
     */
    function relate(name, resource) {
      this.$relationships[name] = resource;
      return this;
    }

    /**
     * Sets/Gets related resources
     * @param [relationships] {Object} hash of related resource factories
     * @public
     * @static
     * @return {*}
     */
    function relationships(relationships) {
      this.$relationships = relationships;
      return this;
    }

    // EXTENDER METHODS
    ////////////////////////////////////////////////////////////

    /**
     * Adds a Method to this $resource. Methods operate on instantiated objects from your $resource.
     * @param arg1 {string|Object|Object[]} A key-value pair containing method name and definition OR an array of
     * key value pairs OR the method name (definition on the next param)
     * @param [func] {Function} if the first parameter is a string of the method name, this parameter will be used as
     * the definition
     * @public
     * @returns {_resource.method}
     */
    function method(arg1, func) {
      extender(this.prototype, arg1, func);
      return this;
    }

    /**
     * Adds a "static" method to this $resource. Statics operate on the non-instantiated version of your $resource
     * @param arg1 {string|Object|Object[]} A key-value pair containing method name and definition OR an array of
     * key value pairs OR the method name (definition on the next param)
     * @param [func] {Function} if the first parameter is a string of the method name, this parameter will be used as
     * the definition
     * @public
     * @returns {*}
     */
    function staticMethod(arg1, func) {
      extender(this, arg1, func);
      return this;
    }

    // PRIVATES
    ////////////////////////////////////////////////////////////

    /**
     * Helper function that extends a provided object with method arrays, hash or string/method value.
     * @param src Object to be extended
     * @param arg1 {string|Object|Object[]} A key-value pair containing method name and definition OR an array of
     * key value pairs OR the method name (definition on the next param)
     * @param [func] {Function} if @arg1 is a string of the method name, this parameter will be used as
     * the definition
     * @private
     */
    function extender(src, arg1, func) {
      if (isString(arg1)) {
        src[arg1] = func;
      }
      else if (isArray(arg1)) {
        forEach(arg1, function (method) {
          extend(src, method);
        });
      }
      else if (isObject(arg1)) {
        extend(src, arg1);
      }
    }

    /**
     * Special response transformer that first runs the user defined transformer and then our own to attach
     * our related resources.
     * @param actions {Object} actions hash to have response transformers added.
     * @param resource {Object}
     * @private
     * @returns {Object} actions hash with added response transformers.
     */
    function addResponseTransformers(actions, resource) {
      forEach(actions, function (action) {
        action.transformResponse = responseTransforms(action.transformResponse, resource);
      });

      return actions;
    }

    /**
     * Response transformer that first calls the user defined transform and then applies our own (which adds the
     * $relationships)
     * @param otherTransform {Function}
     * @param resource {Object}
     * @private
     * @returns {Function}
     */
    function responseTransforms(otherTransform, parentResource) {

      return function transformResponse(response) {
        if (otherTransform) {
          response = otherTransform(response);
        }
        else {
          response = (response ? angular.fromJson(response) : {});
        }

        if (isArray(response)) {
          forEach(response, function (entry) {
            attachRelations(entry, parentResource.$relationships);
          })
        }
        else {
          attachRelations(response, parentResource.$relationships);
        }

        return response;
      };

    }

    /**
     * Attaches related $resource_s to this instantiated $resource_.
     * @param entry {*}
     * @param relationships {Object} hash of related $resource_s to be added to this $resource_
     * @private
     */
    function attachRelations(entry, relationships) {

      if (!entry.$relationships) {
        entry.$relationships = {};
      }

      forEach(relationships, function (relatedResource, name) {
        var params = {};
        forEach(relatedResource.$$parentMap, function (map, key) {
          params[key] = lookupDottedPath(entry, map);
        });
        entry.$relationships[name] = relatedResource.bind(params);
      });

    }

    /**
     * Finds parameters that need to map to a parent $resource and attaches a function that will fetch the parent's
     * value for that param.
     * @param params {Object}
     * @param resource {Object}
     * @private
     * @returns {Object}
     */
    function resolveParentParams(params, resource) {

      var ret = {};
      resource.$$parentMap = {};

      forEach(params, function (param, key) {
        if (param && param.charAt && param.charAt(0) == '^') {
          resource.$$parentMap[key] = param.substr(1);
        }
        ret[key] = param;
      });

      params = ret;
      return params;
    }

    //FROM ANGULAR 1.3
    ////////////////////////////////////////////////////////////
    var MEMBER_NAME_REGEX = /^(\.[a-zA-Z_$][0-9a-zA-Z_$]*)+$/;

    function isValidDottedPath(path) {

      return (path != null && path !== '' && path !== 'hasOwnProperty' &&
      MEMBER_NAME_REGEX.test('.' + path));
    }

    function lookupDottedPath(obj, path) {
      if (!isValidDottedPath(path)) {
        throw new Error('Dotted member path is invalid.', path);
      }

      var keys = path.split('.');
      for (var i = 0, ii = keys.length; i < ii && obj !== undefined; i++) {
        var key = keys[i];
        obj = (obj !== null) ? obj[key] : undefined;
      }
      return obj;
    }

  }

})(angular);
<commit_msg>Fixed error raised when server unexpectedly returns a string message instead of JSON<commit_after>(function (angular) {

  'use strict';

  angular
    .module('ngResourceX', ['ngResource'])
    .provider('$resource_', $resource_);

  var forEach  = angular.forEach,
      extend   = angular.extend,
      copy     = angular.copy,
      isObject = angular.isObject,
      isString = angular.isString,
      isArray  = angular.isArray;

  /**
   * $resource utilities extension.
   * Adds extensibility and related resources to the Angular $resource module.
   * @class
   */
  function $resource_() {

    var provider = this;
    provider.$get = $get;

    //defaults holds all the configs
    provider.defaults = {
      'baseUrl': null,
      'relationPrefix': '_',
      'methods': {
        //'relationships': relationships
      },
      'statics': {
        'relate': relate,
        //'getFull': getFull,
        'relationships': relationships
      },
      'params': {},
      'actions': {
        'update': {
          'method': 'PATCH'
        },
        'get': {
          'method': 'GET'
        },
        'query': {
          'isArray': true,
          'method': 'GET'
        },
        'save': {
          'method': 'POST'
        },
        'options': {
          'method': 'OPTIONS'
        }
      }
    };

    $get.$inject = ['$resource', '$q'];
    /**
     * Provider $get function that returns the resource factory function.
     * @param $resource
     * @param $q
     * @returns {resourceFactory}
     */
    function $get($resource, $q) {

      /**
       * Wrapper for $resource. Creates a $resource and adds default methods/statics
       * @param url {string} URL of this $resource
       * @param params {Object} hash of parameters, same as $resource but modified to support ^ to map to parent properties.
       * @param actions {Object} hash of actions, see $resource documentation
       * @param options {Object} hash of options, see $resource documentation
       * @public
       * @returns {Object} $resource
       */
      function resourceFactory(url, params, actions, options) {

        var resource,
            resParams  = extend({}, copy(provider.defaults.params), params),
            resActions = extend({}, copy(provider.defaults.actions), actions);

        url = (provider.defaults.baseUrl || '') + url;

        resource = $resource(url, resParams, resActions, options);

        //Exposed methods
        resource.method = method;
        resource.static = staticMethod;

        init();

        return resource;

        ////////////////////////////////////////////////////////////

        function init() {

          //resolve our ^ parameters
          resolveParentParams(resParams, resource);
          addResponseTransformers(resActions, resource);

          //add default methods/statics
          forEach(provider.defaults.methods, function (func, key) {
            resource.method(key, func);
          });
          forEach(provider.defaults.statics, function (func, key) {
            resource.static(key, func);
          });

          resource.static('getFull', getFull);
          resource.$relationships = {};
        }

        /**
         * Does a GET but also resolves sub-resources
         * @param getParams {Object} standard $http GET params
         * @param relatedResourcesNames {string[]} names of the related resources to query for
         * @public
         * @instance
         */
        function getFull(getParams, relatedResourcesNames) {

          var deferred    = $q.defer(),
              prefix      = provider.defaults.relationPrefix,
              placeholder = extend(new this(), {
                '$promise': deferred.promise,
                '$ready': false
              });

          if (!relatedResourcesNames) {
            relatedResourcesNames = Object.keys(resource.$relationships);
          }

          deferred.promise = this.get(getParams).$promise.then(gotParentResults);

          function gotParentResults(resource) {

            //if this $resource has related resources
            if (resource.$relationships) {

              //go through the related resources we were asked to grab
              $q.all(forEach(relatedResourcesNames, function (name) {

                //run their queries and assign the prefixed results to the parent
                return resource.$relationships[name].query().$promise
                  .then(function gotRelatedResults(relatedResults) {
                    resource[prefix + name] = relatedResults;
                    return resource;
                  });
              }));
            }

          }

          return placeholder;
        }
      }

      return resourceFactory;
    }

    // DEFAULT EXTENSIONS
    ////////////////////////////////////////////////////////////

    /**
     * Adds a sub-resource to this $resource
     * @param name {string}
     * @param resource {Object}
     * @public
     * @static
     * @returns {$resource_.relate}
     */
    function relate(name, resource) {
      this.$relationships[name] = resource;
      return this;
    }

    /**
     * Sets/Gets related resources
     * @param [relationships] {Object} hash of related resource factories
     * @public
     * @static
     * @return {*}
     */
    function relationships(relationships) {
      this.$relationships = relationships;
      return this;
    }

    // EXTENDER METHODS
    ////////////////////////////////////////////////////////////

    /**
     * Adds a Method to this $resource. Methods operate on instantiated objects from your $resource.
     * @param arg1 {string|Object|Object[]} A key-value pair containing method name and definition OR an array of
     * key value pairs OR the method name (definition on the next param)
     * @param [func] {Function} if the first parameter is a string of the method name, this parameter will be used as
     * the definition
     * @public
     * @returns {_resource.method}
     */
    function method(arg1, func) {
      extender(this.prototype, arg1, func);
      return this;
    }

    /**
     * Adds a "static" method to this $resource. Statics operate on the non-instantiated version of your $resource
     * @param arg1 {string|Object|Object[]} A key-value pair containing method name and definition OR an array of
     * key value pairs OR the method name (definition on the next param)
     * @param [func] {Function} if the first parameter is a string of the method name, this parameter will be used as
     * the definition
     * @public
     * @returns {*}
     */
    function staticMethod(arg1, func) {
      extender(this, arg1, func);
      return this;
    }

    // PRIVATES
    ////////////////////////////////////////////////////////////

    /**
     * Helper function that extends a provided object with method arrays, hash or string/method value.
     * @param src Object to be extended
     * @param arg1 {string|Object|Object[]} A key-value pair containing method name and definition OR an array of
     * key value pairs OR the method name (definition on the next param)
     * @param [func] {Function} if @arg1 is a string of the method name, this parameter will be used as
     * the definition
     * @private
     */
    function extender(src, arg1, func) {
      if (isString(arg1)) {
        src[arg1] = func;
      }
      else if (isArray(arg1)) {
        forEach(arg1, function (method) {
          extend(src, method);
        });
      }
      else if (isObject(arg1)) {
        extend(src, arg1);
      }
    }

    /**
     * Special response transformer that first runs the user defined transformer and then our own to attach
     * our related resources.
     * @param actions {Object} actions hash to have response transformers added.
     * @param resource {Object}
     * @private
     * @returns {Object} actions hash with added response transformers.
     */
    function addResponseTransformers(actions, resource) {
      forEach(actions, function (action) {
        action.transformResponse = responseTransforms(action.transformResponse, resource);
      });

      return actions;
    }

    /**
     * Response transformer that first calls the user defined transform and then applies our own (which adds the
     * $relationships)
     * @param otherTransform {Function}
     * @param resource {Object}
     * @private
     * @returns {Function}
     */
    function responseTransforms(otherTransform, parentResource) {

      return function transformResponse(response) {
        if (otherTransform) {
          response = otherTransform(response);
        }
        else {
          response = (response ? angular.fromJson(response) : {});
        }

        if (isArray(response)) {
          forEach(response, function (entry) {
            attachRelations(entry, parentResource.$relationships);
          });
        }
        else if (isObject(response)) {
          attachRelations(response, parentResource.$relationships);
        }

        return response;
      };

    }

    /**
     * Attaches related $resource_s to this instantiated $resource_.
     * @param entry {*}
     * @param relationships {Object} hash of related $resource_s to be added to this $resource_
     * @private
     */
    function attachRelations(entry, relationships) {

      if (!entry.$relationships) {
        entry.$relationships = {};
      }

      forEach(relationships, function (relatedResource, name) {
        var params = {};
        forEach(relatedResource.$$parentMap, function (map, key) {
          params[key] = lookupDottedPath(entry, map);
        });
        entry.$relationships[name] = relatedResource.bind(params);
      });

    }

    /**
     * Finds parameters that need to map to a parent $resource and attaches a function that will fetch the parent's
     * value for that param.
     * @param params {Object}
     * @param resource {Object}
     * @private
     * @returns {Object}
     */
    function resolveParentParams(params, resource) {

      var ret = {};
      resource.$$parentMap = {};

      forEach(params, function (param, key) {
        if (param && param.charAt && param.charAt(0) == '^') {
          resource.$$parentMap[key] = param.substr(1);
        }
        ret[key] = param;
      });

      params = ret;
      return params;
    }

    //FROM ANGULAR 1.3
    ////////////////////////////////////////////////////////////
    var MEMBER_NAME_REGEX = /^(\.[a-zA-Z_$][0-9a-zA-Z_$]*)+$/;

    function isValidDottedPath(path) {

      return (path != null && path !== '' && path !== 'hasOwnProperty' &&
      MEMBER_NAME_REGEX.test('.' + path));
    }

    function lookupDottedPath(obj, path) {
      if (!isValidDottedPath(path)) {
        throw new Error('Dotted member path is invalid.', path);
      }

      var keys = path.split('.');
      for (var i = 0, ii = keys.length; i < ii && obj !== undefined; i++) {
        var key = keys[i];
        obj = (obj !== null) ? obj[key] : undefined;
      }
      return obj;
    }

  }

})(angular);
<|endoftext|>


<commit_before>
'use strict';

const electron = require('electron');
const app = require('app');
const BrowserWindow = require('browser-window');
const shortcut = require('global-shortcut');
const run = require('child_process');

var win = null;

// Quit when all windows are closed.
app.on('window-all-closed', function() {
	if (process.platform != 'darwin') {
		app.quit();
	}
});

app.on('ready', function() {

	win = new BrowserWindow({width: 1100,
		height: 750,
		icon: __dirname + '/icon.png',
		title: 'Curse',
		'autoHideMenuBar': true});
	win.loadURL('https://www.curse.com/home');

	shortcut.register('F5', function() {
		win.reload();
	});
	shortcut.register('F12', function() {
		win.toggleDevTools();
	});

	win.webContents.on('new-window', function(e, url) {
		e.preventDefault();
		run.execSync('xdg-open ' + url);
	});

	win.on('closed', function() {
		win = null;
	});

});

//Loading Screen

//var loadWindow = null;
//var connected = false;

// loadWindow = new BrowserWindow({width: 800,
// 	height: 480,
// 	icon: __dirname + '/icon.png',
// 	title: "Curse",
// 	'autoHideMenuBar': true,
// 	frame: false});
// loadWindow.setResizable(false);
// loadWindow.loadURL('file://' + __dirname + '/load.html');

//Alt External Link

// document.on('click', 'a[href^="http"]', function(event) {
// 	event.preventDefault();
// 	shell.openExternal(this.href);
// });
<commit_msg>Fixed on not logged in use case.<commit_after>
'use strict';

const electron = require('electron');
const app = require('app');
const BrowserWindow = require('browser-window');
const shortcut = require('global-shortcut');
const run = require('child_process');

var win = null;

// Quit when all windows are closed.
app.on('window-all-closed', function() {
	if (process.platform != 'darwin') {
		app.quit();
	}
});

app.on('ready', function() {

	win = new BrowserWindow({width: 1100,
		height: 750,
		icon: __dirname + '/icon.png',
		title: 'Curse',
		'autoHideMenuBar': true});
	win.loadURL('https://www.curse.com/login');

	shortcut.register('F5', function() {
		win.reload();
	});
	shortcut.register('F12', function() {
		win.toggleDevTools();
	});

	win.webContents.on('new-window', function(e, url) {
		e.preventDefault();
		run.execSync('xdg-open ' + url);
	});

	win.on('closed', function() {
		win = null;
	});

});

//Loading Screen

//var loadWindow = null;
//var connected = false;

// loadWindow = new BrowserWindow({width: 800,
// 	height: 480,
// 	icon: __dirname + '/icon.png',
// 	title: "Curse",
// 	'autoHideMenuBar': true,
// 	frame: false});
// loadWindow.setResizable(false);
// loadWindow.loadURL('file://' + __dirname + '/load.html');

//Alt External Link

// document.on('click', 'a[href^="http"]', function(event) {
// 	event.preventDefault();
// 	shell.openExternal(this.href);
// });
<|endoftext|>


<commit_before>/* eslint-disable react/no-danger */
import { PropTypes } from "react";
import Meta from "../../../components/shared/meta";
import Loading from "../../../components/@primitives/UI/loading";
import Forms from "../../../components/@primitives/UI/forms";

import GroupFinderFeedItem from "../../../components/content/feed-item-card";
import SideBySide from "../../../components/@primitives/UI/cards/SideBySideCard";

import GroupsILead from "../../../components/groups/groups-i-lead";
import KeywordSelect from "./Fields/Keyword";
import CampusSelect from "./Fields/Campus";
import Validate from "../../../util/validate";
import Svg from "../../../components/@primitives/UI/svg";

/* eslint-disable max-len */
const Layout = ({
  tags,
  tagOnClick,
  selectedTags,
  submitTags,
  canSearchTags,
  canSearchCampus,
  canSearchLocation,
  campuses,
  zip,
  selectedCampus,
  campusOnChange,
  searchQuery,
  findByQuery,
  inputOnChange,
  content,
  getLocation,
  iconFill,
}) =>

    {/* Meta */}
    <Meta
      title="Group Finder"
      description="Who are your people? We know it's important to be connected, but it's hard to build lasting friendships. What if taking one simple step changed everything? At NewSpring, we’re trying to make it easier for you to find people who share your interests. We know that when you get together with people and have fun, you’ll begin to grow into a strong community that serves and grows together. What if you are one step away from saying, “These are my people”?"
      image="https://dg0ddngxdz549.cloudfront.net/images/cached/images/remote/http_s3.amazonaws.com/ns.images/newspring/groups/groups.2x1_2000_1000_90_a789ae07aae81961.jpg"
    />

    <GroupsILead />

Find Your People

            Select your interests, campus, and location
to search for groups near you.

        <Forms.Form
          classes={[
            "soft",
            "one-whole",
            "two-thirds@portable",
            "one-half@anchored",
            "display-inline-block",
            "push-bottom",
          ]}
          submit={e => findByQuery(e)}
          action
        >
          <KeywordSelect
            tags={tags}
            searchQuery={searchQuery}
            tagOnClick={tagOnClick}
            selectedTags={selectedTags}
            onChange={e => inputOnChange(e)}
            iconName="tag"
            iconFill="#505050"
            iconTitle="Tag Icon"
          />
          <CampusSelect
            campuses={campuses}
            selectedCampus={selectedCampus}
            campusOnChange={campusOnChange}
            iconName="campus"
            iconFill="#505050"
            iconTitle="Campus Icon"
          />
          <Forms.Input
            inputClasses={"outlined--dotted outlined--light h6 flush-bottom text-black"}
            label={"Location (zip)"}
            defaultValue={zip}
            type="text"
            name="Zip"
            id="zip"
            validation={Validate.isLocationBasedZipCode}
            errorText="Please enter a valid zip code"
            iconName="location"
            iconFill="#505050"
            iconTitle="Location Icon"
          />

            <Svg name={"locate"} title={"Locate Icon"} fill={"iconFill"} />

              <button onClick={e => getLocation(e)} style={{ color: `${iconFill}` }}>
                Use my current location
              </button>

        </Forms.Form>

        {(() => {
          if (!tags.length) {
            return (

                <Loading />

            );
          }

          const classes = ["btn", "push-top@lap-and-up"];
          if (!canSearchTags && !canSearchCampus && !canSearchLocation) {
            classes.push("btn--disabled");
          }
          // XXX why can't I just pass in the function here?
          return (
            <button
              disabled={!canSearchTags && !canSearchCampus && !canSearchLocation}
              onClick={e => submitTags(e)}
              className={classes.join(" ")}
            >
              Let's Go!
            </button>
          );
        })()}

    {/* Group Stories */}

You Can't Do Life Alone

        {content &&
          content.map((entry, key) => {
            if (process.env.WEB) {
              return (
                <a
                  rel="noopener noreferrer"
                  target="_blank"
                  href={`https://newspring.cc/articles/${entry.meta.urlTitle}`}
                  className="plain grid__item one-whole"
                  key={key}
                >
                  <SideBySide
                    classes={["push-bottom@lap-and-up"]}
                    images={entry.content.images}
                    defaultImage={entry.content.images[0].url}
                  >

                      {entry.title}

                      Read more

                  </SideBySide>

              );
            }
            return (

                <GroupFinderFeedItem item={entry} />

            );
          })}

;
/* eslint-enable max-len */

Layout.propTypes = {
  tags: PropTypes.array.isRequired,
  campuses: PropTypes.array.isRequired,
  zip: PropTypes.string.isRequired,
  selectedCampus: PropTypes.object.isRequired,
  tagOnClick: PropTypes.func.isRequired,
  selectedTags: PropTypes.array.isRequired,
  submitTags: PropTypes.func.isRequired,
  campusOnChange: PropTypes.func.isRequired,
  canSearchTags: PropTypes.bool.isRequired,
  canSearchCampus: PropTypes.bool.isRequired,
  canSearchLocation: PropTypes.bool.isRequired,
  searchQuery: PropTypes.array.isRequired,
  findByQuery: PropTypes.func.isRequired,
  inputOnChange: PropTypes.func.isRequired,
  content: PropTypes.array.isRequired,
  getLocation: PropTypes.func.isRequired,
  iconFill: PropTypes.string.isRequired,
};

export default Layout;
<commit_msg>added back use my location coloring that somehow got deleted<commit_after>/* eslint-disable react/no-danger */
import { PropTypes } from "react";
import Meta from "../../../components/shared/meta";
import Loading from "../../../components/@primitives/UI/loading";
import Forms from "../../../components/@primitives/UI/forms";

import GroupFinderFeedItem from "../../../components/content/feed-item-card";
import SideBySide from "../../../components/@primitives/UI/cards/SideBySideCard";

import GroupsILead from "../../../components/groups/groups-i-lead";
import KeywordSelect from "./Fields/Keyword";
import CampusSelect from "./Fields/Campus";
import Validate from "../../../util/validate";
import Svg from "../../../components/@primitives/UI/svg";

/* eslint-disable max-len */
const Layout = ({
  tags,
  tagOnClick,
  selectedTags,
  submitTags,
  canSearchTags,
  canSearchCampus,
  canSearchLocation,
  campuses,
  zip,
  selectedCampus,
  campusOnChange,
  searchQuery,
  findByQuery,
  inputOnChange,
  content,
  getLocation,
  iconFill,
}) =>

    {/* Meta */}
    <Meta
      title="Group Finder"
      description="Who are your people? We know it's important to be connected, but it's hard to build lasting friendships. What if taking one simple step changed everything? At NewSpring, we’re trying to make it easier for you to find people who share your interests. We know that when you get together with people and have fun, you’ll begin to grow into a strong community that serves and grows together. What if you are one step away from saying, “These are my people”?"
      image="https://dg0ddngxdz549.cloudfront.net/images/cached/images/remote/http_s3.amazonaws.com/ns.images/newspring/groups/groups.2x1_2000_1000_90_a789ae07aae81961.jpg"
    />

    <GroupsILead />

Find Your People

            Select your interests, campus, and location
to search for groups near you.

        <Forms.Form
          classes={[
            "soft",
            "one-whole",
            "two-thirds@portable",
            "one-half@anchored",
            "display-inline-block",
            "push-bottom",
          ]}
          submit={e => findByQuery(e)}
          action
        >
          <KeywordSelect
            tags={tags}
            searchQuery={searchQuery}
            tagOnClick={tagOnClick}
            selectedTags={selectedTags}
            onChange={e => inputOnChange(e)}
            iconName="tag"
            iconFill="#505050"
            iconTitle="Tag Icon"
          />
          <CampusSelect
            campuses={campuses}
            selectedCampus={selectedCampus}
            campusOnChange={campusOnChange}
            iconName="campus"
            iconFill="#505050"
            iconTitle="Campus Icon"
          />
          <Forms.Input
            inputClasses={"outlined--dotted outlined--light h6 flush-bottom text-black"}
            label={"Location (zip)"}
            defaultValue={zip}
            type="text"
            name="Zip"
            id="zip"
            validation={Validate.isLocationBasedZipCode}
            errorText="Please enter a valid zip code"
            iconName="location"
            iconFill="#505050"
            iconTitle="Location Icon"
          />

            <Svg name={"locate"} title={"Locate Icon"} fill={iconFill} />

              <button onClick={e => getLocation(e)} style={{ color: `${iconFill}` }}>
                Use my current location
              </button>

        </Forms.Form>

        {(() => {
          if (!tags.length) {
            return (

                <Loading />

            );
          }

          const classes = ["btn", "push-top@lap-and-up"];
          if (!canSearchTags && !canSearchCampus && !canSearchLocation) {
            classes.push("btn--disabled");
          }
          // XXX why can't I just pass in the function here?
          return (
            <button
              disabled={!canSearchTags && !canSearchCampus && !canSearchLocation}
              onClick={e => submitTags(e)}
              className={classes.join(" ")}
            >
              Let's Go!
            </button>
          );
        })()}

    {/* Group Stories */}

You Can't Do Life Alone

        {content &&
          content.map((entry, key) => {
            if (process.env.WEB) {
              return (
                <a
                  rel="noopener noreferrer"
                  target="_blank"
                  href={`https://newspring.cc/articles/${entry.meta.urlTitle}`}
                  className="plain grid__item one-whole"
                  key={key}
                >
                  <SideBySide
                    classes={["push-bottom@lap-and-up"]}
                    images={entry.content.images}
                    defaultImage={entry.content.images[0].url}
                  >

                      {entry.title}

                      Read more

                  </SideBySide>

              );
            }
            return (

                <GroupFinderFeedItem item={entry} />

            );
          })}

;
/* eslint-enable max-len */

Layout.propTypes = {
  tags: PropTypes.array.isRequired,
  campuses: PropTypes.array.isRequired,
  zip: PropTypes.string.isRequired,
  selectedCampus: PropTypes.object.isRequired,
  tagOnClick: PropTypes.func.isRequired,
  selectedTags: PropTypes.array.isRequired,
  submitTags: PropTypes.func.isRequired,
  campusOnChange: PropTypes.func.isRequired,
  canSearchTags: PropTypes.bool.isRequired,
  canSearchCampus: PropTypes.bool.isRequired,
  canSearchLocation: PropTypes.bool.isRequired,
  searchQuery: PropTypes.array.isRequired,
  findByQuery: PropTypes.func.isRequired,
  inputOnChange: PropTypes.func.isRequired,
  content: PropTypes.array.isRequired,
  getLocation: PropTypes.func.isRequired,
  iconFill: PropTypes.string.isRequired,
};

export default Layout;
<|endoftext|>


<commit_before>const { World } = require('../index.js')
const { SimpleIndex } = require('./simple_index.js')
const { MemoizedQueryIndex } = require('./memoized_query_index.js')
const indexers = [SimpleIndex, MemoizedQueryIndex]

function getSize(it) {
	let num = 0
	for (let elem of it) {
		++num
	}
	return num
}

function has(it, target) {
	for (let elem of it) {
		if (elem.toString() == target.toString()) {
			return true
		}
	}
	return false
}

function testIndexers(callback) {
	return function() {
		for (let indexer of indexers) {
			callback(new World(indexer))
		}
	}
}

// TODO: Result of mocha/chai to jest upgrade, remove and use jest's "expect"
function assert(value) {
	expect(Boolean(value)).toBe(true)
}

module.exports = {
    getSize,
    has,
    testIndexers,
    assert
}<commit_msg>Arrow function<commit_after>const { World } = require('../index.js')
const { SimpleIndex } = require('./simple_index.js')
const { MemoizedQueryIndex } = require('./memoized_query_index.js')
const indexers = [SimpleIndex, MemoizedQueryIndex]

function getSize(it) {
	let num = 0
	for (let elem of it) {
		++num
	}
	return num
}

function has(it, target) {
	for (let elem of it) {
		if (elem.toString() == target.toString()) {
			return true
		}
	}
	return false
}

function testIndexers(callback) {
	return () => {
		for (let indexer of indexers) {
			callback(new World(indexer))
		}
	}
}

// TODO: Result of mocha/chai to jest upgrade, remove and use jest's "expect"
function assert(value) {
	expect(Boolean(value)).toBe(true)
}

module.exports = {
    getSize,
    has,
    testIndexers,
    assert
}<|endoftext|>